diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d165effc..0a5f45d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,6 +40,9 @@ jobs: - name: Pack MetadataGenerator.Tool run: dotnet pack src/MetadataGen/MetadataGenerator.Tool/MetadataGenerator.Tool.csproj --configuration Release --no-build --output ./nupkg + - name: Pack PermissionAnalyzer.Tool + run: dotnet pack src/PermissionAnalyzer/PermissionAnalyzer.Tool/PermissionAnalyzer.Tool.csproj --configuration Release --no-build --output ./nupkg + - name: Upload artifacts uses: actions/upload-artifact@v7 with: diff --git a/.github/workflows/release-automation.yml b/.github/workflows/release-automation.yml index 016db2de..7314fb90 100644 --- a/.github/workflows/release-automation.yml +++ b/.github/workflows/release-automation.yml @@ -6,6 +6,8 @@ on: - '.github/workflows/**' - 'Directory.Build.props' - 'src/MetadataGen/Directory.Build.props' + - 'src/PermissionAnalyzer/Directory.Build.props' + - 'src/PermissionAnalyzer/PermissionAnalyzer.Tool/PermissionAnalyzer.Tool.csproj' - 'src/MetadataGen/MetadataGenerator.Tool/MetadataGenerator.Tool.csproj' - 'src/XrmMockup365/XrmMockup365.csproj' push: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e773e547..2f79c663 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,7 @@ name: Release on: push: - tags: ['core-v*', 'metadata-v*'] + tags: ['core-v*', 'metadata-v*', 'permissions-v*'] workflow_dispatch: inputs: tag: @@ -15,7 +15,7 @@ on: permissions: contents: read concurrency: - group: release-product-${{ startsWith(inputs.tag || github.ref_name, 'metadata-v') && 'metadata' || 'core' }} + group: release-product-${{ startsWith(inputs.tag || github.ref_name, 'permissions-v') && 'permissions' || (startsWith(inputs.tag || github.ref_name, 'metadata-v') && 'metadata' || 'core') }} cancel-in-progress: false queue: max jobs: diff --git a/.github/workflows/setup-release-labels.yml b/.github/workflows/setup-release-labels.yml index 0532da90..e8a0e57e 100644 --- a/.github/workflows/setup-release-labels.yml +++ b/.github/workflows/setup-release-labels.yml @@ -18,7 +18,7 @@ jobs: GH_TOKEN: ${{ github.token }} run: | $config = Get-Content scripts/release/config.json -Raw | ConvertFrom-Json -AsHashtable - $labels = @('product:core', 'product:metadata', 'product:none') + @($config.categories.Keys) + $labels = @($config.products.Keys | ForEach-Object { "product:$_" }) + @('product:none') + @($config.categories.Keys) foreach ($label in $labels) { gh label create $label --color 5319e7 --description 'Release classification' --force --repo $env:GITHUB_REPOSITORY if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/AGENTS.md b/AGENTS.md index 48242d98..b8659ec0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,20 @@ plugins, workflows, custom APIs, and security can be tested without a live envir - `Workflow/`, including `WorkflowNode/`: workflow parsing and execution. - `XrmMockupSettings.cs`: authoritative settings types and defaults; inspect it before changing configuration or writing examples. +- `src/PermissionAnalyzer/`: static Dataverse privilege analysis shared by the SDK and + standalone `xrmmockup-permissions` tool. + - `PermissionAnalyzer.Abstractions/`: SDK-free models, scopes, results, and role coverage + (`netstandard2.0`). + - `PermissionAnalyzer.Core/`: Roslyn operation extraction, call graphs, cascades, and + manifest building (`netstandard2.0`). + - `PermissionAnalyzer.Workspace/`: opt-in .NET 10 source loading, configuration, and + metadata readers using private wire contracts. + - `PermissionAnalyzer.Tool/`: CLI frontend, packaged as `XrmMockup.PermissionAnalyzer`. + - `PermissionAnalyzer.Tests/`: snippets compiled in memory against the real SDK and + analyzer/loader regression tests. +- `src/ToolsCommon/`: shared CLI infrastructure, including console log formatting. + This and the permission libraries are internal/non-packable projects; owning product + packages ship their assemblies, not additional independently released NuGet packages. - `src/MetadataSkeleton/`: serialized metadata model shared by the engine and generators. - `src/MetadataGen/`: - `MetadataGenerator365/`: legacy .NET Framework generator, still bundled in the core package. @@ -51,13 +65,19 @@ dotnet test tests/XrmMockup365Test/XrmMockup365Test.csproj --framework net10.0 - # Metadata generator tests dotnet test src/MetadataGen/MetadataGenerator.Tool.Tests/MetadataGenerator.Tool.Tests.csproj + +# Permission analyzer tests +dotnet test src/PermissionAnalyzer/PermissionAnalyzer.Tests/PermissionAnalyzer.Tests.csproj + +# Permission SDK and legacy-plugin compatibility regressions +dotnet test tests/XrmMockup365Test/XrmMockup365Test.csproj --framework net10.0 --filter "FullyQualifiedName~TestPermissionAnalysis|FullyQualifiedName~TestPluginFrameworkCompatibility" ``` A focused `net10.0` run does not replace full Windows/multi-target validation. For code changes, run the affected tests first and the full suite when available; report any SDK, platform, restore, or test limitations rather than claiming validation passed. -Local package preview (PowerShell; builds and packs both products without publishing): +Local package preview (PowerShell; builds and packs all three products without publishing): ```powershell ./scripts/Pack-Local.ps1 @@ -65,7 +85,10 @@ Local package preview (PowerShell; builds and packs both products without publis For release automation changes, also run `./scripts/release/Test-Release.ps1` in PowerShell. See `RELEASE.md` for PR product/category classification and release -procedures. Do not hand-edit generated pending changelog sections or substitute +procedures. Product tags (`core-v*`, `metadata-v*`, `permissions-v*`) select one +package/symbol pair. `scripts/release/Prepare-Release.ps1` supplies its version and +notes through `.release/version.props`; ordinary builds use development versions. +Do not hand-edit generated pending changelog sections or substitute ad hoc version changes for the product-scoped release process. ## Test conventions @@ -83,6 +106,27 @@ ad hoc version changes for the product-scoped release process. - Add regression coverage in the affected suite. Metadata reader tests normally use `Fixtures/ReaderTestBase.cs` and `Fixtures/XrmMockupFactory.cs` in the tool test project. +## Static permission analysis + +Checks are explicit static privilege analysis, not scenario execution or proof of +record-level access. Do not add automatic checks during CRUD execution, invoke the CLI +from the SDK, or mutate mockup state when checking permissions. Preserve current +user/team role resolution, separate impersonated identities, and strict failures for +missing privileges or incomplete analysis. + +The .NET 10 SDK test project enables `XrmMockupEnablePermissionAnalysis` to copy the +shared library payload; it is loaded on demand in an isolated load context. The +lightweight contracts/check APIs remain available on .NET Framework, but source +loading requires .NET 10. Do not bundle either dotnet tool into Core or introduce +independently released permission-library packages. + +Analyzer output must remain deterministic: use ordinal comparers, sort collections, +and write `\n` line endings. See `docs/design/permission-analyzer.md` for the engine +design and `docs/permission-analysis-sdk.md` for SDK setup and boundaries. CLI +configuration uses `XrmMockup:Permissions`; consult +`src/PermissionAnalyzer/PermissionAnalyzer.Tool/README.md` rather than duplicating +its options here. + ## Metadata and live-environment boundaries Ordinary tests use checked-in metadata: `tests/XrmMockup365Test/Metadata/` and diff --git a/README.md b/README.md index 536dec9b..f687eaa2 100644 --- a/README.md +++ b/README.md @@ -32,3 +32,9 @@ for plugins compiled against .NET Framework 4.6.2. ## Releasing Maintainers: see [RELEASE.md](RELEASE.md) for PR labels, repository setup, and independent product releases. + +## Static permission analysis + +XrmMockup tests can explicitly check plugin or entity-operation privilege coverage using +`PermissionAnalysis` and `crm.CheckPermissions`. Workspace loading is opt-in; checks do not +execute scenarios or prove record-level access. See [the SDK guide](docs/permission-analysis-sdk.md). diff --git a/RELEASE.md b/RELEASE.md index 654d0088..59f9f86f 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,13 +1,13 @@ # Release process -Core and metadata releases are independent. A product tag chooses the package and its version; maintainers do not edit version headings or copy release descriptions manually. +Core, metadata and permission analyzer releases are independent. A product tag chooses the package and its version; maintainers do not edit version headings or copy release descriptions manually. ## Repository setup 1. Run **Set up release labels** from `master` to create the labels below. The initial implementation PR is excluded by the migration cutoff; all subsequent PRs must be classified before merging. 2. Use **PR release labels** and the normal .NET **ci** check for source PRs. If you configure required checks, replace any old **PR product labels**, **PR change category**, or **validate** requirements with **PR release labels**. Continue reviewing source PRs normally. The changelog writer runs the required **ci** check on its generated commit before pushing directly to `master`; do not remove or bypass that check. Other rules (such as requiring all changes through a PR, or additional required checks) can still prohibit this direct-write design; `contents: write` does not bypass them. 3. Ensure repository/organization Actions policy permits `GITHUB_TOKEN` to use `contents: write`, `actions: write`, and `statuses: write`. The changelog workflow uses these to push commits, dispatch CI, and publish the verified CI result as a commit status, plus `pull-requests: read` for metadata. **Allow GitHub Actions to create and approve pull requests is not needed**; leave it disabled. No App or PAT is needed. -4. Keep `NUGET_USER` and the NuGet Trusted Publishing policy configured for `release.yml` and the two packages. Restrict who can create release tags. +4. Keep `NUGET_USER` and the NuGet Trusted Publishing policy configured for `release.yml` and the three packages. Restrict who can create release tags. The separate **Release automation tests** workflow runs only for automation/workflow or packaging-configuration changes, or a manual dispatch. Do not make this path-filtered check globally required; if an old `release-automation` check was required, remove that requirement so unrelated PRs are not blocked. The single release-label check and .NET CI still run on every PR. @@ -25,7 +25,8 @@ Every PR to `master` needs a product classification: | --- | --- | | `product:core` | Core package changes | | `product:metadata` | Metadata tool changes | -| Both | Changes affecting both products | +| `product:permissions` | Permission analyzer tool changes | +| Multiple product labels | Changes affecting multiple products | | `product:none` | Repository maintenance; no release-note entry | `product:none` is exclusive: do not combine it with a product label. Use the affected product even if you are not planning an immediate release. @@ -64,6 +65,7 @@ The initial notes collection cutoff is the release-automation rollout merge, PR | --- | --- | | `core-v` | `XrmMockup365` | | `metadata-v` | `XrmMockup.MetadataGenerator` | +| `permissions-v` | `XrmMockup.PermissionAnalyzer` | Use semantic versions such as `1.20.3` or `1.3.0-rc.1`. No combined-version tags are used for new releases. @@ -90,9 +92,9 @@ The workflow checks out the exact source, builds/tests the solution, packs only ### Packaged changelogs and release notes -Release preparation replaces the selected product's `Unreleased` heading in the build checkout with the exact tag version and UTC release date in `d MMMM yyyy` format (for example, `4 November 2026`), using English month names. The other product's changelog and published history are left unchanged. This versioned section is saved as `.release/notes.md` and used for the GitHub release body, including prerelease suffixes. NuGet `PackageReleaseNotes` uses a separate `.release/package-notes.md` containing the latest 10 complete release sections (or all releases if fewer than 10 exist), followed by a link to the selected product's full changelog on GitHub. +Release preparation replaces the selected product's `Unreleased` heading in the build checkout with the exact tag version and UTC release date in `d MMMM yyyy` format (for example, `4 November 2026`), using English month names. The other products' changelogs and published history are left unchanged. This versioned section is saved as `.release/notes.md` and used for the GitHub release body, including prerelease suffixes. NuGet `PackageReleaseNotes` uses a separate `.release/package-notes.md` containing the latest 10 complete release sections (or all releases if fewer than 10 exist), followed by a link to the selected product's full changelog on GitHub. -The regular NuGet package includes the complete selected product changelog at its root: `RELEASE_NOTES.md` for `XrmMockup365`, or `CHANGELOG.md` for `XrmMockup.MetadataGenerator`. Before artifact upload and again before publication, validation checks that both package manifests contain the saved package release notes, that these match the latest 10 sections and full-history link from the packaged changelog, and that the changelog starts with the individual GitHub release section. Missing files, stale notes, and mismatched versions fail validation. Development/local preview packages retain their development notes and unreleased changelog; they are not publication artifacts. +The regular NuGet package includes the complete selected product changelog at its root: `RELEASE_NOTES.md` for `XrmMockup365`, or `CHANGELOG.md` for `XrmMockup.MetadataGenerator` and `XrmMockup.PermissionAnalyzer`. Before artifact upload and again before publication, validation checks that both package manifests contain the saved package release notes, that these match the latest 10 sections and full-history link from the packaged changelog, and that the changelog starts with the individual GitHub release section. Missing files, stale notes, and mismatched versions fail validation. Development/local preview packages retain their development notes and unreleased changelog; they are not publication artifacts. ## Failed release diff --git a/XrmMockup.slnx b/XrmMockup.slnx index 4cab627a..104c4c9c 100644 --- a/XrmMockup.slnx +++ b/XrmMockup.slnx @@ -19,6 +19,13 @@ + + + + + + + @@ -50,5 +57,6 @@ + diff --git a/docs/design/permission-analyzer-refactors.md b/docs/design/permission-analyzer-refactors.md new file mode 100644 index 00000000..259a320a --- /dev/null +++ b/docs/design/permission-analyzer-refactors.md @@ -0,0 +1,98 @@ +# Permission analyzer: candidate refactors + +Bigger refactors found in the pre-push review of the permission analyzer, most valuable first. +The simple fixes from that review are already in. Paths are relative to +`src/PermissionAnalyzer/PermissionAnalyzer.Core`. + +## Done + +1. **One shared Roslyn operation helper class.** `Extraction/Operations.cs` holds `Unwrap`, `Root`, + `IsLocal`, `LocalValues`, `Argument`, `GuidConstant`, the in-source check and the two framework checks + (now `IsSystemCall` and `IsFrameworkType`, as they mean different things); `SourcePaths.Declaration` + replaces the two `Declaration` copies. Services now also report locals changed by deconstruction or + compound assignment, as tables already did. +2. **Rules are applied once.** `Extraction/RuleApplication.cs` applies a rule to a request's members + through `IRequestMembers`; `TableResolver` reads them from code and `UserOperation` from `--operation`. + The copies had drifted less than the review first said: `--operation` treated a check's `When` as + possibly set, which the shared code now does explicitly. A rule without a check on a member now fires + its steps on its fixed table rather than the operation's table, and an access mask on any member is + reported, not just on the primary one. +3. **A common type for entry points and unreached methods.** `EntryPoint` and `MethodManifest` implement + `Model/IManifestSection.cs`, `Manifest.Sections` lists both in report order, and `CoverageReport.For` + takes a section. In the tool, `Output/PrivilegeNeed.cs` projects a section's table and global + requirements, filtered and with their coverage, for the text, JSON, SARIF and role change reports; + the `"global"` placeholder privilege is gone from `RoleChanges` and Markdown (`TableChange.IsGlobal`), + and only the text report still shows `global` in its privilege column. No separate `RequirementSet` + was needed. +4. **Message names.** The `Request` suffix is removed only from a request type's name + (`RequestRules.MessageOfType`). A message from code or a request name is matched exactly: to a rule named + as the message, or as its request type, configured rules first. A name a person writes in `As` or + `--operation` (`MessageNamed`) falls back to the message of a request type, so `CreateRequest` is still + `Create`. Steps fire on the message as called, so a custom API named `ctx_SubmitRequest` with a rule + runs its code. +5. **Speed.** A profile showed the suspected causes were cheap: resolving a request once per shape and + re-walking a method for each local cost well under a second on the sample. Most of the time went to + Roslyn binding the method bodies, one at a time, then to garbage collection. `SummaryExtractor.Extract` + now binds declarations in parallel, including within one large generated file, and builds the graph from + them in source order, so the output is unchanged. The tool uses server GC. FetchXML parsing turns away + text that can't be XML before it throws (every string argument is read as FetchXML), and member and type + ids, relative paths and logical names are cached. On the sample, extraction went from about 24s to 9s. +6. **`ManifestBuilder` split up.** `Analysis/PrivilegeResolver.cs` resolves the execute privileges of + custom API calls and the privileges request rules name. `Build` creates one from the entry points, so + the builder no longer keeps custom API state between builds, and it collects into one `ResolvedHits` + instead of passing three lists around. `Aggregate` only merges and sorts. `AddMetadataSteps` indexes + the plugin classes and the code steps by type, so matching metadata steps is no longer quadratic. +7. **Smaller structural items.** Message names are constants in `Model/Messages.cs`, and the SDK member + names the extraction reads in `Extraction/SdkNames.cs`. `Model/EntryPointIds.cs` builds every entry + point id and reads the function name and method id back out. `TableResolution` no longer changes once + made: `Union` returns a new one, so `Empty` is shared, and the one place that merged into a resolution + another node still held (a method's return tables) no longer does. `TableResolver` reads collections of + requests, records, entity references and lookups one way (`Filled` and `Added`), so a local + `EntityReferenceCollection` filled with `AddRange` or `Insert` is now read instead of unresolved. The text + writer's `Write` is split into a per-report class, the lines the text and Markdown reports share are in + `ReportText`, and `ManifestWriters.Create` picks the writer. Fixed on the way: a default object cut off + by the depth limit or a cycle is no longer memoized, `Cascades.Expand` keeps the steps a cascade fires, + `--operation` selects only its own operation, a type parameter is read as its constraints allow, and + `WithinTargets` keeps the columns, bypass and other parts of a value. + +## Shared with XrmMockup and the metadata tool + +Functionality duplicated between this tool, `xrmmockup-metadata` and XrmMockup365, found in the +critical review, for a later consolidation PR. Most valuable first; paths are relative to `src/`. + +1. **Privilege checks per request.** `PermissionAnalyzer.Core/Extraction/RequestRules.cs` restates by hand + what each XrmMockup handler's `CheckSecurity` checks, and the two disagree. XrmMockup skips checks the + rules list: Merge runs Associate and Disassociate through `handler.Execute` and writes with `db.Update` + (`MergeRequestHandler.cs`), QualifyLead writes the lead with `db.Update`, CloseIncident adds the + resolution with `db.Add`, the Win/Lose/Close messages write the parent through SetState, and ReviseQuote + reads with `db.GetEntity`. XrmMockup also checks things the rules miss: Read on the regarding record in + SendEmail, Create on `quotedetail` in ReviseQuote, Append/AppendTo in QualifyLead, and the record team + messages, which have no rule. It never checks a `prv*` privilege. `RequestRule.Enforced` records where + XrmMockup doesn't check, but nothing reads it. Proposal: an SDK-free netstandard2.0 library with the + per-message checks, used by the analyzer and by XrmMockup's handlers, or at least by a parity test. + Until then, mark the rules above `Enforced = false` and report it. +2. **Step and workflow trigger matching.** XrmMockup splits filtered attributes and + `triggeronupdateattributelist` on `,` without trimming or lowercasing (`XrmMockup365/Plugin/PluginTrigger.cs`, + `Workflow/WorkflowManager.cs`, `WorkflowConstructor.cs`), so `"name, telephone1"` never fires on + `telephone1`: a bug in XrmMockup. The analyzer trims and lowercases (`PluginStepLoader`, `WorkflowLoader`). + XrmMockup reads a workflow with an empty primary entity as any table and stores `runas` without applying + it; the analyzer drops the first and models the second. XrmMockup ignores the bypass parameters. Share + the parsing and the matching of message, table and columns, in `MetadataSkeleton` or the library in 1. +3. **Reading the metadata files.** `Metadata.xml`, `Workflows`, `SecurityRoles`, `PrivilegeCatalog.xml` and + the DataContract settings are spelled separately in `XrmMockup365/Internal/Utility.cs`, + `MetadataGenerator.Core/Services/DataContractMetadataSerializer.cs`, `MetadataGenerator365/Program.cs` + and `PermissionAnalyzer.Tool/Metadata/*Loader.cs`. The analyzer's `WorkflowLoader` lacks XrmMockup's + duplicate workflow id check, and `MetadataFileLoader` merges `*Metadata.xml` in ordinal order where XrmMockup + reads `Metadata.xml` first. Proposal: a `MetadataFiles` class in `MetadataSkeleton` with the names and + readers; the analyzer keeps its streaming partial reads on top. +4. **Security role model.** `RoleLoader` maps roles onto the analyzer's own `Privilege` and `PrivilegeDepth`, + and `RoleSet.Combine` repeats the max depth of `Security.GetPrincipalPrivilege`. The SDK-free enums are + deliberate; they could move to the library in 1. +5. **Tool configuration.** The two tools' `ConfigReader`s are near copies. The metadata tool's `--config` + ignores the file name and a missing file (`MetadataGenerator.Tool/Program.cs`); this tool honours both. + `-s` is a `.sln` path here and Dataverse solution names there, and the metadata tool's + `ShortCategoryConsoleFormatter` would shorten this tool's log prefix. Low value: a small shared source + package at most. + +Left alone on purpose: the legacy `MetadataGenerator365`, and the analyzer reading only parts of the +metadata instead of the whole `MetadataSkeleton`, for speed. diff --git a/docs/design/permission-analyzer.md b/docs/design/permission-analyzer.md new file mode 100644 index 00000000..b96a11f1 --- /dev/null +++ b/docs/design/permission-analyzer.md @@ -0,0 +1,1087 @@ +# Design: Permission Analyzer (`xrmmockup-permissions`) + +Status: Draft + +## 1. Problem + +Teams that test Dataverse code with XrmMockup still find missing security role privileges +late, usually as `Principal user is missing prvWriteX privilege` in a test or production +environment. The code already holds the answer: every `Create`, `Retrieve`, `Update`, +`Delete`, `Associate`, query and message names a table and implies a privilege. XrmMockup +already downloads the security roles (`Metadata/SecurityRoles/*.xml`) and the plugin step +registrations, so the "granted" side is also on disk. + +This tool analyzes a **consumer's codebase** (plugins, custom APIs, workflow activities, +Azure Functions and other callers of Dataverse, not XrmMockup itself) **statically**. It works +out which table privileges each entry point needs and compares them with the downloaded roles. + +## 2. Goals and non-goals + +Goals + +- Static analysis only. The analyzed code is not run and no Dataverse connection is needed. Loading + a project is a design-time build, so MSBuild targets and tasks (such as `Exec`) and source + generators from the project and its packages can run: the tool must only be pointed at code that + would be built anyway (§8). +- **Deterministic answers.** The same code and metadata always give the same output, with + stable ordering. Every requirement states why it is included (§5.2). Nothing is scored or + guessed: when the tool can't decide something, it includes it with the reason or lists it + as unresolved. The requirement set is therefore a superset of what the code can need, + never a sample. +- Cover plugin-style entry points (plugin steps, custom APIs, code activities) and + application-style entry points (Azure Functions, plus any method named as an entry point). +- Two questions, answered by one CLI command: + 1. **required**: exactly which privileges does action *A* need? + 2. **check**: does role *R* (or a set of roles) grant everything action *A* needs? Answered + whenever there are roles to check against, and failing the run with `--fail-on-missing`. +- Scope can be the **whole solution** or a single **query**: one operation that fires + plugins (e.g. `Update account`), one plugin step, one custom API or one Azure Function. +- Machine-readable output for CI, with an exit code that fails the build on gaps. + +Non-goals (for the first version) + +- Proving privilege *depth* (User/Business Unit/Parent-Child/Organization). Depth depends on + who owns the data at runtime, so it is reported, not verified (see §8). +- Field-level security, column security profiles and app/form access. +- Code outside C# (JavaScript web resources, Power Automate flows, Power Fx). +- Changing XrmMockup core. The tool is a separate dotnet tool, not a subcommand of + `xrmmockup-metadata`, which keeps Roslyn/MSBuild out of the metadata generator. + +## 3. Background: how XrmMockup decides what is required + +All privilege checks in mockup go through `Security.HasPermission` +(`src/XrmMockup365/Security.cs`). The request handlers define which checks each message +does, and the analyzer copies them so its answers match what a mockup test would enforce: + +| Message | Checks (from the handler) | +|---|---| +| Create | Create on target; per lookup set: Append on target, AppendTo (+ Read for UI role) on referenced record (`CreateRequestHandler.cs`) | +| Update | Write on target; per changed lookup: Append on target, AppendTo (+ Read for UI role) on referenced record (`UpdateRequestHandler.cs`) | +| Delete | Delete on target (`DeleteRequestHandler.cs`) | +| Retrieve | Read on target (`RetrieveRequestHandler.cs`) | +| RetrieveMultiple | Read on queried table and linked tables (`RetrieveMultipleRequestHandler.cs`) | +| Associate / Disassociate | Read + AppendTo on target, Read + Append on related records (`AssociateRequestHandler.cs`, `DisassociateRequestHandler.cs`) | +| Assign | Assign (+ Write) on target (`Security.CheckAssignPermission`) | +| Grant/ModifyAccess | Share on target, plus every right being shared (`Security.CheckSharingAccess`) | +| SendEmail | Read + Write on email, Read on regarding record | + +Two mockup shortcuts matter for the analyzer: + +- Calls made as the admin/SYSTEM user always pass, so operations that run as SYSTEM need no + role privilege (§5.4). +- A table that no role mentions at all always passes. The analyzer reports such tables as + `not-role-governed` instead of as required. + +## 4. Architecture + +A standalone .NET tool, kept out of XrmMockup core so consumers don't pull Roslyn/MSBuild +into their test projects. + +``` +src/PermissionAnalyzer/ + PermissionAnalyzer.Core/ netstandard2.0 + Model/ Privilege, Requirement, RoleDefinition, EntryPoint, Manifest + Discovery/ Entry-point discovery (plugins, custom APIs, activities, functions) + Extraction/ Roslyn operation extraction + table/attribute resolution + Rules/ Message → privilege rule table (mirrors mockup handlers) + Graph/ Call graph, DI resolution, plugin cascade expansion + Analysis/ Manifest building, coverage of RoleDefinitions + PermissionAnalyzer.Tool/ net10.0, PackAsTool, command `xrmmockup-permissions` + Metadata/ Role loading (MetadataSkeleton) → RoleDefinition + Workspace/ MSBuildWorkspace loading + PermissionAnalyzer.Tests/ xUnit; in-memory compilations against the real SDK + test metadata +``` + +- Core targets `netstandard2.0` (Roslyn APIs only, no MSBuild) so the same rules can later + ship as a `DiagnosticAnalyzer` package for IDE warnings, reading `Metadata/` via + `AdditionalFiles`. +- The Tool loads the consumer solution with `Microsoft.CodeAnalysis.Workspaces.MSBuild` + (`MSBuildWorkspace`) and passes compilations to Core. Since Roslyn 4.x the workspace builds + in an out-of-process build host, so `Microsoft.Build.Locator` isn't needed. A multi-targeted + project loads once per target framework; the duplicate findings merge into one. The report is a + conservative union across loaded frameworks, not a per-framework report. At a shared source + location, accesses and helper calls are deduplicated by their resolved facts, not just their + message or method: table arguments, service identities, generic arguments and the receiver's + creation all matter. Returned tables are unioned per shape, returned services are kept from + every compilation, and each constructor field keeps the union of its final service values. + Identical compilations add nothing; reversing their order does not change the output. +- Role and metadata files are read in the Tool with the shared `MetadataSkeleton.projitems` + (same `DataContractSerializer` format XrmMockup and the metadata generator use), so there is + no second definition of the model. The skeleton depends on the Dataverse SDK, so the Tool + converts each role to Core's SDK-free `RoleDefinition`, and Core stays `netstandard2.0` with + Roslyn as its only dependency. + +Pipeline: + +``` +solution ──► compile ──► discover entry points ──► extract operations per method + │ │ + ▼ ▼ + call graph + DI resolution ◄─────────┘ + │ + ▼ + expand plugin cascades (operation → triggered steps → their operations) + │ + ▼ + per-entry-point requirement set ──► role coverage (when roles are given) ──► report +``` + +## 5. Analysis + +### 5.1 Entry-point discovery + +| Kind | Detected by | Identity | +|---|---|---| +| Plugin step (XrmPluginCore) | `RegisterPluginStep(EventOperation, ExecutionStage, handler)` and `RegisterStep(…, service => …)` / `nameof(TService.Method)` in plugin constructors; `.AddFilteredAttributes`, `.AddImage` read as well | `T` → table, operation, stage, handler method | +| Plugin step (metadata) | `Metadata/` plugin registrations (`MetaPlugin`): message, entity, stage, `ImpersonatingUserId` | Matched to classes by type name (`MetaPlugin.AssemblyName`) and `PluginTypeAssemblyName`, falling back to the type name alone; runs-as from impersonation. For classes that also register steps in code, only the impersonation is taken, onto the matching step | +| Plain `IPlugin` | Classes implementing `IPlugin` with steps only in metadata | `Execute(IServiceProvider)` | +| Custom API | `RegisterCustomAPI(...)` (XrmPluginCore) and custom API metadata | API unique name | +| Code activity | `CodeActivity` subclasses (`Execute(CodeActivityContext)`) | Type name | +| Azure Function (isolated) | Methods with `[Function("Name")]` (`Microsoft.Azure.Functions.Worker`) | Function name + trigger attribute (`HttpTrigger`, `ServiceBusTrigger`, `TimerTrigger`, …) | +| Azure Function (in-process) | Methods with `[FunctionName("Name")]` (`Microsoft.Azure.WebJobs`) | Same | +| Explicit | `--entry "Namespace.Type.Method"` or `XrmMockup:Permissions:EntryPoints` (§6.3) | Fully qualified method | + +Discovery uses the semantic model (symbol names), not text matching, so aliases and partial +classes work. + +Entry point ids: `plugin:{type}:{message}:{table|any}:{stage}` for steps (`{type}` is the +reflection name, with `+` for nested types), `plugin:{type}` for a plain `IPlugin` without known +steps, `custom-api:{name}`, `activity:{type}`, `function:{assembly}/{name}` (function names are only +unique within an app) and `method:{method id}`. Abstract +plugin classes, and plugin classes that other plugin classes derive from, are not entry points +themselves. + +Methods with operations that no entry point reaches are reported under `unreached`, analyzed as if +called by the caller (assumed), so code called from outside the solution is never silently dropped. +When a project is analyzed rather than a solution, only the project's own methods are: the projects it references are analyzed for +what its entry points call, but a shared library also holds code for other apps, so its unreached +methods would only add privileges the project doesn't need. + +### 5.2 Operation extraction + +Within each method body, the extractor finds: + +- `IOrganizationService`, `IOrganizationServiceAsync`/`Async2` and `ServiceClient`: + `Create`, `Retrieve`, `RetrieveMultiple`, `Update`, `Delete`, `Associate`, `Disassociate`, + `Execute`, and their async forms. +- `Execute(new XxxRequest { … })`, where the request type is looked up in the rule table + (§5.3). Requests built locally and added to `ExecuteMultipleRequest.Requests` / + `ExecuteTransactionRequest.Requests` are unpacked. +- `OrganizationServiceContext` (including generated contexts): `CreateQuery()` / + `CreateQuery("x")`, query properties of a generated context (`AccountSet`, any property of type + `IQueryable` on a context) and LINQ joins (Read on each joined table), `AddObject`, + `UpdateObject`, `DeleteObject`, `AddLink`/`DeleteLink`/`AddRelatedObject` (Read and + Append/AppendTo, as `Associate`/`Disassociate`), and `Execute` (as on the service). *(Done.)* + - The privileges are reported where the change is queued, not at `SaveChanges`, which sends them + as one batch; the change's own line is the one to fix. A queued change fires its message's plugin + steps; a joined query fires `RetrieveMultiple` for its outer table only, as the platform runs one + query. `LoadProperty` reads through a relationship whose table isn't known, and is unresolved. + - A context runs as the service it is created with. Code in a context class (`this.DeleteObject`) + gets the service of the context it is called on, which a call passes on like an argument, so a + context held in a field or passed around keeps the identity of its creator. +- Known helper extension methods (XrmPluginCore and common framework helpers), listed as + rule entries instead of hard-coded. + +**Table resolution**, tried in this order: + +1. Early-bound type: `[EntityLogicalName("account")]` on `T` / the constructed type. +2. Constant strings: `new Entity("account")`, `new EntityReference("account", id)`, + `new QueryExpression("account")`, `LinkEntity` names, `EntityLogicalName` constants. +3. FetchXML: string literals and interpolated constants parsed for `entity` and + `link-entity` names. +4. Local data flow inside the method: locals, `readonly` fields, constructor-assigned fields + and `ToEntityReference()` on resolved entities. +5. Values returned by methods in the solution: each method summary records the tables of its + `return` statements, which can depend on its parameters, and a call resolves them with its own + arguments. Type arguments of generic methods are bound like parameters, so + `Get()` resolves `new T().LogicalName` or `Activator.CreateInstance()` inside it. + Type parameters of generic types are bound from the call's receiver: a call records the type + arguments of every generic type the receiver is or derives from, and each type records how its + generic ancestors' type arguments map to its own type parameters, so `Repository`, + `ContactRepository : Repository`, an override in `Logged : Repository` and a call + through `IRepository` all resolve `CreateQuery()` in the repository. A type + parameter no call binds stays unresolved. + Recursive helpers stop at the cycle, and the depth limit of the call graph applies. +6. Otherwise the operation is recorded as **Unresolved**, with its source location. It is + never dropped silently. + +**Attribute resolution** (for Append/AppendTo): lookups set on early-bound properties +(`ctx_AccountId = …`, column from `[AttributeLogicalName]`), indexers +(`entity["parentcustomerid"] = new EntityReference(…)`) and `Attributes.Add` are found. The +referenced table is resolved from the `EntityReference` value like any other table. When it +can't be, the lookup's targets from the entity metadata in `Metadata/` are used: the single +target of a simple lookup (basis `direct`), or every target of a polymorphic lookup (customer, +regarding) with basis `all-lookup-targets`. + +Each requirement records its **basis**, which says why it is in the set. A basis is a fact +about the code, not a likelihood: + +| Basis | Meaning | +|---|---| +| `direct` | Table and privilege resolved from the call itself (types, constants, local data flow) | +| `all-implementations` | Reached through an interface with no DI registration; every implementation is included (§5.5) | +| `all-lookup-targets` | Polymorphic lookup whose target can't be resolved; every allowed target is included | +| `filter-unknown` | Update step with filtered attributes, called where the set attributes can't be determined; the step is included (§5.6) | +| `execute-privilege` | Custom API execute privilege (§5.7) | + +Operations whose table can't be resolved at all are listed as `unresolved` with their +location and reason. They are kept apart from the requirement set, because a privilege +can't be named without a table. + +### 5.3 Message → privilege rules + +`Execute` is the generic way into Dataverse, so most real code reaches tables through request +objects as well as through the CRUD methods. The rules map each request type to the +privileges it needs. Phase 3.5 builds them. + +**Rule table.** The rules are data (a table in `RequestRules`), not code, so they can be extended and +overridden in `XrmMockup:Permissions:Rules` (§6.3). A rule names the message (`Assign` or the +request type `AssignRequest`; a message is matched to a rule by its own name first, ignoring case, so a +custom API named `ctx_ApproveRequest` isn't read by the rule for `ctx_Approve`), the member +that holds the target, and the privileges. Further checks can name another member or a fixed +table, and apply only when a boolean member is set (`when`). A rule can also expand into other +requests, the way XrmMockup's handlers call each other, or hold nested requests (`requests`). A +configured rule replaces the built-in rule for its message: + +```jsonc +{ "message": "AssignRequest", "target": "Target", "privileges": ["Assign", "Write"] }, +{ "message": "SetStateRequest", "target": "EntityMoniker", "privileges": ["Write"], "enforced": false }, +{ "message": "UpsertRequest", "as": ["CreateRequest", "UpdateRequest"] }, +{ "message": "CreateMultipleRequest", "targets": "Targets", "as": ["CreateRequest"] }, +{ "message": "ExecuteMultipleRequest", "requests": "Requests" }, +{ "message": "GrantAccessRequest", "target": "Target", "privileges": ["Share", "$PrincipalAccess.AccessMask"] }, +{ "message": "QualifyLeadRequest", "target": "LeadId", "privileges": ["Write"], + "checks": [{ "table": "account", "privileges": ["Create"], "when": "CreateAccount" }, /* contact, opportunity */] }, +{ "message": "BulkDeleteRequest", "globalPrivileges": ["prvBulkDelete"] }, +{ "message": "SendEmailRequest", "checks": [{ "table": "email", "privileges": ["Read", "Write"] }], + "assumption": "SendEmail sends the email as the calling user; sending it as another user needs prvSendAsUser" }, +{ "message": "WhoAmIRequest" } +``` + +`targets` makes the `as` rules' checks on `Target` apply to that member instead. `$Member` adds +the rights an `AccessRights` member grants; when it can't be read, the request is unresolved. A +`when` member is skipped only when it is a constant `false`. + +**Privileges by name.** `globalPrivileges` lists privileges a request needs that aren't a table +privilege on one of its members, such as `prvBulkDelete`. They follow the lookup of execute +privileges (§5.7): with a privilege catalog, a name not tied to a table becomes a +`GlobalRequirement`, a name tied to tables becomes its table privilege on each, and a name the +catalog doesn't have, or one tied to tables whose access right isn't a table privilege, is +unresolved ("the X request needs privilege 'P', which isn't in the privilege catalog"). Without +a catalog the name is taken as a privilege not tied to a table, so the built-in rules still work +with older metadata. `assumption` adds an assumption wherever the request is called, for what +depends on runtime data. Both are collected from the `as` rules too. + +Built-in rules, in groups: + +| Requests | Privileges | +|---|---| +| `CreateRequest`, `UpdateRequest`, `DeleteRequest`, `RetrieveRequest`, `RetrieveMultipleRequest`, `AssociateRequest`, `DisassociateRequest` | Same as the matching `IOrganizationService` method (§3) | +| `UpsertRequest` | Create and Write on the target (whether the record exists is a runtime fact) | +| `CreateMultipleRequest`, `UpdateMultipleRequest`, `UpsertMultipleRequest`, `DeleteMultipleRequest` | As the single request, per table in `Targets` (`EntityCollection.EntityName`, or the tables of the entities added) | +| `SetStateRequest`, `AssignRequest`, `GrantAccessRequest`, `ModifyAccessRequest`, `RevokeAccessRequest`, `QualifyLeadRequest` and the other messages XrmMockup implements | As listed in §3, or from the handler | +| `InitializeFileBlocksUploadRequest` / `InitializeFileBlocksDownloadRequest` | Write / Read on `Target` | +| `BulkDeleteRequest`; `ImportSolutionRequest`, `ImportSolutionAsyncRequest`; `ExportSolutionRequest`, `ExportSolutionAsyncRequest`; `PublishXmlRequest`, `PublishAllXmlRequest`; `ExecuteWorkflowRequest`; `DeleteRecordChangeHistoryRequest`; `DeleteAuditDataRequest` | `prvBulkDelete`; `prvImportCustomization`; `prvExportCustomization`; `prvPublishCustomization`; `prvWorkflowExecution`; `prvDeleteRecordChangeHistory`; `prvDeleteAuditPartitions` | +| `RetrieveAuditDetailsRequest`, `RetrieveAttributeChangeHistoryRequest`, `RetrieveRecordChangeHistoryRequest` | `prvReadRecordAuditHistory` and `prvReadAuditSummary` | +| `MergeRequest` | Read and Write on `Target`, and `prvMerge` | +| `SendEmailRequest` | Read and Write on email, with the assumption that it is sent as the caller: sending as another user needs `prvSendAsUser`, which depends on the email's `from` at runtime | +| Requests that need no table privilege: block transfers that continue an initialized one (`UploadBlockRequest`, `CommitFileBlocksUploadRequest`, `DownloadBlockRequest`), metadata (`RetrieveEntityRequest`, `RetrieveAttributeRequest`, `RetrieveMetadataChangesRequest`, …), `WhoAmIRequest`, `RetrieveVersionRequest`, `FetchXmlToQueryExpressionRequest` | None. Not reported as unresolved | + +**Privileges set by parameters and columns.** Some privileges depend on what a request sets, +not on its message, so they apply to every request: + +- `BypassCustomPluginExecution` (a request parameter) needs `prvBypassCustomPlugins`, and + `BypassBusinessLogicExecution` or `BypassBusinessLogicExecutionStepIds` need + `prvBypassCustomBusinessLogic`, unless the value is a constant `false`, `null` or empty. The + steps they skip are handled in §5.6. The `bypassPluginExecution` argument of the + `ServiceClient` CRUD extension methods isn't followed. +- `overriddencreatedon` set on a created record (direct calls, `CreateRequest`, `AddObject`) + needs `prvOverrideCreatedOnCreatedBy`, as Dataverse only honors it with that privilege. + +Privileges only the UI checks (such as exporting to Excel) are out of scope. Disabling a user +(`SetState` on `systemuser`) needs a further privilege for that table only, which a rule can't +express, so it isn't added. + +Rules follow Dataverse. Some checks Dataverse makes aren't enforced by XrmMockup's handlers +(for example `SetState` and the file block requests). Each rule records whether +XrmMockup enforces it, so the cross-check in §9 knows which differences are expected. + +**Requests through the code.** A request is tracked like a table (§5.5): through locals, +fields, parameters, return values and object initializers, so a request built in one method and +executed by a shared helper resolves at each call. Request collections +(`ExecuteMultipleRequest.Requests`, `ExecuteTransactionRequest.Requests`, and +`List` or similar passed between methods) hold everything added to them +with `Add`, `AddRange` or a collection initializer. Batching (`Chunk`, `Skip`/`Take`, `foreach`) +passes the contents through. The contents of a collection are the union of everything added to +it, so they over-approximate, like the rest of the call graph. + +**Requests without a rule** stay unresolved, with a reason that says which: + +- A request without a rule: "no rule for message 'Xxx'". It can be added in `Rules`. +- A request without a rule whose message is a custom API found in the code, a plugin step + message in the metadata, or has a publisher prefix (`ctx_Approve`): recognized as a + custom API call. Its execute privilege (§5.7) and the plugins it runs (§5.6) are + expanded when the code or the privilege catalog has the custom API. Otherwise it is listed + under `Not checked` as a custom API call, apart from the rest. +- A request whose type or table can't be determined: the reason, as for other operations. + +**Append and AppendTo** (also phase 3.5): Create, Update and their request forms (`Upsert`, +`*Multiple`, batches) add Append on the target and AppendTo on each table referenced by a +lookup that is set (see attribute resolution in §5.2), as XrmMockup checks them. `ownerid` and +`null` values are skipped, as in XrmMockup; the Read XrmMockup also checks for the UI role +doesn't apply to code. Lookups are followed through locals, collections, helpers and +parameters: a helper's parameter contributes the lookups set on it there, and the caller's. + +Only lookups set in code are seen. A record from a source the analysis can't follow (retrieved, +a field, a deconstruction) adds no requirement and no unresolved entry, because it usually +carries no changed lookups. A lookup value whose table can't be resolved, with no metadata for +its column, is reported as unresolved with the reason prefixed `lookup value:`. + +### 5.4 Execution identity ("runs as") + +Each operation is tagged with the principal it runs under, because this decides which roles +are checked: + +| Source of the service | Runs as | +|---|---| +| `factory.CreateOrganizationService(context.UserId)` / `localContext.OrganizationService` | **Caller** (or the step's impersonating user) | +| `factory.CreateOrganizationService(null)` / `OrganizationAdminService` | **System**: no role privilege needed, listed for information | +| `factory.CreateOrganizationService()` | **User** (by id) | +| Step with `ImpersonatingUserId` in metadata, or `.SetUserContext()` in XrmPluginCore | **User** (the impersonating user) replaces Caller for the step | +| Azure Function / app code (`ServiceClient`, injected `IOrganizationService`) | **Application user**, mapped to roles in `XrmMockup:Permissions:Principals` (§6.3); a `CallerId` assignment switches it to **Caller (impersonated)** | + +When the source can't be determined, the operation defaults to the entry point's caller (Caller +for plugins, custom APIs and activities; Application user for functions and `--entry` methods) and +is flagged as assumed, with the reason listed under `assumptions`. + +### 5.5 Call graph and dependency injection + +- An inter-procedural call graph is built over all source methods in the solution. An + entry point's requirements are the union of the operations reachable from it, with the + call path kept for reporting. +- The `IOrganizationService` passed as an argument, or stored in a field or constructor, + keeps its runs-as tag across calls. +- Interface calls (e.g. `IAccountService.HandleCreate` from `RegisterStep`, + or services injected into Azure Functions) are resolved by: + 1. DI registrations found in the solution (`services.AddScoped()`, XrmPluginCore + service registration, `Program.cs`/`Startup.cs` of function apps), then + 2. falling back to every implementation in the solution, with basis `all-implementations`. +- Recursion and cycles are handled by memoizing per-method summaries (requirement sets + plus parameter-dependent placeholders). + +### 5.6 Plugin cascade expansion + +A data operation that runs as the caller also fires the synchronous and asynchronous steps +registered for that message and table, and those run as the same caller unless +impersonated. Mockup does the same through `RequestExecutionPipeline`. The analyzer: + +1. Builds a step registry from code registrations (§5.1) merged with metadata registrations. +2. For each operation `(message, table, attributes)`, finds matching steps. For Update it + respects `FilteredAttributes` when the set attributes are known. When they aren't, the + step is included with basis `filter-unknown`. The set attributes are tracked like the + lookups set on a record: early-bound properties, indexers and `Attributes.Add` on a created + entity or a local, and on a parameter per call site. An entity from elsewhere, a computed + column name, or an entity passed to another method in the solution makes them unknown. +3. Adds the step's requirements under the **effective** identity (caller, or the step's + impersonating user), and expands the operations of the step in turn. Each step is expanded + once per identity and basis per entry point, which bounds the expansion and stops cycles, so + no depth limit is needed. + +The messages an operation fires are derived from the operation: + +- Direct calls fire their own message (`Create`, `Update`, `Delete`, `Retrieve`, + `RetrieveMultiple`, `Associate`, `Disassociate`; `CreateAndReturn` fires `Create`), on the + table of the call. `RetrieveMultiple` fires on the query's own table, not its linked tables. +- A request fires its rule's message and the messages it runs as (§5.3): `Upsert` fires + `Upsert`, `Create` and `Update`, and `CreateMultiple` fires `CreateMultiple` and `Create`. The + table is the one of the rule's first member check, usually `Target`. A request without a rule, + such as a custom API call, fires its message without a table, which matches steps and custom + APIs registered without a table. +- A step registered without a table matches every table. + +The fired step ids are listed per entry point under `triggers`, including steps fired by other +steps. + +This is what makes the "query a specific operation" mode useful: `Update account` gives the +full set of privileges a user needs for that update to succeed, including every plugin that +fires. + +**`--operation`.** A user operation is an entry point of kind `Operation` with no code. It is +evaluated as a request of its message whose first member check (usually `Target`) refers to the +given table, run as `Caller`. For a rule that names the table its steps fire on (`FiresOn`, such as +`opportunity` for `WinOpportunity`), the given table is that table, and every member check is on +another member: + +- The privileges of the member checks on that member are needed on the table, and those of + fixed-table checks on their table. Checks on other members (`RelatedEntities`), access masks + and nested requests can't be known and are reported as unresolved. A message without a rule + is reported as unresolved and fires its message on the table. +- It fires the rule's messages on the table, setting the `--attributes` columns when given, so + filtered Update steps match as for code (step 2). Without them, the columns set are unknown. +- For a message that creates or writes the table, each lookup among the attributes needs `Append` + on the table and `AppendTo` on its targets from the metadata. + +Its own hits are reported at the location `--operation` with no path, so a fired step's path +starts at the operation. + +**Cascades from Azure Functions and app code.** The same expansion applies to the operations an +Azure Function (or an `--entry` method) performs, so `--function ProcessOrder --role "Integration App"` +covers the plugins the function's +requests fire, not just the function's own calls. A request that fails in a plugin fails for the +function too. Specifics: + +- **Identity**: fired steps run as the identity of the operation that fired them: the + application user, or the impersonated user when the function sets `CallerId` (Dataverse then + runs plugins as that user). A step's own impersonation (`ImpersonatingUserId`, + `SetUserContext`) overrides it, as in step 3, and is checked against the `Users` mapping + (§6.3) instead of the function's roles. Operations that run as System still fire plugins; + those run as System unless impersonated. +- **Plugin code location**: function apps rarely reference their plugin projects, so the plugin + code isn't in the analyzed solution. The step registry still comes from `Metadata/`, and the + plugin code is added with a setting that lists extra solutions or projects to load for + cascades only (`XrmMockup:Permissions:PluginSolutions`, and a repeatable + `--plugin-solution ` that adds to it). Their own entry points, and their methods no entry + point reaches, aren't reported unless a scope selects them; code that is also in the analyzed + solution is reported as usual. Their files are shown relative to the analyzed solution + (`../Contoso.Plugins/AccountPlugin.cs`), and `ExcludeProjects` path patterns match relative to + their own solution. +- **Steps without code**: a metadata step whose plugin type isn't in any loaded code is listed + as a finding ("step `X` fires but its code wasn't analyzed"), so missing plugin code is never + silently treated as needing nothing. +- **Unresolved operations**: an operation whose table is unknown fires the steps registered without + a table only. The steps on a table are reported as one unresolved finding per operation ("may fire + any of N steps") rather than included: in a real solution every step of the message, and + everything those fire, would be most of the solution, which says nothing about the operation. + Tables are resolved where they can be first: the record `Retrieve` returns is of the table it + asks for, an early-bound lookup property refers to its targets in the metadata, and + `PrimaryEntityName` in a plugin step is the step's table. +- **Output**: plugin requirements keep the full path, from the function through the request to + the step and into the plugin code (`ProcessOrder → OrderService.Submit → Create + ctx_order → plugin:Contoso.OrderPostPlugin:Create:ctx_order:PostOperation → …`), and the + entry point lists the steps it fires under `triggers` (§7). Asynchronous steps are included, + since they need the same privileges even though their failure doesn't fail the request. +- **Bypassed steps**: a request with `BypassCustomPluginExecution` set to a constant `true` + doesn't run synchronous steps, and one with `BypassBusinessLogicExecution` doesn't run the + synchronous (`CustomSync`) or asynchronous (`CustomAsync`) steps it names; with several values, + only what all of them skip. A step's mode comes from `.SetExecutionMode(ExecutionMode.Asynchronous)` + on the registration or `Mode` in the metadata. A value set at runtime needs the privilege (§5.3) + but skips nothing. `BypassBusinessLogicExecutionStepIds` skips nothing either, because the + analysis doesn't know step ids. A custom API's own code is never skipped. + +**Workflows.** The workflows in `Metadata/Workflows` that run automatically (category workflow, +with a table, and on create, on delete or on an update of listed columns, as mockup reads them) +fire like steps without code. A real-time workflow runs as the caller or its owner (`runas`), a +background workflow as its owner, and the bypass parameters skip them like steps of the same mode. +Their steps (XAML) aren't analyzed, so each fired workflow is an unresolved finding ("fires +real-time workflow 'X', whose steps aren't analyzed"), counted as `unresolvedWorkflow`, which +`--strict` fails on. Without this, a workflow's needs would be silently missed. Analyzing its +create and update steps, which mockup already parses, with the same rules is a later extension. + +### 5.7 Custom API execute privileges + +A custom API can require an execute privilege (`ExecutePrivilegeName`). That must be an +existing privilege, so it maps to role data exactly. Built in phase 5: + +- **Where it comes from**: the XrmPluginCore registration in code, where the last call wins: + - `.WithExecutePrivilege(Privilege.Read)`: the table of `T` and the privilege, directly. + - `.WithExecutePrivilege("ctx_Order", Privilege.Write)`: the schema name lowercased (a + schema name is the logical name with another casing) and the privilege, directly. + - `.WithExecutePrivilegeName("prvReadctx_Order")`: a name to look up. + + Otherwise it comes from the privilege catalog, which lists every custom API in the + environment with its execute privilege, if any. +- **Privilege catalog**: the metadata generator writes `Metadata/PrivilegeCatalog.xml` + (`PrivilegeCatalog` in `MetadataSkeleton`). It holds every privilege (`name`, `privilegeid`, + `accessright` and the sorted tables from `privilegeobjecttypecodes`) and every custom API + (`uniquename` and `executeprivilegename`, `null` when it has none). XrmMockup doesn't read it. + Looking a name up gives `(tables, AccessRight)`. For example, `prvWriteAccount` gives + `(account, Write)`, which is checked against roles like any other requirement (basis + `execute-privilege`). Names are matched ignoring case. +- **Privileges not tied to a table** (`objecttypecode = none`, e.g. `prvExportToExcel`): the + generator keeps these on the role in `SecurityRole.GlobalPrivileges`, by name, separate from + the per-table `Privileges` dictionary so mockup's table checks are unaffected. They are + `null` in metadata generated before, which isn't the same as granting none. They become a + `GlobalRequirement` on the entry point and are checked by name (§6.2). The legacy + `MetadataGenerator365` is unchanged. +- **Calling a custom API**: `Execute(new OrganizationRequest("ctx_DoThing"))` or a generated + request class needs the execute privilege under the identity of the call, plus the API + implementation's own requirements, expanded the same way as plugin cascades (§5.6). The + custom API's own entry point also needs its execute privilege, under `Caller`, with the + registration as its source. +- **What can't be looked up** stays unresolved, with a reason starting "custom API 'X'": + - no catalog: "needs execute privilege 'P', which needs a privilege catalog + (PrivilegeCatalog.xml) to look up"; + - a name the catalog doesn't have: "… which isn't in the privilege catalog"; + - an access right that isn't a table privilege, on a privilege tied to tables: "… whose + access right isn't a table privilege"; + - a name computed at runtime: "needs an execute privilege set at runtime"; + - a custom API that is only in the catalog: "is called; its code isn't analyzed"; + - a custom API that neither the code nor the catalog has: "is called; its code and + execute privilege are unknown". + +Execute privileges are never derived from naming conventions. + +## 6. CLI + +``` +xrmmockup-permissions [scope] [roles] [--fail-on-missing | --strict] [options] +``` + +There is one command, the root command, like `xrmmockup-metadata`. It always lists what the code needs +and checks it against roles when there are any (§6.2). Options: + +| Option | Meaning | +|---|---| +| `--solution ` / `-s` | Solution (`.sln`/`.slnx`) or project (`.csproj`, with the projects it references) to analyze (default: `XrmMockup:Permissions:Solution`, else the single `.sln`/`.slnx` in the current directory) | +| `--metadata ` / `-m` | XrmMockup `Metadata/` folder (security roles, plugin steps, workflows, entity metadata). Default: `XrmMockup:Permissions:MetadataDirectory`, else `XrmMockup:Metadata:OutputDirectory`, else `./Metadata` next to the configuration file when it exists | +| `--exclude ` / `-x` | Leave out projects matching the pattern; repeatable, adds to `XrmMockup:Permissions:ExcludeProjects` | +| `--plugin-solution ` | A solution or project with plugin code the analyzed code fires but doesn't include, loaded for plugin cascades only; repeatable, adds to `XrmMockup:Permissions:PluginSolutions` | +| `--config ` / `-c` | Path to `appsettings.json`, same as `xrmmockup-metadata` (§6.3) | +| `--format text\|json\|markdown\|sarif` / `-f` | Output format (default `text`; `markdown` for pull request comments and job summaries, `sarif` for GitHub code scanning; phase 6, §10) | +| `--output ` / `-o` | Write report to file | +| `--detail minimal\|compact\|normal\|detailed\|full` / `-d` | How much of the text report to show (phase 5.5, §10): `minimal` (default) shows only the privileges to change per set of roles, `compact` adds the entry points that need them, `normal` shows what needs attention with its sources, `detailed` adds what is granted, `full` adds every source and call path | +| `--table `, `--privilege `, `--runs-as `, `--basis ` | Only show requirements on the given tables, with the given privileges, identities or bases (§5.2); filtering is applied after analysis, so it never changes what is computed | +| `--role ` / `-r`, `--caller-role ` | Roles to check against (§6.2); repeatable | +| `--no-roles` | Don't check against the `Principals` and `Users` settings (§6.2) | +| `--fail-on-missing`, `--strict` | Exit with `1` when a privilege is missing, and with `--strict` also when something couldn't be checked (§6.2) | + +### 6.1 Scope selectors + +Exactly one, or none for the whole solution: + +| Selector | Example | Meaning | +|---|---|---| +| *(none)* | | Every discovered entry point | +| `--operation " "` | `--operation "Update account" --attributes accountnumber` | A user operation, plus every plugin it fires (§5.6) | +| `--plugin [:[:]]` | `--plugin AccountPostPlugin:Update` | One plugin, or one of its steps | +| `--custom-api ` | `--custom-api ctx_DoThing` | One custom API | +| `--function ` | `--function ProcessOrder` | One Azure Function (by function name) | +| `--entry ` | `--entry Contoso.Sync.Importer.Run` | Any method as an entry point | + +### 6.2 Roles and exit codes + +``` +xrmmockup-permissions # every entry point +xrmmockup-permissions --operation "Create contact" +xrmmockup-permissions --role "Salesperson" --operation "Update account" +xrmmockup-permissions --role "Salesperson" --role "Marketing" --plugin AccountPostPlugin +xrmmockup-permissions --role "Integration App" --function ProcessOrder --fail-on-missing +``` + +- **Roles to check against**: `--role` and `--caller-role` (repeatable), else the `Principals` + and `Users` settings (§6.3) that match the analyzed code. Without any, or with `--no-roles`, + the output is the requirement manifest per entry point (table → privileges, identity, basis, + locations). It contains no role data, so it depends only on code and metadata: the artifact to + commit or diff in CI. `--no-roles` can't be combined with the role options, `--fail-on-missing` + or `--strict`. +- **Exit code**: `0` unless `--fail-on-missing` or `--strict` is given, so the report can be read + without failing anything. With `--fail-on-missing`, `1` when a privilege is missing; `--strict` + implies it and also fails on what couldn't be checked (below). Errors exit `2`. Failing is + opt-in, so a CI job has to pass the flag; in return, the flag with nothing to check against is an + error, so a misconfigured job can't pass by checking nothing. +- Repeating `--role` combines roles (union of privileges, highest depth wins), the same way + mockup combines a principal's roles in `Security.JoinPrivileges`. +- **Any depth counts**: a privilege is covered when the combined roles grant it at any depth + (`User`, `BusinessUnit`, `ParentChildBusinessUnit` or `Organization`). The granted depth is + shown next to the requirement, but it doesn't affect the result or the exit code (§8). A + minimum-depth option is a possible future feature (§10). +- With no scope and an app-user mapping in `appsettings.json`, each Azure Function is checked against + its configured roles. +- Each requirement is checked against the roles of the identity it runs as (§5.4): + + | Runs as | Checked against | + |---|---| + | Caller | `--role` | + | Application user | `--role`, else `Principals` for the function (`/`), else for its app (``) | + | User | `Users` for that user id; otherwise "not checked: runs as user X" | + | Caller (impersonated) | `--caller-role` (repeatable); otherwise "not checked" | + | System | Nothing; listed for information | + + `--role` replaces `Principals`. Requirements with an assumed identity are checked like the + rest and keep their `(assumed)` label, so a missing privilege on one fails `--fail-on-missing`. +- **Impersonation**: a call made with `CallerId` set runs with the privileges of the + impersonated user, so its requirements are checked against `--caller-role`. The identity that + sets `CallerId` (the application user, for app code) must also hold + `prvActOnBehalfOfAnotherUser`. Every operation that runs as `ImpersonatedCaller` adds it as a + global requirement of that identity, with the same sources. Without `--caller-role`, the idea of + stopping at the impersonated call and listing it for a separate check of the calling user is + described in §10. +- **Privileges not tied to a table** (§5.7) are checked by name against the roles' global + privileges. In order: SYSTEM needs nothing, an identity without roles is not checked, roles + from metadata without global privileges make it `unverifiable` (only `--strict` fails on that), + then granted, suppressed or missing. +- With `--fail-on-missing`, no `--role` or `--caller-role`, and no `Principals` or `Users` entry + that matches the analyzed code, there is nothing to check against and the run exits with `2`. + Without the flag it lists what the code needs. A role name that isn't in `Metadata/`, given or + configured, is an error (exit `2`) that suggests the closest names. +- `Suppress` entries (§6.3) turn a missing privilege into "suppressed", which doesn't fail. + A table no role in `Metadata/` mentions counts as covered, because XrmMockup doesn't check it. +- `--strict` fails like `--fail-on-missing`, and also on unresolved operations, identities with no roles to check against, + unverifiable privileges and entry points or methods whose analysis stopped at the call limit (`Evaluator.MaxVisits`). +- Output: granted / missing per `(table, privilege)` with the depth the role grants, the + source location and the call path. With `--fail-on-missing`, exit code `0` = covered, `1` = + missing privileges; `2` is always an analysis error. Unresolved operations alone don't fail + the run unless `--strict` is set. + +``` +Update account (as caller) — role "Salesperson" + ✔ account Write [User] (request) + ✔ account Read [User] AccountPostPlugin → Execute AccountPostPlugin.cs:37 + ✘ ctx_parent Create AccountPostPlugin → Execute AccountPostPlugin.cs:37 + ✘ ctx_parent Append AccountPostPlugin → Execute AccountPostPlugin.cs:37 (ctx_accountid) + ✔ account AppendTo [User] AccountPostPlugin → Execute AccountPostPlugin.cs:37 + ? Update AccountHelper.Touch AccountHelper.cs:12 table name from parameter 'logicalName' +Result: 2 missing, 1 unresolved +``` + +As built in phase 3, the text output lists the roles per identity under each entry point +(`roles for Caller: Salesperson (--role)`) and marks each requirement `✔` (granted, with the +depth, or on a table no role governs), `✘` (missing), `-` (suppressed) or `·` (not checked, or +SYSTEM, or unverifiable). A privilege not tied to a table has its name in the table column and +`global` as the privilege, and is also listed under `Privileges not tied to a table`. + +The `Result:` line only counts what was checked. A `Missing privileges:` list follows it, then a +`Not checked:` line, so a pass isn't read as proof that the roles are enough: + +``` +6 entry points, 2 unreached methods, 9 tables, 14 table privileges (31 requirements counted per entry point and method), 5 unresolved +Result: 27 granted, 4 missing +Missing privileges: + ✘ ctx_orderline Create ApplicationUser Integration App (--role) in function:Contoso.Functions/ProcessOrder, function:Contoso.Functions/ResubmitOrder + ✘ ctx_orderline Read ApplicationUser Integration App (--role) in function:Contoso.Functions/GetOrder +Not checked: 5 unresolved operations (1 request without a rule, 3 custom API calls, 1 with an unknown table or request) +``` + +`Missing privileges` merges the missing requirements by table, privilege, identity and roles, +so each gap is listed once with every entry point that needs it. `Not checked` lists unresolved +operations (requests with no rule and custom API calls apart from operations with an unknown +table or request, §5.3), requirements whose identity has no roles, and privileges not tied to a +table that are unverifiable because the role metadata predates them, and the entry points or methods whose analysis +stopped at the call limit. The line is left out when everything was checked. When nothing is missing but something wasn't +checked, `--fail-on-missing` exits `0` with a warning, and `--strict` fails. + +Finding which downloaded roles, or smallest combination of roles, would cover a requirement +is deferred (§10). + +### 6.3 Configuration (`appsettings.json`) + +The tool reads the same `appsettings.json` as `xrmmockup-metadata` and follows its +conventions: + +- Sources, later ones winning: `appsettings.json`, `appsettings.{DOTNET_ENVIRONMENT}.json`, + environment variables, then command-line options. This is the metadata tool's + `ConfigReader` order, which the permissions tool reuses. +- `--config ` / `-c` points at the file; by default it is read from the current directory. +- Settings live under `XrmMockup:Permissions`, next to the existing `XrmMockup:Metadata` + section. Each setting is a property on a `PermissionsConfiguration` record + (`SectionPath = "XrmMockup:Permissions"`), like `MetadataConfiguration`. +- The metadata folder is, in order: `--metadata`, `XrmMockup:Permissions:MetadataDirectory`, + `XrmMockup:Metadata:OutputDirectory`, then `./Metadata` when it exists. A project that already + generates metadata needs no extra path setting. Configured paths are relative to the config + file; command-line paths are relative to the current directory. +- Without `--solution` or `Solution`, the tool uses the single `*.sln`/`*.slnx` in + the current directory. +- The tool makes no Dataverse connection (a future `--user` would be the exception, + §10), so it ignores `DataverseUrl` and + `DataverseCredentialType`. + +The section holds what static analysis can't know: + +```jsonc +{ + "DataverseUrl": "https://your-org.crm4.dynamics.com", + "XrmMockup": { + "Metadata": { + "OutputDirectory": "./Metadata", + "Solutions": ["MySolution"] + }, + "Permissions": { + "Solution": "./src/Contoso.sln", + "MetadataDirectory": "./tests/Metadata", // optional, see above + // Projects to leave out, e.g. tests. Wildcards; a pattern with '/' matches the solution-relative path. + // --exclude/-x adds to these. + "ExcludeProjects": ["*.Tests", "tests/*"], + // Plugin code the analyzed code fires but doesn't include, for cascades only (§5.6). + // --plugin-solution adds to these. + "PluginSolutions": ["../Contoso.Plugins/Contoso.Plugins.sln"], + // Azure Function apps / app code: which roles their application user has + "Principals": { + "Contoso.Functions": { "Roles": ["Integration App"] }, + "Contoso.Functions/ProcessOrder": { "Roles": ["Integration App", "Order Processor"] } + }, + // Impersonating users from plugin step metadata and background workflow owners, by systemuserid + // (any GUID format; anything else is an error), mapped to roles + "Users": { + "00000000-0000-0000-0000-000000000001": { "Name": "svc-plugins", "Roles": ["Plugin Service"] } + }, + "EntryPoints": ["Contoso.Sync.Importer.Run"], + "Rules": [ /* extra or overridden message rules, §5.3 */ ], + "Suppress": [ + { "Table": "ctx_auditlog", "Privilege": "Create", "Reason": "Created by SYSTEM via helper" }, + { "Privilege": "prvActOnBehalfOfAnotherUser", "Reason": "Granted outside the roles" } // no Table: by name + ] + } + } +} +``` + +A `Principals` key or `Users` id that matches nothing analyzed is logged as a warning, like an +`--exclude` pattern that matches no project. The warnings are left out when an entry point option +narrows the analysis, and for `Principals` when `--role` replaces them. + +Command-line options override the matching setting, as in the metadata tool. For example, +`--solution` overrides `Solution` and `--metadata` overrides the metadata folder. + +## 7. Output model + +```jsonc +{ + "entryPoints": [{ + "id": "plugin:Contoso.AccountPostPlugin:Update:account:PostOperation", + "kind": "PluginStep", + "type": "Contoso.AccountPostPlugin", "assembly": "Contoso.Plugins", + "trigger": { "message": "Update", "table": "account", "stage": "PostOperation" }, + "impersonatingUserId": "…", // only when the step impersonates + "declaration": { "file": "Plugins/AccountPostPlugin.cs", "line": 13, "column": 13 }, + "requirements": [{ + "table": "ctx_parent", "privilege": "Create", + "runsAs": "Caller", "basis": "direct", // "userId" for User, "assumed": true when guessed + "sources": [{ "file": "Plugins/AccountPostPlugin.cs", "line": 37, "column": 21, + "path": ["AccountPostPlugin.Execute"] }] + }], + "unresolved": [ /* operation + location + reason + path */ ], + "assumptions": [ /* reason + location */ ], + // With roles only: each requirement also gets + // A privilege not tied to a table is a requirement without "table": + // { "privilege": "prvActOnBehalfOfAnotherUser", "runsAs": "ApplicationUser", "basis": "direct", "sources": [ … ] } + // "coverage": { "status": "granted", "depth": "User" } (or missing, suppressed + reason, not-governed, not-checked, system, unverifiable) + "roles": [{ "runsAs": "Caller", "roles": ["Salesperson"], "origin": "--role" }], // or "note" when not checked + "triggers": [ "plugin:Contoso.ContactPostPlugin:Create:contact:PostOperation" ] // phase 4 + }], + "unreached": [ /* per-method manifests, as in phase 1 */ ], + "notRoleGoverned": ["activityparty"], + "missing": [{ "table": "contact", "privilege": "Create", "runsAs": "Caller", "roles": ["Salesperson"], + "origin": "--role", "in": ["plugin:Contoso.AccountPostPlugin:Update:account:PostOperation"] }], // with roles only; no "table" for a privilege not tied to a table + "result": { "granted": 12, "notGoverned": 0, "missing": 2, "suppressed": 0, "notChecked": 1, + "system": 1, "unresolved": 1, "unresolvedNoRule": 0, "unresolvedCustomApi": 0, "unresolvedWorkflow": 0, + "unverifiable": 0, "truncated": 0, + "incomplete": true } // with roles only +} +``` + +The same model drives text, Markdown, JSON and SARIF output. The text report below `normal` and +Markdown share the grouping of the privileges to change per set of roles (`RoleChanges`). SARIF +results point at the source location of each missing privilege; see phase 6 in §10. + +## 8. Limitations + +- **Trust**: `MSBuildWorkspace` loads projects with a design-time build, so their targets, tasks + and source generators can run. The README tells CI users not to analyze fork pull requests + in a job with secrets (`pull_request_target`), and to take `Metadata/` and the configuration from + the base branch so a change can't grant itself the privileges it needs. +- **Depth**: the report shows the depth each role grants (`User`, `BusinessUnit`, + `ParentChildBusinessUnit`, `Organization`) next to each requirement, but can't prove it is + enough, because that depends on record ownership at runtime. For now any depth counts as + covered (§6.2). +- Table names computed at runtime, reflection, `dynamic`, and requests built in other + assemblies (binary-only references) come out as `Unresolved`. +- Interface dispatch without DI registrations over-approximates (all implementations). +- The steps of workflows aren't analyzed. A workflow an operation fires is reported as unresolved + (§5.6), not what it needs. +- Conditional code is treated as reachable (no path sensitivity), so requirements are a + superset. +- Team-inherited roles and record sharing are outside the static view. The check answers for + the roles given, not for a specific user's effective rights. + +## 9. Validation strategy + +- **Golden manifests**: `PermissionAnalyzer.Tests` analyzes `tests/TestPluginAssembly365` + (which covers XrmPluginCore, DI-based, legacy DAXIF, non-DAXIF and direct plugins, custom + APIs and code activities) and compares the output with committed manifests. +- **New fixtures**: small projects for isolated and in-process Azure Functions, DI-heavy + services, FetchXML/LINQ queries and `ExecuteMultiple`. +- **Cross-check with XrmMockup**: for selected scenarios, give a test user exactly the + privileges the tool reports, run the scenario in XrmMockup and expect success; remove one + reported privilege and expect an access-denied fault. This ties the rule table to mockup's + real behavior and catches drift when handlers change. +- A runtime permission recorder in XrmMockup (recording every check inside + `Security.HasPermission`) automates this cross-check. It is a later, not yet decided feature, see + [role verification for scenarios](#future-role-verification-for-scenarios-in-xrmmockup-core). + +## 10. Delivery plan + +| Phase | Scope | Outcome | +|---|---|---| +| 1 | Project skeleton, MSBuildWorkspace loading, role loading via MetadataSkeleton, direct `IOrganizationService` CRUD with early-bound/literal tables, per-method manifest, `required` (no scope). Also pulled forward: `QueryExpression`/`AddLink`/FetchXML tables, `Associate`/`Disassociate`, loops over `RetrieveMultiple` results, `Solution`/`MetadataDirectory` configuration | First useful manifest | +| 2 | Entry-point discovery (XrmPluginCore, metadata steps, custom APIs, activities, Azure Functions), call graph, runs-as tagging, DI resolution | Per-entry-point requirements; `--plugin`, `--custom-api`, `--function`, `--entry` | +| 3 | `check` command, `required --role`, role combination, exit codes, `XrmMockup:Permissions` configuration. The two commands were later merged into the root command, with `--fail-on-missing` in place of `check` (§6.2) | Both questions answerable; CI-ready | +| 3.5 | Execute rule table (§5.3): built-in rules, `Rules` setting, `ExecuteMultiple`/`ExecuteTransaction` and `*Multiple` requests, requests and request collections followed through the call graph, requests needing no table privilege, custom API calls recognized; Append/AppendTo via relationship metadata | Requests and lookups checked; what is left under `Not checked` is what static analysis can't see | +| 4 | Plugin cascade expansion (done: steps and custom APIs fired by direct calls and requests, from every entry point including Azure Functions and app code, identity, unknown tables reported, steps without code, FilteredAttributes, `--operation` scope, plugin code loaded from other solutions (§5.6)) | "What does a user need to do X"; a function's roles checked against the plugins it fires | +| 5 | LINQ and `OrganizationServiceContext` (§5.2, done, with type parameters of generic types); privilege catalog + global privileges in the metadata generator, custom API execute privileges (§5.7), `prvActOnBehalfOfAnotherUser` checked; requests needing privileges by name, bypass parameters and `overriddencreatedon` (§5.3) (done) | Near-complete coverage | +| 5.5 | Output clean-up (below, done): filtering, and detail levels where the default shows only the privileges to change and the full detail, such as requirements the roles already grant, is available on request | Output short enough to act on, with the full picture still available | +| 6 | SARIF/Markdown output (below, done), docs, NuGet tool packaging alongside `xrmmockup-metadata` (done: `XrmMockup.PermissionAnalyzer`, versioned from its CHANGELOG by CI and `release.yml`, first version `1.0.0-rc.1`) | Release | +| Later | Role verification for scenarios in XrmMockup core (below), not yet decided: a core feature that changes XrmMockup365 itself, so tests can run a scenario as a principal and compare what was checked, granted and denied with the analyzer's output. Role suggestions (which single role, or smallest combination of downloaded roles, covers a requirement), minimum required depth, stopping at impersonated calls without `--caller-role` (opt-in, see below), roles from a user's assignments and privileges the roles grant but nothing uses (see below), IDE `DiagnosticAnalyzer` package on Core, analyzing the steps of workflows (fired workflows are reported as unresolved until then) | | + +**Output clean-up (phase 5.5, done).** On a real solution the output is long, and most of it is +requirements the roles already grant. That is rarely what a reader needs, but it must stay +available, for example to review a role or to answer "why does this function need Write on +account". On a sample Azure Functions app, the text report went from 454 lines (335 KB, lines of up to +20,000 characters from call paths) to 15 lines at the default `minimal`: ten tables to change in one role, the counts, `Result` and +what was left out. `compact` is 47 lines and `normal` 69 (9 KB). + +- **Detail**: `--detail minimal|compact|normal|detailed|full`. `minimal` (the default) + replaces the sections and the `Missing privileges` list with the changes to make, without + sources: a block per set of roles (`Missing from Order API (--role), for + ApplicationUser:`) with what it lacks, merged over every entry point and identity that uses + it, since a role is changed once whatever needs it. Each table has a line, in table order, with + its privileges in the order of the role editor's columns (`ctx_orderline + Create, Read, Append`), so a role can be changed one table at a time. Unchecked requirements get a + block per identity with the reason (`Caller needs (not checked: pass --role):`), unverifiable + ones a block per set of roles. Without roles, each block is what an identity needs, leaving out + SYSTEM, which needs no role. `compact` adds, under each block, the entry points and methods that + need its privileges: those that need exactly the same ones are listed together, with their + tables listed the same way, which answers which entry points a change is for. `normal` shows the requirements + that are missing, not checked or unverifiable, the unresolved operations, and only the entry + points and methods that have any. Sources are shown as up to three locations, without call + paths. With roles, `Privileges per table` is left out, since `Missing privileges` says what to + change. A last line says what was left out (`Not shown: 242 requirements with nothing to fix, + 73 assumptions. --detail detailed lists them, ...`). `detailed` adds the granted, not + governed, suppressed and SYSTEM requirements, every section, assumptions, the steps each entry + point fires and the privileges per table. `full` is the output from before the phase, byte for + byte, with every source and its call path. +- **Filtering**: `--table`, `--privilege`, `--runs-as` and `--basis`, each comma-separated or + repeatable, matching any value ignoring case; different filters combine. A privilege not tied + to a table has no table, so a table filter leaves it out. An unresolved operation has no known + table or basis, so only the identity and privilege filters apply to it, and a privilege filter + keeps it when it has no privileges or one of them matches. `Missing privileges` keeps the + merged privileges that some matching requirement is missing, so a basis filter, which merged + privileges don't carry, narrows it too. Filters, like the detail level, apply after analysis: the + counts line, `Result`, `Not checked` and the exit code are those of the whole analysis, and a + `Filtered by ...: n of m requirements match` line says how much matched. +- **JSON** ignores the detail level, so tools and a later role verification always get the full + result with every call path. Filters apply to it: requirements and unresolved operations they + don't match are left out, as are sections left without any, and `missing` is narrowed as in + the text. `result` stays the count of the whole analysis. +- Without roles, nothing is granted, so `normal` shows every + requirement and the privileges per table, and differs from `full` only in the sources and in + leaving out assumptions and fired steps. + +**Output formats (phase 6, done).** Two more formats, for CI rather than a terminal. Both ignore +the detail level, take the filters, and keep the output deterministic. + +- **Markdown** (`--format markdown`) is for a pull request comment or a job summary: a heading + with the result, `Result` and `Not checked` (as a warning callout), then the `minimal` blocks as + `| Table | Privileges |` tables, with the `compact` entry point groups and the unresolved + operations in `
`, so the comment stays short. It ends with the counts. The heading + counts each missing privilege once per identity and roles, as `Missing privileges` lists them. + Free text is escaped and ids are code spans fenced past their longest run of backticks, with `|` + escaped and line breaks and control characters as spaces, so they can't break a table or add + Markdown of their own. +- **SARIF** (`--format sarif`, 2.1.0) is for GitHub code scanning. The rules are + `missing-privilege` (error), `unresolved-operation` (warning, not for SYSTEM), `not-checked` + and `unverifiable` (notes). A result is a call site with one privilege, identity and role + set, merged over the entry points and methods that reach it: the message names up to three, + `relatedLocations` are all their declarations, and `properties.entryPoints` their ids. A + suppressed privilege is a `missing-privilege` result with an `external` suppression whose + justification is the reason, so code scanning shows it as dismissed rather than hiding the + configuration. Without roles, only unresolved operations are results: every requirement as a + finding would say nothing actionable. A location outside the code (`--operation`) uses the + entry point's declaration, or has none. +- **SARIF paths.** Source locations are relative to the analysis root, with `../` for plugin + code next to it, but code scanning resolves URIs against the repository root. The runner walks + up from the analysis root to the nearest `.git` folder or file (a worktree has a file), and + the writer prefixes each path with the root's place in the repository and resolves the `../` + segments, with `uriBaseId` `%SRCROOT%`. No absolute path is written, so the output is the same + on every machine; outside a repository the paths stay relative to the analysis root. The + driver version is the tool's informational version. + +**Idea: minimum required depth.** A `--min-depth` option (or per-table setting) that only +counts a privilege as covered at or above a given depth, so CI could, for example, require +`Organization` Read on reference tables. It needs a detailed specification before it is +built: whether the minimum applies globally, per table, per privilege or per entry point; +how it interacts with combined roles and with tables no role governs; how it relates to the +ownership XrmMockup actually checks at runtime (owner, business unit, sharing); and how it is +configured in `XrmMockup:Permissions`. Deferred until then. + +**Idea: stop at impersonated calls without `--caller-role`.** Today a call made with `CallerId` +set is analyzed like any other: its requirements and the plugins it fires (§5.6) are listed as +"not checked" when no `--caller-role` is given. Those requirements depend on the user the app +acts for, not on the application user, so a run that only has the application user's roles can't +say anything about them, and the cascade they fire makes the report longer without making it +more useful. The proposal: without `--caller-role`, stop following the chain at the impersonated +call, and report in the output that it was detected and what it does. That splits the check in +two: + +1. Check the application user alone: `--function ProcessOrder --role "Integration App"` + covers what the function does as itself, plus `prvActOnBehalfOfAnotherUser` for the + impersonation (§6.2), which stays a requirement of the impersonating identity. +2. Check the calling user independently, from the impersonated operations the first run lists, + for example `Create account` and `Update contact`: `--operation "Create account" --role + Salesperson`, which fires the same plugins as the impersonated call would. + +What the output shows of the impersonated calls, by detail level (§10, phase 5.5): + +- `minimal`: one line with the number of impersonated operations not followed, and the + detail level that lists them, like the hint for assumptions. +- `compact`: the operations, merged per message and table with the columns set when they are + known, written so they can be used as `--operation` (and `--attributes`) values for the second + check. +- `normal`: each operation with the sources where it is made and where `CallerId` is set. +- `detailed` and `full`: the call paths as well. +- JSON lists them in full, whatever the detail level; Markdown lists them like `compact`, and SARIF + perhaps as `note` results. + +It is opt-in, with a flag whose name is still to be decided. Without the flag the impersonated +call is followed as it is today, so adding it changes no existing output or exit code. + +Things to settle before it is built: + +- The name of the flag, and whether `--strict` fails on the calls it stops at. It shouldn't fail + `--fail-on-missing`, since nothing is known to be missing. +- An operation whose table can't be resolved stays unresolved; whether it is also listed as an + impersonated call. +- Calls the plugins make with `CallerId`, which are rarer: whether the same applies to them, and + how a step's own impersonation (`ImpersonatingUserId`) interacts with it. +- `--operation` takes one operation per run (§6.1), so the second check needs a run per + operation unless it becomes repeatable, which would let the `compact` list be passed as is. +- With `--caller-user` (below), the second check could run in the same invocation instead. + +**Idea: privileges the roles grant but nothing uses.** The reverse of the role check: list the +privileges in the `--role` roles that none of the selected entry points needs, so a role can be +trimmed to least privilege. It only means something when the selected entry points are everything +the role is for, such as an API security role held by the application user of one Azure Function +app (`--function ... --role "Order API"`). For a role people also use in the UI, +most of what it grants is unused by the code, and the list would be noise. Things to settle before +it is built: + +- How it is asked for: an option such as `--unused`, since it is a different question from + whether the roles suffice, and whether it can fail CI or only reports. +- What counts as used: the requirements of the selected entry points under that role's identity, + including the plugin steps and custom APIs they fire (§5.6) and global privileges (§5.7). A + privilege used only by code outside the scope looks unused, so the output must say which entry + points it was measured against. +- Unresolved operations, unknown tables and unknown custom APIs make "unused" uncertain: a table + the analysis couldn't name may be the one a privilege is for. The report should say how many + there were, and perhaps refuse to call anything unused while there are any for that identity. +- Depth: whether a privilege granted at `Organization` where `User` would do is reported, which + needs the minimum required depth (above) to be settled first. +- Several roles: whether a privilege is unused in each role on its own, or redundant because + another of the given roles grants it too. +- Output: a block per role with the tables and privileges that could be removed, in the role + editor's column order like `Missing privileges`, plus JSON; Markdown and SARIF probably don't + need it. + + `--user ` (e.g. +`--user jane@contoso.com`) looks the user up in Dataverse and checks against the roles they +actually hold, instead of a hand-written `--role` list: + +- Look up the `systemuser` by `domainname` (UPN), with `internalemailaddress` as a fallback. + An unknown or ambiguous user is an error. +- Collect the user's directly assigned roles (`systemuserroles`) and the roles of every team + they belong to (`teammembership` → `teamroles`), including Microsoft Entra group teams. In + Dataverse, both kinds add privileges. +- Match each role to the role definitions in `Metadata/` through its root role + (`parentrootroleid`), because every business unit has its own copy of a role with a + different id. A role that isn't in `Metadata/` is an error that suggests regenerating the + metadata, so the check never silently runs against fewer roles than the user has. +- The output names each role and where it comes from (direct, or which team). +- The same lookup serves impersonated calls: a `--caller-user ` option would give + the roles of the end user that app code acts for through `CallerId`, instead of a + hand-written `--caller-role` list. The impersonating identity still needs + `prvActOnBehalfOfAnotherUser` (§6.2). + +Things to settle before building it: + +- It is the first feature that connects to Dataverse. It would reuse the metadata tool's + connection settings (`DataverseUrl`, `DataverseCredentialType`, `--credential-type`). + Only a run with `--user` connects; every other run stays offline (goal in §2, §6.3). +- The result depends on live data, so it is not deterministic over time. The output should + record the environment URL, the user and when the roles were read. A `--save-roles` option + could write the resolved role list to a file, so a later run can reproduce the check + without connecting. +- Whether to use the user's business unit, and the business units of the teams, once depth + matters (see minimum required depth above). +- The signed-in identity needs read access to `systemuser`, `team` and `role`. + +### Future: role verification for scenarios in XrmMockup core + +**Goal.** Today the analyzer finds the privileges code needs by reading the code. XrmMockup could +confirm those findings by running scenarios against roles. A test would state "run this as a +user with these roles" and get back what was checked, granted and denied, not just pass or fail. + +**Scenarios to cover:** + +- **Azure Function execution**: run the function's code against a mockup service that acts as + an application user holding the configured roles, including any `CallerId` impersonation. +- **Plugin triggering**: run a `Create` or `Update` (with given columns) as a user with given + roles. Every step it fires, including steps fired by other steps and steps with an + impersonating user, is checked under the identity it really runs as. +- **Custom APIs and requests**: run a request as a principal and check what its handler and + plugins need. + +**Proposed API (sketch):** + +```csharp +var result = crm.VerifyRoles( + principal: Principal.ApplicationUser(roles: ["Integration App"]), + scenario: svc => new OrderFunction(svc).Run(input)); + +result.Denied // (table, privilege, identity, call path) that failed +result.Checked // every privilege check made, with the depth granted +result.Fired // plugin steps run, with the identity of each +``` + +- `Principal.User(roles)`, `Principal.ApplicationUser(roles)` and + `Principal.Impersonating(caller, roles)` describe who runs the scenario. +- The run records every privilege check rather than stopping at the first denial, so one run + reports everything that's missing. +- Option `StrictUnenforced`: also check the rules XrmMockup doesn't enforce today + (`RequestRule.Enforced = false`, such as `SetState`, §5.3) and report them separately. + +**Link with the analyzer:** + +- The output uses the analyzer's terms: table, privilege, `RunsAs` and step ids. That lets a + test compare a run with `xrmmockup-permissions` output and flag requirements the + analyzer missed (for example LINQ through an `OrganizationServiceContext`, until phase 5) or + included without need. This replaces the manual cross-check in §9. +- The analyzer's `Principals` and `Users` settings in `appsettings.json` (§6.3) could feed the + scenario's principals, so code analysis and runtime checks use the same roles. + +**Open questions:** + +- How much of `Security` and `RequestExecutionPipeline` has to change to record checks instead + of throwing on the first denial? +- How are asynchronous steps treated? They need the privileges, but their failure doesn't fail + the request. +- How should depth (user, business unit, organization) be reported when the mockup's records + don't exercise every depth? + +**Phase:** later, not yet decided. It would be its own core feature, since it needs changes to +XrmMockup365 itself, not only the analyzer. + +## 11. Decisions + +- **Packaging**: a separate dotnet tool, `xrmmockup-permissions`, not a subcommand of + `xrmmockup-metadata`. +- **One command**: `required` and `check` were the same analysis and report, differing only in + the exit code, so they are one root command. Failing is opt-in with `--fail-on-missing`, which + is an error without roles to check against; configured roles always apply, and `--no-roles` + gives the role-free output (§6.2). +- **Deterministic output**: without roles, the output is an exact, reproducible requirement set + derived from code and metadata only. Role coverage (`--role`, `Principals`, `Users`) + is a layer on top that compares that set against the roles present in `Metadata/`. The + tool does not guess whether the downloaded role set is complete. +- **Custom API privileges**: execute privileges are mapped exactly through a privilege + catalog added to the metadata generator (§5.7). +- **Configuration**: a `XrmMockup:Permissions` section in the shared `appsettings.json`, + loaded the same way as the metadata tool. There is no separate config file (§6.3). +- **Any depth counts**: role coverage treats a privilege granted at any depth as covered, + and only reports the depth. A minimum-depth check is deferred until it is specified (§10). +- **Roles per identity**: `--role` covers the caller and the application user, `--caller-role` + the user acted for through `CallerId`, and `Users` specific users. A requirement whose + identity has no roles is "not checked" instead of silently passing or failing (§6.2). +- **Stopping at impersonated calls is opt-in**: when it is built, a flag (name to be decided) + turns it on, and the default keeps following the impersonated call, so it can be added after + the first release without changing existing output or exit codes (§10). +- **Role suggestions deferred**: the first version answers "what is needed" and "do these + roles cover it". Working out which roles would cover a requirement comes later. diff --git a/docs/permission-analysis-sdk.md b/docs/permission-analysis-sdk.md new file mode 100644 index 00000000..ca7f8231 --- /dev/null +++ b/docs/permission-analysis-sdk.md @@ -0,0 +1,119 @@ +# Static permission checks in XrmMockup tests + +Permission checks analyze source code and compare the privileges it may need with the mockup's +current role definitions. **They do not run a plugin or an organization request, change mockup +state, or prove record-level access.** Ownership, sharing and access depth are not simulated by this check: +as in the standalone analyzer, any granted privilege depth counts. + +## Setup + +Reference only the existing `XrmMockup365` package. Enable source loading explicitly in the +.NET 10 test project: + +```xml + + true + +``` + +There are **no additional NuGet packages and no dotnet tool installation is required**. The +permission contracts, analyzer engine and workspace loader remain internal shared library +projects. `XrmMockup365` ships the lightweight .NET Standard 2.0 contracts in its normal library +assets for all three supported target frameworks. It also carries the library-only .NET 10 analyzer +payload and its dependencies in a private folder. The opt-in target copies that payload into +build/publish output; ordinary Core consumers do not copy or load it. Roslyn/MSBuild run in a +separate load context so they do not change the host's workflow dependencies. + +The standalone Permission Analyzer package ships the same shared libraries alongside its own +CLI. Neither dotnet tool is bundled into Core, and the Metadata Generator remains unchanged. +Only the existing three product packages are packed/published, so the selected-product release +flow still uses one package/symbol pair per product. Shared contracts have a stable assembly +identity; internal assemblies do not introduce independently versioned NuGet dependencies. + +For local packages, build the solution and use `scripts/Pack-Local.ps1`. Core packing expects the +shared workspace library output from that solution build; `pack --no-build` does not rebuild it. +Repository/project-reference tests reference the internal contracts project directly and pass +`XrmMockupEnablePermissionAnalysis` to their Core project reference; packaged consumers need +only the property above. + +Core supports .NET Framework 4.6.2 and 4.8. Checks and result contracts are available on both, +but loading source requires .NET 10. No Roslyn/MSBuild dependencies are added to normal Core +PackageReferences on any supported target framework. + +Install the .NET 10 SDK with `dotnet` on `PATH`, and restore/build the analyzed project before loading it. Load once in the test fixture and reuse it: + +```csharp +using DG.Tools.XrmMockup; +using XrmMockup.PermissionAnalyzer; +using XrmPluginCore.Enums; + +fixture.PermissionAnalysis = await PermissionAnalysis.LoadAsync(projectOrSolutionPath); + +crm.CheckPermissions( + fixture.PermissionAnalysis, + PermissionSelector.Operation(EventOperation.Create), + SecurityRoles.XrmMockupTestAccessTeam) + .ThrowIfFailed(); +``` + +The loader reads `appsettings.json` next to the analyzed project/solution, when present, using +its existing `XrmMockup:Permissions` settings for rules, metadata, excluded projects, explicit +entry methods and plugin solutions. Project references are loaded too. It disposes the workspace +once the compilations and source summaries are loaded. Source graphs are reused; if the current +mockup's lookup catalog changes, a new metadata-dependent source graph is extracted from the +already-loaded compilations and reused. Reload the analysis if the source code changes. + +## Select a scope + +```csharp +// All registered steps of this exact plugin type and assembly: +PermissionSelector.Plugin(); + +// Narrow to a message and stage; omitted filters mean all registered steps: +PermissionSelector.Plugin(EventOperation.Update, ExecutionStage.PostOperation); +PermissionSelector.Plugin("custom_message", ExecutionStage.PostOperation); + +// Synthetic operations include direct privileges even when no plugin is registered: +PermissionSelector.Operation(EventOperation.Create); +PermissionSelector.Operation(EventOperation.Update, account => account.Name); +PermissionSelector.Operation("custom_message"); +``` + +Entity and attribute logical names come from SDK `EntityLogicalName` and `AttributeLogicalName` +attributes. Attribute expressions must select direct entity properties, not computations or nested +members. Specified attributes determine Update filtering and lookup Append/AppendTo privileges. +Omitted attributes mean unknown attributes, conservatively including filtered Update steps. +Entity operations include applicable plugin steps at all stages, asynchronous steps and recursive +cascades. The mockup's currently registered workflows and registered plugin code that was not loaded are reported as incomplete. + +## Choose roles or a user + +Pass generated `SecurityRoles` GUID members, not display names or sanitized generated member +names. Multiple IDs combine their privileges. Unknown IDs and empty explicit lists are rejected. + +```csharp +var result = crm.CheckPermissions(analysis, scope, SecurityRoles.RoleA, SecurityRoles.RoleB); +var forUser = crm.CheckPermissions(analysis, scope, user.ToEntityReference()); +``` + +The user overload requires an existing local `systemuser` and reads current direct roles and +roles of teams the user belongs to. Role definitions and assignments are read anew for every +check, so changes between checks take effect. Existing results remain snapshots. + +Explicit impersonating users are checked separately using their own current direct/team roles. +Unknown impersonating users and identities whose roles cannot be established (including an +unspecified `CallerId` identity) are not silently checked against the primary caller's roles. +SYSTEM operations retain the analyzer's no-role-required behavior. + +## Inspect or assert results + +`result.Passed`, `result.Manifest` and `result.Coverage` expose the same manifest and coverage +engine used by the CLI. `ThrowIfFailed()` throws a framework-neutral `PermissionCheckException` +with the result attached when privileges are missing **or the analysis is incomplete**: unresolved +operations, unchecked identities, unavailable global privilege data, source compilation errors or +call-limit truncation. Diagnostics identify entry points, roles, identities and source locations. +There is no permissive SDK mode or suppression option. + +The standalone `xrmmockup-permissions` CLI retains its existing options and reporting behavior. +Checks are explicit only: no automatic CRUD validation, runtime tracing, live Dataverse lookups +or role suggestions are performed. diff --git a/docs/release-flow.md b/docs/release-flow.md index 424eff8f..20d24463 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -6,10 +6,10 @@ See [the current sequence diagram and simplification analysis](release-sequence. ## Contract -- PR labels choose core, metadata, both, or exclusive `product:none`. +- PR labels choose one or more of core, metadata and permissions, or exclusive `product:none`. - A category label or matching `Add:`, `Fix:`, `Change:`, `Breaking:`, or `Chore:` title prefix is mandatory. -- Both product changelogs are committed directly to master after merges and successful releases. Wait for the notes commit before tagging; no changelog PR is created. -- `core-v` and `metadata-v` independently publish their one selected NuGet package. +- All configured product changelogs are committed directly to master after merges and successful releases. Wait for the notes commit before tagging; no changelog PR is created. +- `core-v`, `metadata-v` and `permissions-v` independently publish their one selected NuGet package. - Each release makes one `dotnet nuget push` (including its matching `.snupkg`), without skipping duplicates. Failure stops the run; maintainers can delete the failed tag and restart if NuGet has not accepted that version. - No merge-queue support, emergency audit mechanism, persistent release ledger/checkpoints, package checksums, receipts, or automatic partial-publication recovery. @@ -21,7 +21,7 @@ Normal maintenance PRs use `product:none` and a valid category. The changelog wr ## Notes generation -`update-changelogs.yml` runs on master pushes or manual dispatch, using `GITHUB_TOKEN` with `contents: write`, `actions: write` and `pull-requests: read`. It commits only the two configured changelog files directly to master. The required native `ci` job must pass on the generated commit before the direct write; other repository rules must still permit it; Actions PR creation/approval permission is not required. +`update-changelogs.yml` runs on master pushes or manual dispatch, using `GITHUB_TOKEN` with `contents: write`, `actions: write` and `pull-requests: read`. It commits only the configured product changelog files directly to master. The required native `ci` job must pass on the generated commit before the direct write; other repository rules must still permit it; Actions PR creation/approval permission is not required. 1. Require a clean working tree, fetch current remote master/tags, and start the generated commit from that source. Workflow concurrency serializes writers without canceling an in-flight update. 2. List published GitHub releases. Choose the latest successful same-product release as that product's notes boundary; before any new-format release, use the fixed migration cutoff `6e689d959b9013e2318320e9c317449d0de02c2d` (the PR #361 rollout merge). This exclusive boundary excludes the unclassified rollout and older PRs without rewriting legacy history. @@ -40,7 +40,7 @@ Workflow-level concurrency serializes each product independently. Tag releases a ### Read-only build -The Windows build job checks out trusted scripts and the requested source separately. Trusted preparation code validates the entire product tag/version, master ancestry, version progression, and that the selected changelog matches the merged-PR notes at that source. Preparation scopes release boundaries and range ancestry to the selected product; a later release of the other product does not invalidate an earlier reviewed source. The changelog writer still collects both products on current master. An unmerged source cannot replace privileged preparation code. Manual dispatch takes a candidate tag and source ref and is always preview-only. Only a tag push enables publication. +The Windows build job checks out trusted scripts and the requested source separately. Trusted preparation code validates the entire product tag/version, master ancestry, version progression, and that the selected changelog matches the merged-PR notes at that source. Preparation scopes release boundaries and range ancestry to the selected product; a later release of the other product does not invalidate an earlier reviewed source. The changelog writer still collects all configured products on current master. An unmerged source cannot replace privileged preparation code. Manual dispatch takes a candidate tag and source ref and is always preview-only. Only a tag push enables publication. Prerelease identifiers are compared case-insensitively to match NuGet version identity. Release sections are inserted literally, preserving dollar-sign sequences from PR titles in both saved notes and the packaged changelog. diff --git a/docs/release-sequence.md b/docs/release-sequence.md index 520c866a..37cb8257 100644 --- a/docs/release-sequence.md +++ b/docs/release-sequence.md @@ -35,7 +35,7 @@ sequenceDiagram alt Manual preview Maintainer->>Build: Dispatch candidate tag and source_ref (preview-only) else Product release - Maintainer->>GitHub: Push core-vVERSION or metadata-vVERSION + Maintainer->>GitHub: Push core-vVERSION, metadata-vVERSION or permissions-vVERSION GitHub->>Build: Trigger release end Build->>GitHub: Checkout trusted scripts and exact source separately @@ -67,7 +67,7 @@ Pending notes and published history are automatic bot commits on master. No chan - PowerShell handles policy and text/JSON transformations; `gh` and `dotnet` perform operations directly. No Node runtime or custom GitHub HTTP client. - One read-only `pull_request` classification workflow fetches PR metadata once and reports a single native **PR release labels** check. Manual validation dispatch verifies the selected PR head commit. - Product/category definitions live in one JSON configuration file. -- One serialized changelog writer stages only the two note files on temporary branches, dispatches CI on each exact commit, then fast-forwards master, with bounded regeneration retries for concurrent merges and no force pushes. +- One serialized changelog writer stages only the configured product note files on temporary branches, dispatches CI on each exact commit, then fast-forwards master, with bounded regeneration retries for concurrent merges and no force pushes. - Label provisioning and GitHub publication are short workflow steps, not separate wrapper scripts. - Tag pushes are the only publication trigger. Manual dispatch only builds previews. - One package push also uploads matching symbols. Partial success is recovered manually from artifacts. diff --git a/scripts/Pack-Local.ps1 b/scripts/Pack-Local.ps1 index 6f48ebce..99dcd7c4 100644 --- a/scripts/Pack-Local.ps1 +++ b/scripts/Pack-Local.ps1 @@ -2,12 +2,13 @@ param( [string]$Output = './nupkg', [string]$Configuration = 'Release', [string]$CoreVersion = '0.0.0-dev', - [string]$MetadataVersion = '0.0.0-dev' + [string]$MetadataVersion = '0.0.0-dev', + [string]$PermissionsVersion = '0.0.0-dev' ) # Local packaging is a preview only: no changelog writes, release state, or credentials. $ErrorActionPreference = 'Stop' -$versionArgs = @("-p:CoreReleaseVersion=$CoreVersion", "-p:MetadataReleaseVersion=$MetadataVersion") +$versionArgs = @("-p:CoreReleaseVersion=$CoreVersion", "-p:MetadataReleaseVersion=$MetadataVersion", "-p:PermissionsReleaseVersion=$PermissionsVersion") dotnet build --configuration $Configuration @versionArgs if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } @@ -15,3 +16,5 @@ dotnet pack './src/XrmMockup365/XrmMockup365.csproj' --configuration $Configurat if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } dotnet pack './src/MetadataGen/MetadataGenerator.Tool/MetadataGenerator.Tool.csproj' --configuration $Configuration --no-build --output $Output @versionArgs if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +dotnet pack './src/PermissionAnalyzer/PermissionAnalyzer.Tool/PermissionAnalyzer.Tool.csproj' --configuration $Configuration --no-build --output $Output @versionArgs +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/scripts/release/Release.psm1 b/scripts/release/Release.psm1 index 50094d46..4b101201 100644 --- a/scripts/release/Release.psm1 +++ b/scripts/release/Release.psm1 @@ -41,7 +41,7 @@ function Get-PrProducts { if ($selected.Count) { throw 'product:none is exclusive' } return } - if (!$selected.Count) { throw 'Choose product:core, product:metadata, both, or product:none' } + if (!$selected.Count) { throw ('Choose one or more of ' + (($script:Config.products.Keys | Sort-Object | ForEach-Object { "product:$_" }) -join ', ') + ', or product:none') } return $selected } function Get-PrNote { @@ -59,7 +59,7 @@ function Get-PrNote { } function Get-ReleaseTag { param([string]$Tag) - if ($Tag -cnotmatch '^(core|metadata)-v(.+)$') { throw 'Use core-vVERSION or metadata-vVERSION' } + if ($Tag -cnotmatch '^([a-z]+)-v(.+)$' -or !$script:Config.products.ContainsKey($Matches[1])) { throw 'Use a configured product tag: core-vVERSION, metadata-vVERSION or permissions-vVERSION' } $product = $Matches[1]; $version = $Matches[2] if ($version -notmatch '^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$' -or $version -match '-v\d+\.\d+\.\d+') { throw 'Invalid release version' } [void][semver]$version diff --git a/scripts/release/Test-Release.ps1 b/scripts/release/Test-Release.ps1 index 8efd6b46..81d6dec8 100644 --- a/scripts/release/Test-Release.ps1 +++ b/scripts/release/Test-Release.ps1 @@ -40,19 +40,24 @@ Assert ($classification.Contains("github.event_name == 'workflow_dispatch' && gi Write-Output 'PASS: single read-only native classification workflow and metadata triggers' $config = Get-ReleaseConfig -foreach ($product in @('core', 'metadata')) { +foreach ($product in ($config.products.Keys | Sort-Object)) { + Assert ($workflow.Contains("'$product-v*'")) 'Every configured product has a release tag trigger' [xml]$project = Get-Content (Join-Path $PSScriptRoot "../../$($config.products[$product].project)") -Raw $changelogName = Split-Path $config.products[$product].changelog -Leaf $packedChangelog = @($project.SelectNodes('/Project/ItemGroup/None[@Pack="true"]') | Where-Object { $path = if ($_.Include) { $_.Include } else { $_.Update } (($path -replace '\\', '/') -split '/')[-1] -ceq $changelogName }) - Assert ($packedChangelog.Count -eq 1 -and $packedChangelog[0].PackagePath -in @('', '\')) 'Both products must pack their changelog at the package root' + Assert ($packedChangelog.Count -eq 1 -and $packedChangelog[0].PackagePath -in @('', '\')) 'All products must pack their changelog at the package root' } -Write-Output 'PASS: both product projects include their changelog in the NuGet package' +Write-Output 'PASS: all product projects include their changelog in the NuGet package' Assert ((Compare-Version '1.20.3-RC.1' '1.20.3-rc.1') -eq 0) 'NuGet casing identity' Assert ((Compare-Version '1.20.3-rc.10' '1.20.3-rc.2') -gt 0) 'Numeric prerelease order' Assert ((Get-ReleaseTag 'metadata-v1.2.1').product -eq 'metadata') 'Product tag' +Assert ((Get-ReleaseTag 'permissions-v1.0.0-rc.2').product -eq 'permissions') 'Permission analyzer product tag' +Assert (@(Get-PrProducts @{ labels = @('product:permissions') }).Count -eq 1) 'Permission analyzer product label' +Reject { Get-PrProducts @{ labels = @('product:none', 'product:permissions') } } +Reject { Get-ReleaseTag 'unknown-v1.0.0' } Reject { Get-ReleaseTag 'v1.20.3' }; Reject { Get-ReleaseTag 'core-v01.2.3' } Reject { Get-PrProducts @{ labels = @('product:none', 'product:core') } } Reject { Get-PrNote @{ title = 'No category'; labels = @('product:core') } } @@ -76,7 +81,7 @@ try { $published[0].body = "### 1.20.3 - 2026-11-04`n* Published" Assert ((Get-Changelog $original @() 'core' $published).Contains('### 1.20.3 - 4 November 2026')) 'ISO release bodies are formatted on import' } finally { [Globalization.CultureInfo]::CurrentCulture = $oldCulture } -foreach ($product in @('core', 'metadata')) { +foreach ($product in ($config.products.Keys | Sort-Object)) { foreach ($count in @(1, 9, 10, 11, 12)) { $sections = @(for ($i = $count; $i -gt 0; $i--) { $version = if ($i -eq $count) { "2.$i.0-rc.1" } else { "v2.$i.0" } @@ -91,7 +96,7 @@ foreach ($product in @('core', 'metadata')) { } } Reject { Get-PackageReleaseNotes "### Unreleased`n* Pending" 'core' 'owner/repo' } -Write-Output 'PASS: English display dates, UTC imported dates and ten-release package notes for both products' +Write-Output 'PASS: English display dates, UTC imported dates and ten-release package notes for all products' # A real Git fixture plus a small in-memory gh double exercise aggregation and # preparation without duplicating gh's HTTP transport or a service implementation. @@ -109,7 +114,7 @@ try { $legacySha = Invoke-Git -Arguments @('rev-parse', 'HEAD') '.release/' | Set-Content '.gitignore' $global:TestAssociatedPrs = @(); $global:TestPrs = @(); $global:TestPrReads = 0 - $global:TestReleases = foreach ($product in @('core', 'metadata')) { + $global:TestReleases = foreach ($product in ($config.products.Keys | Sort-Object)) { $version = $config.products[$product].baselineVersion $path = $config.products[$product].changelog if (Split-Path $path) { New-Item (Split-Path $path) -ItemType Directory -Force | Out-Null } @@ -521,6 +526,7 @@ function global:gh { @{ title = 'Fix: Valid title'; labels = @('product:core'); valid = $true }, @{ title = 'Maintenance'; labels = @(@{ name = 'product:none' }, @{ name = 'change:chore' }); valid = $true }, @{ title = 'Fix: Missing product'; labels = @(); valid = $false }, + @{ title = 'Add: Permission analyzer'; labels = @('product:permissions'); valid = $true }, @{ title = 'Fix: Exclusive product'; labels = @('product:none', 'product:core'); valid = $false }, @{ title = 'Missing category'; labels = @('product:core'); valid = $false }, @{ title = 'Add: Conflict'; labels = @('product:core', 'change:fix'); valid = $false }, @@ -583,7 +589,7 @@ function Assert-PackageValidation([bool]$Valid) { try { New-Item (Join-Path $root '.release/packages') -ItemType Directory -Force | Out-Null Set-Location $root; $env:RELEASE_TAG = $null; $env:GITHUB_REPOSITORY = 'owner/repo' - foreach ($product in @('core', 'metadata')) { + foreach ($product in ($config.products.Keys | Sort-Object)) { Remove-Item '.release/packages/*' -Force -ErrorAction SilentlyContinue $id = $config.products[$product].packageId; $version = '2.0.0-rc.1' $script:TestReleaseNotes = "### $version - 13 November 2026`n" + '* Fix: Preserve $$ and $& (#1)' @@ -631,7 +637,7 @@ try { Remove-Item '.release/packages/other.nupkg' Remove-Item $symbols; Assert-PackageValidation $false } - Write-Output 'PASS: both product package/symbol pairs include matching release notes and versioned changelogs; stale notes, missing changelogs, wrong metadata and invalid pairs fail' + Write-Output 'PASS: all product package/symbol pairs include matching release notes and versioned changelogs; stale notes, missing changelogs, wrong metadata and invalid pairs fail' } finally { Set-Location $old; $env:RELEASE_TAG = $oldTag; $env:GITHUB_REPOSITORY = $oldPackageRepository Remove-Item $root -Recurse -Force diff --git a/scripts/release/config.json b/scripts/release/config.json index d693bdc3..a5b804a1 100644 --- a/scripts/release/config.json +++ b/scripts/release/config.json @@ -16,6 +16,14 @@ "versionProperty": "MetadataReleaseVersion", "notesProperty": "MetadataReleaseNotesPath", "baselineVersion": "1.2.0" + }, + "permissions": { + "packageId": "XrmMockup.PermissionAnalyzer", + "project": "src/PermissionAnalyzer/PermissionAnalyzer.Tool/PermissionAnalyzer.Tool.csproj", + "changelog": "src/PermissionAnalyzer/PermissionAnalyzer.Tool/CHANGELOG.md", + "versionProperty": "PermissionsReleaseVersion", + "notesProperty": "PermissionsReleaseNotesPath", + "baselineVersion": "1.0.0-rc.1" } }, "categories": { diff --git a/scripts/release/validate-packages.ps1 b/scripts/release/validate-packages.ps1 index 0d4b9ab8..0082c1c7 100644 --- a/scripts/release/validate-packages.ps1 +++ b/scripts/release/validate-packages.ps1 @@ -4,7 +4,8 @@ Add-Type -AssemblyName System.IO.Compression.FileSystem $release = Get-Content '.release/release.json' -Raw | ConvertFrom-Json if ($release.tag -cne "$($release.product)-v$($release.version)") { throw 'Release version differs from the tag' } $config = Get-Content (Join-Path $PSScriptRoot 'config.json') -Raw | ConvertFrom-Json -AsHashtable -$id = if ($release.product -eq 'core') { 'XrmMockup365' } elseif ($release.product -eq 'metadata') { 'XrmMockup.MetadataGenerator' } else { throw 'Unknown product' } +if (!$config.products.ContainsKey($release.product)) { throw 'Unknown product' } +$id = $config.products[$release.product].packageId $changelogName = Split-Path $config.products[$release.product].changelog -Leaf $notes = (Get-Content '.release/notes.md' -Raw).Replace("`r`n", "`n").TrimEnd() $packageHistoryNotes = (Get-Content '.release/package-notes.md' -Raw).Replace("`r`n", "`n").TrimEnd() diff --git a/src/MetadataGen/MetadataGenerator.Core/Extensions/ServiceCollectionExtensions.cs b/src/MetadataGen/MetadataGenerator.Core/Extensions/ServiceCollectionExtensions.cs index c16b3de0..5472ac65 100644 --- a/src/MetadataGen/MetadataGenerator.Core/Extensions/ServiceCollectionExtensions.cs +++ b/src/MetadataGen/MetadataGenerator.Core/Extensions/ServiceCollectionExtensions.cs @@ -32,6 +32,7 @@ public static IServiceCollection AddMetadataGeneratorServices(this IServiceColle services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/MetadataGen/MetadataGenerator.Core/Readers/IPrivilegeReader.cs b/src/MetadataGen/MetadataGenerator.Core/Readers/IPrivilegeReader.cs new file mode 100644 index 00000000..09870e0e --- /dev/null +++ b/src/MetadataGen/MetadataGenerator.Core/Readers/IPrivilegeReader.cs @@ -0,0 +1,15 @@ +using DG.Tools.XrmMockup; + +namespace XrmMockup.MetadataGenerator.Core.Readers; + +/// +/// Reads the privileges in Dataverse and the execute privileges of custom APIs. +/// +public interface IPrivilegeReader +{ + /// + /// Gets every privilege with the tables it applies to, and every custom API that has an execute privilege. + /// Both are sorted by name. + /// + Task GetPrivilegeCatalogAsync(CancellationToken ct = default); +} diff --git a/src/MetadataGen/MetadataGenerator.Core/Readers/PrivilegeReader.cs b/src/MetadataGen/MetadataGenerator.Core/Readers/PrivilegeReader.cs new file mode 100644 index 00000000..ec621cd1 --- /dev/null +++ b/src/MetadataGen/MetadataGenerator.Core/Readers/PrivilegeReader.cs @@ -0,0 +1,80 @@ +using DG.Tools.XrmMockup; +using Microsoft.Crm.Sdk.Messages; +using Microsoft.Extensions.Logging; +using Microsoft.Xrm.Sdk; +using Microsoft.Xrm.Sdk.Query; +using XrmMockup.MetadataGenerator.Core.Connection; + +namespace XrmMockup.MetadataGenerator.Core.Readers; + +/// +/// Reads the privileges in Dataverse and the execute privileges of custom APIs. +/// +internal sealed class PrivilegeReader( + IOrganizationServiceProvider serviceProvider, + ILogger logger) : IPrivilegeReader +{ + /// + /// The object type code of privileges that aren't tied to a table. + /// + internal const string NoTable = "none"; + + private readonly IOrganizationService _service = serviceProvider.Service; + + public async Task GetPrivilegeCatalogAsync(CancellationToken ct = default) + { + logger.LogInformation("Getting privileges"); + + return await Task.Run(() => + { + var privileges = _service.RetrieveAll(new QueryExpression("privilege") + { + ColumnSet = new ColumnSet("privilegeid", "name", "accessright") + }); + + var tables = _service.RetrieveAll(new QueryExpression("privilegeobjecttypecodes") + { + ColumnSet = new ColumnSet("privilegeid", "objecttypecode") + }) + .Where(e => e.GetAttributeValue("privilegeid") is not null && e.GetAttributeValue("objecttypecode") is { } table && table != NoTable) + .ToLookup(e => e.GetAttributeValue("privilegeid").Id, e => e.GetAttributeValue("objecttypecode")); + + // Every custom API, also those without an execute privilege, so a call to one is known to need none + var customApis = _service.RetrieveAll(new QueryExpression("customapi") + { + ColumnSet = new ColumnSet("uniquename", "executeprivilegename") + }); + + var catalog = new PrivilegeCatalog + { + Privileges = privileges + .Where(p => !string.IsNullOrEmpty(p.GetAttributeValue("name"))) + .Select(p => new MetaPrivilege + { + Name = p.GetAttributeValue("name"), + PrivilegeId = p.Id, + AccessRight = p.GetAttributeValue("accessright"), + Tables = [.. tables[p.Id].Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)] + }) + .OrderBy(p => p.Name, StringComparer.Ordinal) + .ThenBy(p => p.PrivilegeId) + .ToList(), + CustomApis = customApis + .Where(a => !string.IsNullOrEmpty(a.GetAttributeValue("uniquename"))) + .Select(a => new MetaCustomApi + { + UniqueName = a.GetAttributeValue("uniquename"), + ExecutePrivilegeName = a.GetAttributeValue("executeprivilegename") is { Length: > 0 } privilege ? privilege : null + }) + .OrderBy(a => a.UniqueName, StringComparer.Ordinal) + .ToList() + }; + + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Retrieved {Count} privileges and {CustomApis} custom APIs", catalog.Privileges.Count, catalog.CustomApis.Count); + } + return catalog; + }, ct); + } +} diff --git a/src/MetadataGen/MetadataGenerator.Core/Readers/QueryExtensions.cs b/src/MetadataGen/MetadataGenerator.Core/Readers/QueryExtensions.cs new file mode 100644 index 00000000..2b175006 --- /dev/null +++ b/src/MetadataGen/MetadataGenerator.Core/Readers/QueryExtensions.cs @@ -0,0 +1,28 @@ +using Microsoft.Xrm.Sdk; +using Microsoft.Xrm.Sdk.Query; + +namespace XrmMockup.MetadataGenerator.Core.Readers; + +internal static class QueryExtensions +{ + /// + /// Every record the query matches, page by page. + /// + public static List RetrieveAll(this IOrganizationService service, QueryExpression query) + { + query.PageInfo.PageNumber = 1; + var entities = new List(); + var resp = service.RetrieveMultiple(query); + entities.AddRange(resp.Entities); + + while (resp.MoreRecords) + { + query.PageInfo.PageNumber++; + query.PageInfo.PagingCookie = resp.PagingCookie; + resp = service.RetrieveMultiple(query); + entities.AddRange(resp.Entities); + } + + return entities; + } +} diff --git a/src/MetadataGen/MetadataGenerator.Core/Readers/SecurityRoleReader.cs b/src/MetadataGen/MetadataGenerator.Core/Readers/SecurityRoleReader.cs index c1b5b468..8529aabd 100644 --- a/src/MetadataGen/MetadataGenerator.Core/Readers/SecurityRoleReader.cs +++ b/src/MetadataGen/MetadataGenerator.Core/Readers/SecurityRoleReader.cs @@ -43,22 +43,22 @@ public async Task> GetSecurityRolesAsync( } // Query all required data - var privileges = QueryPaging(new QueryExpression(Privilege) + var privileges = _service.RetrieveAll(new QueryExpression(Privilege) { - ColumnSet = new ColumnSet("privilegeid", "accessright", "canbeglobal", "canbedeep", "canbelocal", "canbebasic") + ColumnSet = new ColumnSet("privilegeid", "name", "accessright", "canbeglobal", "canbedeep", "canbelocal", "canbebasic") }); - var privilegeOTCs = QueryPaging(new QueryExpression(PrivilegeOtc) + var privilegeOTCs = _service.RetrieveAll(new QueryExpression(PrivilegeOtc) { ColumnSet = new ColumnSet("privilegeid", "objecttypecode") }); - var rolePrivileges = QueryPaging(new QueryExpression(RolePrivileges) + var rolePrivileges = _service.RetrieveAll(new QueryExpression(RolePrivileges) { ColumnSet = new ColumnSet("privilegeid", "roleid", "privilegedepthmask") }); - var roleList = QueryPaging(GetRoleQuery(roleIdsToInclude)); + var roleList = _service.RetrieveAll(GetRoleQuery(roleIdsToInclude)); // Join: roleprivileges inner join roles // Use GetAttributeValue for defensive access in case parentrootroleid is missing @@ -96,11 +96,12 @@ from rpr in res.DefaultIfEmpty() foreach (var e in validSecurityRoles) { var entityName = (string)e.pp.privilegeOTC!["objecttypecode"]; - - if (entityName == "none") continue; + var global = entityName == PrivilegeReader.NoTable; + var privilegeName = e.pp.privilege!.GetAttributeValue("name"); + if (global && string.IsNullOrEmpty(privilegeName)) continue; var rp = ToRolePrivilege(e.pp.privilege!, e.rpr!.roleprivilege); - if (rp.AccessRight == AccessRights.None) continue; + if (!global && rp.AccessRight == AccessRights.None) continue; var roleId = (Guid)e.rpr.roleprivilege["roleid"]; if (!roles.TryGetValue(roleId, out var roleValue)) @@ -127,7 +128,8 @@ from rpr in res.DefaultIfEmpty() { Name = name, RoleId = roleId, - Privileges = [] + Privileges = [], + GlobalPrivileges = [] }; roles[roleId] = roleValue; @@ -137,6 +139,13 @@ from rpr in res.DefaultIfEmpty() } } + // Privileges that aren't tied to a table are kept apart, so XrmMockup's table checks don't see them + if (global) + { + roleValue.GlobalPrivileges.TryAdd(privilegeName, rp); + continue; + } + if (!roleValue.Privileges.TryGetValue(entityName, out var value)) { value = []; @@ -154,24 +163,6 @@ from rpr in res.DefaultIfEmpty() }, ct); } - private List QueryPaging(QueryExpression query) - { - query.PageInfo.PageNumber = 1; - var entities = new List(); - var resp = _service.RetrieveMultiple(query); - entities.AddRange(resp.Entities); - - while (resp.MoreRecords) - { - query.PageInfo.PageNumber++; - query.PageInfo.PagingCookie = resp.PagingCookie; - resp = _service.RetrieveMultiple(query); - entities.AddRange(resp.Entities); - } - - return entities; - } - private static DG.Tools.XrmMockup.RolePrivilege ToRolePrivilege(Entity privilege, Entity rolePrivilege) { return new DG.Tools.XrmMockup.RolePrivilege diff --git a/src/MetadataGen/MetadataGenerator.Core/Services/DataContractMetadataSerializer.cs b/src/MetadataGen/MetadataGenerator.Core/Services/DataContractMetadataSerializer.cs index 2cbfe3e7..88acf2ad 100644 --- a/src/MetadataGen/MetadataGenerator.Core/Services/DataContractMetadataSerializer.cs +++ b/src/MetadataGen/MetadataGenerator.Core/Services/DataContractMetadataSerializer.cs @@ -16,6 +16,11 @@ internal sealed partial class DataContractMetadataSerializer( IOptions options, ILogger logger) : IMetadataSerializer { + /// + /// The file the privilege catalog is written to, next to Metadata.xml. + /// + public const string PrivilegeCatalogFile = "PrivilegeCatalog.xml"; + private readonly GeneratorOptions _options = options.Value; public async Task SerializeMetadataAsync( @@ -117,6 +122,28 @@ await Task.Run(() => }, ct); } + public async Task SerializePrivilegeCatalogAsync( + PrivilegeCatalog catalog, + CancellationToken ct = default) + { + await Task.Run(() => + { + Directory.CreateDirectory(_options.OutputDirectory); + + var serializer = new DataContractSerializer(typeof(PrivilegeCatalog)); + var catalogPath = Path.Combine(_options.OutputDirectory, PrivilegeCatalogFile); + + using var stream = new FileStream(catalogPath, FileMode.Create); + using var writer = CreateXmlWriter(stream); + serializer.WriteObject(writer, catalog); + + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation("Written {Count} privileges to {Path}", catalog.Privileges.Count, catalogPath); + } + }, ct); + } + public async Task GenerateTypeDeclarationsAsync( Dictionary securityRoles, CancellationToken ct = default) diff --git a/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSerializer.cs b/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSerializer.cs index 7918de77..a8a1ef7b 100644 --- a/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSerializer.cs +++ b/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSerializer.cs @@ -23,6 +23,11 @@ public interface IMetadataSerializer /// Task SerializeSecurityRolesAsync(Dictionary securityRoles, CancellationToken ct = default); + /// + /// Serializes the privilege catalog to the configured output directory. + /// + Task SerializePrivilegeCatalogAsync(PrivilegeCatalog catalog, CancellationToken ct = default); + /// /// Generates the TypeDeclarations.cs file with security role GUIDs. /// diff --git a/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSource.cs b/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSource.cs index 5d390c83..eac30c12 100644 --- a/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSource.cs +++ b/src/MetadataGen/MetadataGenerator.Core/Services/IMetadataSource.cs @@ -22,4 +22,9 @@ public interface IMetadataSource /// Gets security roles. /// Task> GetSecurityRolesAsync(Guid rootBusinessUnitId, CancellationToken ct = default); + + /// + /// Gets every privilege and the execute privileges of custom APIs. + /// + Task GetPrivilegeCatalogAsync(CancellationToken ct = default); } diff --git a/src/MetadataGen/MetadataGenerator.Core/Services/MetadataGeneratorService.cs b/src/MetadataGen/MetadataGenerator.Core/Services/MetadataGeneratorService.cs index a93f8906..fc865ba2 100644 --- a/src/MetadataGen/MetadataGenerator.Core/Services/MetadataGeneratorService.cs +++ b/src/MetadataGen/MetadataGenerator.Core/Services/MetadataGeneratorService.cs @@ -35,10 +35,14 @@ public async Task GenerateAsync(CancellationToken ct = default) skeleton.RootBusinessUnit.Id, ct); + // Get the privilege catalog + var privilegeCatalog = await metadataSource.GetPrivilegeCatalogAsync(ct); + // Serialize all outputs await serializer.SerializeMetadataAsync(skeleton, ct); await serializer.SerializeWorkflowsAsync(workflows, ct); await serializer.SerializeSecurityRolesAsync(securityRoles, ct); + await serializer.SerializePrivilegeCatalogAsync(privilegeCatalog, ct); await serializer.GenerateTypeDeclarationsAsync(securityRoles, ct); logger.LogInformation("Metadata generation completed successfully"); diff --git a/src/MetadataGen/MetadataGenerator.Core/Services/OnlineMetadataSource.cs b/src/MetadataGen/MetadataGenerator.Core/Services/OnlineMetadataSource.cs index d758d2e6..c2ac9a01 100644 --- a/src/MetadataGen/MetadataGenerator.Core/Services/OnlineMetadataSource.cs +++ b/src/MetadataGen/MetadataGenerator.Core/Services/OnlineMetadataSource.cs @@ -18,6 +18,7 @@ internal sealed class OnlineMetadataSource( IOptionSetReader optionSetReader, ICurrencyReader currencyReader, IOrganizationReader organizationReader, + IPrivilegeReader privilegeReader, IOptions options, ILogger logger) : IMetadataSource { @@ -81,4 +82,9 @@ public async Task> GetSecurityRolesAsync( _options.AllSecurityRoles, ct); } + + public async Task GetPrivilegeCatalogAsync(CancellationToken ct = default) + { + return await privilegeReader.GetPrivilegeCatalogAsync(ct); + } } diff --git a/src/MetadataGen/MetadataGenerator.Tool.Tests/Readers/PrivilegeReaderTests.cs b/src/MetadataGen/MetadataGenerator.Tool.Tests/Readers/PrivilegeReaderTests.cs new file mode 100644 index 00000000..f305fd8c --- /dev/null +++ b/src/MetadataGen/MetadataGenerator.Tool.Tests/Readers/PrivilegeReaderTests.cs @@ -0,0 +1,123 @@ +using DG.Tools.XrmMockup; +using Microsoft.Crm.Sdk.Messages; +using Microsoft.Extensions.Logging; +using Microsoft.Xrm.Sdk; +using Microsoft.Xrm.Sdk.Query; +using NSubstitute; +using Xunit; +using XrmMockup.MetadataGenerator.Core.Readers; +using XrmMockup.MetadataGenerator.Tool.Tests.Fixtures; + +namespace XrmMockup.MetadataGenerator.Tool.Tests.Readers; + +/// +/// Tests for PrivilegeReader. +/// XrmMockup doesn't hold privilege records, so the service returns canned records per table. +/// +public class PrivilegeReaderTests +{ + private static readonly Guid ReadOrder = Guid.NewGuid(); + private static readonly Guid AppendActivity = Guid.NewGuid(); + private static readonly Guid ActOnBehalf = Guid.NewGuid(); + + private readonly IOrganizationService _service = Substitute.For(); + private readonly List _queries = []; + + public PrivilegeReaderTests() + { + Returns("privilege", + Privilege(ReadOrder, "prvReadctx_Order", AccessRights.ReadAccess), + Privilege(AppendActivity, "prvAppendActivity", AccessRights.AppendAccess), + Privilege(ActOnBehalf, "prvActOnBehalfOfAnotherUser", AccessRights.None), + Privilege(Guid.NewGuid(), null, AccessRights.ReadAccess)); + Returns("privilegeobjecttypecodes", + Table(ReadOrder, "ctx_order"), + Table(AppendActivity, "task"), + Table(AppendActivity, "email"), + Table(AppendActivity, "task"), + Table(ActOnBehalf, PrivilegeReader.NoTable)); + Returns("customapi", + CustomApi("ctx_Submit", "prvReadctx_Order"), + CustomApi("ctx_Approve", "prvActOnBehalfOfAnotherUser"), + CustomApi("ctx_Ping", null)); + } + + private PrivilegeReader CreateReader() => + new(new MockOrganizationServiceProvider(_service), Substitute.For>()); + + [Fact] + public async Task GetPrivilegeCatalogAsync_ReturnsNamedPrivilegesSortedByName() + { + var catalog = await CreateReader().GetPrivilegeCatalogAsync(); + + Assert.Equal(["prvActOnBehalfOfAnotherUser", "prvAppendActivity", "prvReadctx_Order"], catalog.Privileges.Select(p => p.Name)); + Assert.Equal(AccessRights.AppendAccess, catalog.Privileges[1].AccessRight); + Assert.Equal(AppendActivity, catalog.Privileges[1].PrivilegeId); + } + + [Fact] + public async Task GetPrivilegeCatalogAsync_ListsTablesSortedAndDistinct() + { + var catalog = await CreateReader().GetPrivilegeCatalogAsync(); + + Assert.Equal(["email", "task"], catalog.Privileges.Single(p => p.Name == "prvAppendActivity").Tables); + Assert.Equal(["ctx_order"], catalog.Privileges.Single(p => p.Name == "prvReadctx_Order").Tables); + } + + [Fact] + public async Task GetPrivilegeCatalogAsync_LeavesTablesEmptyForGlobalPrivileges() + { + var catalog = await CreateReader().GetPrivilegeCatalogAsync(); + + Assert.Empty(catalog.Privileges.Single(p => p.Name == "prvActOnBehalfOfAnotherUser").Tables); + } + + [Fact] + public async Task GetPrivilegeCatalogAsync_ReturnsCustomApisSortedByName() + { + var catalog = await CreateReader().GetPrivilegeCatalogAsync(); + + Assert.Equal(["ctx_Approve", "ctx_Ping", "ctx_Submit"], catalog.CustomApis.Select(a => a.UniqueName)); + Assert.Equal("prvReadctx_Order", catalog.CustomApis[2].ExecutePrivilegeName); + } + + [Fact] + public async Task GetPrivilegeCatalogAsync_ReturnsCustomApisWithoutAnExecutePrivilege() + { + var catalog = await CreateReader().GetPrivilegeCatalogAsync(); + + Assert.Null(catalog.CustomApis.Single(a => a.UniqueName == "ctx_Ping").ExecutePrivilegeName); + Assert.Empty(_queries.Single(q => q.EntityName == "customapi").Criteria.Conditions); + } + + private void Returns(string table, params Entity[] entities) + { + _service.RetrieveMultiple(Arg.Is(q => q.EntityName == table)) + .Returns(call => + { + _queries.Add(call.Arg()); + return new EntityCollection([.. entities]); + }); + } + + private static Entity Privilege(Guid id, string? name, AccessRights accessRight) => + new("privilege", id) + { + ["name"] = name, + ["accessright"] = (int)accessRight + }; + + private static Entity Table(Guid privilegeId, string table) => + new("privilegeobjecttypecodes", Guid.NewGuid()) + { + ["privilegeid"] = new EntityReference("privilege", privilegeId), + ["objecttypecode"] = table + }; + + private static Entity CustomApi(string uniqueName, string? executePrivilegeName) => + new("customapi", Guid.NewGuid()) + { + ["uniquename"] = uniqueName, + ["executeprivilegename"] = executePrivilegeName + }; +} diff --git a/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/DataContractMetadataSerializerTests.cs b/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/DataContractMetadataSerializerTests.cs index d9982de3..4b3f1f67 100644 --- a/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/DataContractMetadataSerializerTests.cs +++ b/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/DataContractMetadataSerializerTests.cs @@ -237,6 +237,74 @@ public async Task GenerateTypeDeclarationsAsync_CreatesTypeDeclarationsFile() Assert.True(File.Exists(typeDefPath)); } + [Fact] + public async Task SerializeSecurityRolesAsync_RoundTripsGlobalPrivileges() + { + var roleId = Guid.NewGuid(); + var role = new SecurityRole + { + Name = "Test Role", + RoleId = roleId, + Privileges = [], + GlobalPrivileges = new Dictionary + { + ["prvActOnBehalfOfAnotherUser"] = new RolePrivilege { CanBeGlobal = true, PrivilegeDepth = PrivilegeDepth.Global } + } + }; + + await _serializer.SerializeSecurityRolesAsync(new Dictionary { { roleId, role } }); + + var file = Directory.GetFiles(Path.Combine(_testOutputDir, "SecurityRoles"), "*.xml").Single(); + await using var stream = new FileStream(file, FileMode.Open); + var deserialized = (SecurityRole?)new DataContractSerializer(typeof(SecurityRole)).ReadObject(stream); + var privilege = Assert.Single(deserialized!.GlobalPrivileges); + Assert.Equal("prvActOnBehalfOfAnotherUser", privilege.Key); + Assert.Equal(PrivilegeDepth.Global, privilege.Value.PrivilegeDepth); + } + + [Fact] + public async Task SecurityRole_WithoutGlobalPrivileges_DeserializesWithNull() + { + var roleId = Guid.NewGuid(); + var role = new SecurityRole { Name = "Test Role", RoleId = roleId, Privileges = [] }; + await _serializer.SerializeSecurityRolesAsync(new Dictionary { { roleId, role } }); + var file = Directory.GetFiles(Path.Combine(_testOutputDir, "SecurityRoles"), "*.xml").Single(); + + // Role files generated before global privileges were downloaded have no GlobalPrivileges element + var xml = System.Text.RegularExpressions.Regex.Replace(await File.ReadAllTextAsync(file), "]*/>", ""); + Assert.DoesNotContain("GlobalPrivileges", xml); + using var reader = System.Xml.XmlReader.Create(new StringReader(xml)); + var deserialized = (SecurityRole?)new DataContractSerializer(typeof(SecurityRole)).ReadObject(reader); + + Assert.NotNull(deserialized); + Assert.Null(deserialized.GlobalPrivileges); + } + + [Fact] + public async Task SerializePrivilegeCatalogAsync_CreatesDeserializableFile() + { + var catalog = new PrivilegeCatalog + { + Privileges = + [ + new MetaPrivilege { Name = "prvReadAccount", PrivilegeId = Guid.NewGuid(), AccessRight = AccessRights.ReadAccess, Tables = ["account"] }, + new MetaPrivilege { Name = "prvActOnBehalfOfAnotherUser", PrivilegeId = Guid.NewGuid(), AccessRight = AccessRights.None, Tables = [] } + ], + CustomApis = [new MetaCustomApi { UniqueName = "ctx_Submit", ExecutePrivilegeName = "prvReadAccount" }] + }; + + await _serializer.SerializePrivilegeCatalogAsync(catalog); + + var path = Path.Combine(_testOutputDir, DataContractMetadataSerializer.PrivilegeCatalogFile); + await using var stream = new FileStream(path, FileMode.Open); + var deserialized = (PrivilegeCatalog?)new DataContractSerializer(typeof(PrivilegeCatalog)).ReadObject(stream); + Assert.NotNull(deserialized); + Assert.Equal(["prvReadAccount", "prvActOnBehalfOfAnotherUser"], deserialized.Privileges.Select(p => p.Name)); + Assert.Equal(["account"], deserialized.Privileges[0].Tables); + Assert.Equal(AccessRights.ReadAccess, deserialized.Privileges[0].AccessRight); + Assert.Equal("prvReadAccount", Assert.Single(deserialized.CustomApis).ExecutePrivilegeName); + } + [Fact] public async Task GenerateTypeDeclarationsAsync_ContainsNamespace() { diff --git a/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/MetadataGeneratorServiceTests.cs b/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/MetadataGeneratorServiceTests.cs index 901960a7..a6d8436f 100644 --- a/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/MetadataGeneratorServiceTests.cs +++ b/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/MetadataGeneratorServiceTests.cs @@ -23,6 +23,7 @@ public class MetadataGeneratorServiceTests private readonly MetadataSkeleton _skeleton; private readonly List _workflows; private readonly Dictionary _securityRoles; + private readonly PrivilegeCatalog _privilegeCatalog; public MetadataGeneratorServiceTests() { @@ -47,6 +48,7 @@ public MetadataGeneratorServiceTests() { { Guid.NewGuid(), new SecurityRole { Name = "Test Role", RoleId = Guid.NewGuid(), Privileges = [] } } }; + _privilegeCatalog = new PrivilegeCatalog { Privileges = [], CustomApis = [] }; // Setup mocks _metadataSource.GetMetadataAsync(Arg.Any()) @@ -55,6 +57,8 @@ public MetadataGeneratorServiceTests() .Returns(_workflows); _metadataSource.GetSecurityRolesAsync(Arg.Any(), Arg.Any()) .Returns(_securityRoles); + _metadataSource.GetPrivilegeCatalogAsync(Arg.Any()) + .Returns(_privilegeCatalog); } private MetadataGeneratorService CreateService(GeneratorOptions options) @@ -147,6 +151,19 @@ await _serializer.Received(1).SerializeSecurityRolesAsync( Arg.Any()); } + [Fact] + public async Task GenerateAsync_SerializesPrivilegeCatalog() + { + var options = new GeneratorOptions { OutputDirectory = "/test", Solutions = [], Entities = [] }; + var service = CreateService(options); + + await service.GenerateAsync(); + + await _serializer.Received(1).SerializePrivilegeCatalogAsync( + Arg.Is(c => c == _privilegeCatalog), + Arg.Any()); + } + [Fact] public async Task GenerateAsync_GeneratesTypeDeclarations() { @@ -173,9 +190,11 @@ public async Task GenerateAsync_CallsSerializersAfterFetchingAllData() _metadataSource.GetMetadataAsync(Arg.Any()); _metadataSource.GetWorkflowsAsync(Arg.Any()); _metadataSource.GetSecurityRolesAsync(Arg.Any(), Arg.Any()); + _metadataSource.GetPrivilegeCatalogAsync(Arg.Any()); _serializer.SerializeMetadataAsync(Arg.Any(), Arg.Any()); _serializer.SerializeWorkflowsAsync(Arg.Any>(), Arg.Any()); _serializer.SerializeSecurityRolesAsync(Arg.Any>(), Arg.Any()); + _serializer.SerializePrivilegeCatalogAsync(Arg.Any(), Arg.Any()); _serializer.GenerateTypeDeclarationsAsync(Arg.Any>(), Arg.Any()); }); } diff --git a/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/OnlineMetadataSourceTests.cs b/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/OnlineMetadataSourceTests.cs index 59f93814..23d887b7 100644 --- a/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/OnlineMetadataSourceTests.cs +++ b/src/MetadataGen/MetadataGenerator.Tool.Tests/Services/OnlineMetadataSourceTests.cs @@ -25,6 +25,7 @@ public class OnlineMetadataSourceTests private readonly IOptionSetReader _optionSetReader; private readonly ICurrencyReader _currencyReader; private readonly IOrganizationReader _organizationReader; + private readonly IPrivilegeReader _privilegeReader; private readonly ILogger _logger; public OnlineMetadataSourceTests() @@ -36,6 +37,7 @@ public OnlineMetadataSourceTests() _optionSetReader = Substitute.For(); _currencyReader = Substitute.For(); _organizationReader = Substitute.For(); + _privilegeReader = Substitute.For(); _logger = Substitute.For>(); // Setup default mock returns @@ -69,6 +71,7 @@ private OnlineMetadataSource CreateSource(GeneratorOptions options) _optionSetReader, _currencyReader, _organizationReader, + _privilegeReader, Options.Create(options), _logger); } @@ -390,4 +393,16 @@ await _entityMetadataReader.Received(1).GetEntityMetadataAsync( Arg.Any(), Arg.Is(ct => ct == cts.Token)); } + + [Fact] + public async Task GetPrivilegeCatalogAsync_ReturnsCatalogFromReader() + { + var catalog = new PrivilegeCatalog { Privileges = [], CustomApis = [] }; + _privilegeReader.GetPrivilegeCatalogAsync(Arg.Any()).Returns(catalog); + var source = CreateSource(new GeneratorOptions { OutputDirectory = "/test", Solutions = [], Entities = [] }); + + var result = await source.GetPrivilegeCatalogAsync(); + + Assert.Same(catalog, result); + } } diff --git a/src/MetadataGen/MetadataGenerator.Tool/CHANGELOG.md b/src/MetadataGen/MetadataGenerator.Tool/CHANGELOG.md index 862e8141..7dba3d74 100644 --- a/src/MetadataGen/MetadataGenerator.Tool/CHANGELOG.md +++ b/src/MetadataGen/MetadataGenerator.Tool/CHANGELOG.md @@ -7,7 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Unreleased -* No unreleased changes. +* Add: `PrivilegeCatalog.xml` with every privilege (name, access right and tables) and every custom API with its execute privilege, for the permission analyzer +* Add: Security role files list the role's privileges that aren't tied to a table, such as `prvActOnBehalfOfAnotherUser`, under `GlobalPrivileges`. XrmMockup ignores them, and role files generated before still load ### v1.2.0 - 11 September 2026 diff --git a/src/MetadataGen/MetadataGenerator.Tool/Extensions/ServiceCollectionExtensions.cs b/src/MetadataGen/MetadataGenerator.Tool/Extensions/ServiceCollectionExtensions.cs index db42a664..93230e08 100644 --- a/src/MetadataGen/MetadataGenerator.Tool/Extensions/ServiceCollectionExtensions.cs +++ b/src/MetadataGen/MetadataGenerator.Tool/Extensions/ServiceCollectionExtensions.cs @@ -4,8 +4,8 @@ using Microsoft.Extensions.Logging.Console; using XrmMockup.MetadataGenerator.Core.Extensions; using XrmMockup.MetadataGenerator.Core.Models; -using XrmMockup.MetadataGenerator.Tool.Logging; using XrmMockup.MetadataGenerator.Tool.Options; +using XrmMockup.Tools.Common.Logging; using MsOptions = Microsoft.Extensions.Options; @@ -62,11 +62,7 @@ public static IServiceCollection AddToolLogging(this IServiceCollection services builder .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) - .AddConsole(options => - { - options.FormatterName = ShortCategoryConsoleFormatter.FormatterName; - }) - .AddConsoleFormatter(options => + .AddShortCategoryConsole(options => { options.TimestampFormat = "HH:mm:ss "; options.ColorBehavior = LoggerColorBehavior.Enabled; diff --git a/src/MetadataGen/MetadataGenerator.Tool/MetadataGenerator.Tool.csproj b/src/MetadataGen/MetadataGenerator.Tool/MetadataGenerator.Tool.csproj index a1a0751e..fbc02723 100644 --- a/src/MetadataGen/MetadataGenerator.Tool/MetadataGenerator.Tool.csproj +++ b/src/MetadataGen/MetadataGenerator.Tool/MetadataGenerator.Tool.csproj @@ -18,6 +18,7 @@ + diff --git a/src/MetadataGen/MetadataGenerator.Tool/README.md b/src/MetadataGen/MetadataGenerator.Tool/README.md index 3b69adf9..415e30b7 100644 --- a/src/MetadataGen/MetadataGenerator.Tool/README.md +++ b/src/MetadataGen/MetadataGenerator.Tool/README.md @@ -225,7 +225,8 @@ The tool generates the following files in the output directory: |------|----------| | `Metadata.xml` | Serialized MetadataSkeleton containing entity metadata, option sets, plugins, currencies, and organization settings | | `Workflows/` | Individual XML files for each workflow definition | -| `SecurityRoles/` | Individual XML files for each security role with privilege definitions | +| `SecurityRoles/` | Individual XML files for each security role with privilege definitions. Privileges that aren't tied to a table, such as `prvActOnBehalfOfAnotherUser`, are listed separately under `GlobalPrivileges` | +| `PrivilegeCatalog.xml` | Every privilege in the environment with its access right and tables, and every custom API with its execute privilege, if any. XrmMockup doesn't read it; the permission analyzer (`xrmmockup-permissions`) uses it to look up privileges by name | | `TypeDeclarations.cs` | C# source file with security role GUIDs for use in tests | ## Using with XrmMockup diff --git a/src/MetadataSkeleton/MetadataSkeleton.cs b/src/MetadataSkeleton/MetadataSkeleton.cs index 6b0c41df..868c1302 100644 --- a/src/MetadataSkeleton/MetadataSkeleton.cs +++ b/src/MetadataSkeleton/MetadataSkeleton.cs @@ -92,7 +92,7 @@ public RolePrivilege Clone() clone.CanBeGlobal = this.CanBeGlobal; clone.CanBeDeep = this.CanBeDeep; clone.CanBeLocal = this.CanBeLocal; - clone.CanBeLocal = this.CanBeLocal; + clone.CanBeBasic = this.CanBeBasic; clone.AccessRight = this.AccessRight; clone.PrivilegeDepth = this.PrivilegeDepth; @@ -102,6 +102,12 @@ public RolePrivilege Clone() public class SecurityRole { public Dictionary> Privileges; + + /// + /// Privileges that aren't tied to a table, such as prvActOnBehalfOfAnotherUser, by privilege name. + /// Null in metadata generated before they were downloaded. + /// + public Dictionary GlobalPrivileges; public string Name; public EntityReference BusinessUnitId; public Guid RoleId; @@ -123,6 +129,15 @@ public SecurityRole Clone() clone.Privileges.Add(p.Key, p.Value); } + if (this.GlobalPrivileges != null) + { + clone.GlobalPrivileges = new Dictionary(); + foreach (var priv in this.GlobalPrivileges) + { + clone.GlobalPrivileges.Add(priv.Key, priv.Value.Clone()); + } + } + clone.Name = "Clone of " + this.Name; clone.BusinessUnitId = this.BusinessUnitId; clone.RoleId = Guid.NewGuid(); @@ -131,4 +146,37 @@ public SecurityRole Clone() return clone; } } + + /// + /// Every privilege in the environment and every custom API with its execute privilege, so a privilege name can be + /// looked up as a table and access right. Written to PrivilegeCatalog.xml next to Metadata.xml. + /// + public class PrivilegeCatalog { + public List Privileges; + public List CustomApis; + } + + public class MetaPrivilege { + public string Name; + public Guid PrivilegeId; + public AccessRights AccessRight; + + /// + /// Logical names of the tables the privilege applies to, sorted. Empty for a privilege that isn't tied to a + /// table. + /// + public List Tables; + } + + /// + /// A custom API and the privilege it needs to be called. + /// + public class MetaCustomApi { + public string UniqueName; + + /// + /// Null when the custom API needs no privilege. + /// + public string ExecutePrivilegeName; + } } diff --git a/src/PermissionAnalyzer/Directory.Build.props b/src/PermissionAnalyzer/Directory.Build.props new file mode 100644 index 00000000..8c69067f --- /dev/null +++ b/src/PermissionAnalyzer/Directory.Build.props @@ -0,0 +1,12 @@ + + + + + 0.0.0-dev + $(PermissionsReleaseVersion) + net10.0 + latest + enable + enable + + diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/CoverageEvaluator.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/CoverageEvaluator.cs new file mode 100644 index 00000000..51be3ced --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/CoverageEvaluator.cs @@ -0,0 +1,262 @@ +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Coverage; + +/// +/// A missing privilege that is accepted, from XrmMockup:Permissions:Suppress. +/// +/// Table logical name, or empty for a privilege not tied to a table. +/// The privilege, or null for every privilege on the table. +/// Why it is accepted, shown in the output. +/// +/// The name of a privilege not tied to a table, such as prvActOnBehalfOfAnotherUser, when +/// is empty. +/// +public sealed record Suppression(string Table, Privilege? Privilege, string? Reason, string? GlobalPrivilege = null) +{ + public bool Matches(Requirement requirement) => + Table.Length > 0 && string.Equals(Table, requirement.Table, StringComparison.OrdinalIgnoreCase) && (Privilege is null || Privilege == requirement.Privilege); + + public bool Matches(GlobalRequirement requirement) => + string.Equals(GlobalPrivilege, requirement.Privilege, StringComparison.OrdinalIgnoreCase); +} + +/// +/// The roles to check each identity against. +/// +public sealed class CoverageOptions +{ + public CoverageOptions() { } + /// Constructor for SDK consumers using older C# versions. + public CoverageOptions(RoleSet roles, IReadOnlyDictionary users) + { + Roles = roles; Users = users; + } + + /// + /// --role: for the caller and the application user. Replaces when set. + /// + public RoleSet? Roles { get; init; } + + /// + /// --caller-role: for the user that app code acts for by setting CallerId. + /// + public RoleSet? CallerRoles { get; init; } + + /// + /// The application user's roles, by assembly (Contoso.Functions) or by assembly and function + /// (Contoso.Functions/ProcessOrder), which wins. Keys ignore case. + /// + public IReadOnlyDictionary Principals { get; init; } = new Dictionary(); + + /// + /// Roles of specific users, such as the impersonating user of a plugin step, by user id. Keys ignore case. + /// + public IReadOnlyDictionary Users { get; init; } = new Dictionary(); + + public IReadOnlyList Suppress { get; init; } = []; +} + +/// +/// Checks a manifest's requirements against security roles. +/// +public static class CoverageEvaluator +{ + private const string PrincipalsSetting = "XrmMockup:Permissions:Principals"; + private const string UsersSetting = "XrmMockup:Permissions:Users"; + + public static CoverageReport Evaluate(Manifest manifest, CoverageOptions options) => Evaluate(manifest, options, requireKnownIdentities: false); + + /// SDK coverage must establish every non-SYSTEM identity, even for tables no role governs. + public static CoverageReport EvaluateForPermissionCheck(Manifest manifest, CoverageOptions options) => Evaluate(manifest, options, requireKnownIdentities: true); + + private static CoverageReport Evaluate(Manifest manifest, CoverageOptions options, bool requireKnownIdentities) + { + var notGoverned = new HashSet(manifest.NotRoleGoverned ?? [], StringComparer.Ordinal); + var principals = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var principal in options.Principals) principals[principal.Key] = principal.Value; + var users = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var user in options.Users) users[user.Key] = user.Value; + + var usesConfiguredRoles = false; + var usedPrincipals = new HashSet(StringComparer.OrdinalIgnoreCase); + var usedUsers = new HashSet(StringComparer.OrdinalIgnoreCase); + var sections = new List(); + var missing = new SortedDictionary<(string Table, Privilege Privilege, RunsAs RunsAs, string Roles), (RoleSet Roles, SortedSet In)>(MissingOrder); + var missingGlobal = new SortedDictionary<(string Privilege, RunsAs RunsAs, string Roles), (RoleSet Roles, SortedSet In)>(MissingGlobalOrder); + + SectionCoverage Section(IManifestSection manifestSection) + { + var id = manifestSection.Id; + var entryPoint = manifestSection as EntryPoint; + var applicationUser = ApplicationUserRoles(entryPoint, options, principals, usedPrincipals); + var identities = new SortedDictionary(); + var coverage = new Dictionary(); + var globalCoverage = new Dictionary(); + + IdentityRoles IdentityOf(RunsAs identity) + { + if (!identities.TryGetValue(identity, out var roles)) + { + roles = Roles(identity, entryPoint, options, applicationUser, users); + if (identity.Kind == RunsAsKind.User && roles.Roles is not null) usedUsers.Add(identity.UserId!); + if (roles.Roles is { } set && set != options.Roles && set != options.CallerRoles) usesConfiguredRoles = true; + identities.Add(identity, roles); + } + return roles; + } + + foreach (var requirement in manifestSection.Requirements) + { + var identity = requirement.RunsAs with { Assumed = false }; + var roles = IdentityOf(identity); + var result = Check(requirement, roles, notGoverned, options.Suppress, requireKnownIdentities); + coverage.Add(requirement, result); + if (result.Status == CoverageStatus.Missing) AddMissing(missing, (requirement.Table, requirement.Privilege, identity, roles.Roles!.ToString()), roles.Roles, id); + } + + foreach (var requirement in manifestSection.GlobalRequirements) + { + var identity = requirement.RunsAs with { Assumed = false }; + var roles = IdentityOf(identity); + var result = Check(requirement, roles, options.Suppress); + globalCoverage.Add(requirement, result); + if (result.Status == CoverageStatus.Missing) AddMissing(missingGlobal, (requirement.Privilege, identity, roles.Roles!.ToString()), roles.Roles, id); + } + + var needsRole = manifestSection.Unresolved.Where(u => u.RunsAs.Kind != RunsAsKind.System).ToList(); + var section = new SectionCoverage( + coverage, + globalCoverage, + identities.Values.Where(i => i.RunsAs.Kind != RunsAsKind.System).ToList(), + needsRole.Count, + needsRole.Count(u => RequestReasons.NoRuleMessage(u.Reason) is not null), + needsRole.Count(u => RequestReasons.IsCustomApi(u.Reason)), + needsRole.Count(u => RequestReasons.IsWorkflow(u.Reason))); + sections.Add(section); + return section; + } + + var entryPoints = new Dictionary(StringComparer.Ordinal); + var unreached = new Dictionary(StringComparer.Ordinal); + foreach (var section in manifest.Sections) + { + (section is EntryPoint ? entryPoints : unreached)[section.Id] = Section(section); + } + + var all = sections.SelectMany(s => s.All).ToList(); + int Count(CoverageStatus status) => all.Count(c => c.Status == status); + var summary = new CoverageSummary( + Count(CoverageStatus.Granted), + Count(CoverageStatus.NotGoverned), + Count(CoverageStatus.Missing), + Count(CoverageStatus.Suppressed), + Count(CoverageStatus.NotChecked), + Count(CoverageStatus.System), + sections.Sum(s => s.Unresolved), + sections.Sum(s => s.UnresolvedNoRule), + sections.Sum(s => s.UnresolvedCustomApi), + sections.Sum(s => s.UnresolvedWorkflow), + Count(CoverageStatus.Unverifiable), + manifest.Sections.Count(s => s.Truncated)); + + var missingPrivileges = missing.Select(m => new MissingPrivilege(m.Key.Table, m.Key.Privilege, m.Key.RunsAs, m.Value.Roles, m.Value.In.ToList())).ToList(); + var missingGlobalPrivileges = missingGlobal.Select(m => new MissingGlobalPrivilege(m.Key.Privilege, m.Key.RunsAs, m.Value.Roles, m.Value.In.ToList())).ToList(); + // --role replaces the principals, so none of them is expected to match + var unusedPrincipals = options.Roles is null ? Unused(options.Principals.Keys, usedPrincipals) : []; + return new CoverageReport(entryPoints, unreached, summary, missingPrivileges, missingGlobalPrivileges, usesConfiguredRoles, unusedPrincipals, Unused(options.Users.Keys, usedUsers)); + } + + private static List Unused(IEnumerable keys, HashSet used) => + keys.Where(k => !used.Contains(k)).OrderBy(k => k, StringComparer.Ordinal).ToList(); + + private static readonly IComparer<(string Table, Privilege Privilege, RunsAs RunsAs, string Roles)> MissingOrder = + Comparer<(string Table, Privilege Privilege, RunsAs RunsAs, string Roles)>.Create((x, y) => + { + var result = string.CompareOrdinal(x.Table, y.Table); + if (result == 0) result = x.Privilege.CompareTo(y.Privilege); + if (result == 0) result = x.RunsAs.CompareTo(y.RunsAs); + return result != 0 ? result : string.CompareOrdinal(x.Roles, y.Roles); + }); + + private static readonly IComparer<(string Privilege, RunsAs RunsAs, string Roles)> MissingGlobalOrder = + Comparer<(string Privilege, RunsAs RunsAs, string Roles)>.Create((x, y) => + { + var result = string.CompareOrdinal(x.Privilege, y.Privilege); + if (result == 0) result = x.RunsAs.CompareTo(y.RunsAs); + return result != 0 ? result : string.CompareOrdinal(x.Roles, y.Roles); + }); + + /// + /// Records that needs a privilege lack. + /// + private static void AddMissing(SortedDictionary In)> missing, TKey key, RoleSet roles, string id) + { + if (!missing.TryGetValue(key, out var found)) missing.Add(key, found = (roles, new SortedSet(StringComparer.Ordinal))); + found.In.Add(id); + } + + private static RequirementCoverage Check(Requirement requirement, IdentityRoles identity, HashSet notGoverned, IReadOnlyList suppress, bool requireKnownIdentities) + { + if (requirement.RunsAs.Kind == RunsAsKind.System) return new RequirementCoverage(CoverageStatus.System); + if (requireKnownIdentities && identity.Roles is null) return new RequirementCoverage(CoverageStatus.NotChecked); + // No role can grant a table no role governs, whatever roles the identity has + if (notGoverned.Contains(requirement.Table)) return new RequirementCoverage(CoverageStatus.NotGoverned); + if (identity.Roles is not { } roles) return new RequirementCoverage(CoverageStatus.NotChecked); + if (roles.Depth(requirement.Table, requirement.Privilege) is { } depth) return new RequirementCoverage(CoverageStatus.Granted, depth); + + return suppress.FirstOrDefault(s => s.Matches(requirement)) is { } suppression + ? new RequirementCoverage(CoverageStatus.Suppressed, Reason: suppression.Reason) + : new RequirementCoverage(CoverageStatus.Missing); + } + + private static RequirementCoverage Check(GlobalRequirement requirement, IdentityRoles identity, IReadOnlyList suppress) + { + if (requirement.RunsAs.Kind == RunsAsKind.System) return new RequirementCoverage(CoverageStatus.System); + if (identity.Roles is not { } roles) return new RequirementCoverage(CoverageStatus.NotChecked); + if (!roles.KnowsGlobalPrivileges) return new RequirementCoverage(CoverageStatus.Unverifiable); + if (roles.GlobalDepth(requirement.Privilege) is { } depth) return new RequirementCoverage(CoverageStatus.Granted, depth); + + return suppress.FirstOrDefault(s => s.Matches(requirement)) is { } suppression + ? new RequirementCoverage(CoverageStatus.Suppressed, Reason: suppression.Reason) + : new RequirementCoverage(CoverageStatus.Missing); + } + + private static IdentityRoles Roles(RunsAs identity, EntryPoint? entryPoint, CoverageOptions options, RoleSet? applicationUser, Dictionary users) => + identity.Kind switch + { + RunsAsKind.Caller => new IdentityRoles(identity, options.Roles, options.Roles is null ? "not checked: pass --role" : null), + RunsAsKind.ApplicationUser => new IdentityRoles(identity, applicationUser, applicationUser is null + ? entryPoint?.Assembly is { } assembly + ? $"not checked: pass --role, or map {assembly} in {PrincipalsSetting}" + : "not checked: pass --role" + : null), + RunsAsKind.User => users.TryGetValue(identity.UserId ?? "", out var roles) + ? new IdentityRoles(identity, roles) + : new IdentityRoles(identity, null, $"not checked: runs as user {identity.UserId}; map it in {UsersSetting}"), + RunsAsKind.ImpersonatedCaller => new IdentityRoles(identity, options.CallerRoles, options.CallerRoles is null + ? "not checked: acts for the user in CallerId; pass --caller-role with that user's roles" + : null), + _ => new IdentityRoles(identity, null), + }; + + /// + /// --role, else the entry point's function or assembly in . + /// + private static RoleSet? ApplicationUserRoles(EntryPoint? entryPoint, CoverageOptions options, Dictionary principals, HashSet used) + { + if (options.Roles is not null) return options.Roles; + if (entryPoint?.Assembly is not { } assembly) return null; + + if (entryPoint.Kind == EntryPointKind.Function && EntryPointIds.FunctionName(entryPoint.Id) is { } name + && principals.TryGetValue($"{assembly}/{name}", out var function)) + { + used.Add($"{assembly}/{name}"); + return function; + } + if (!principals.TryGetValue(assembly, out var app)) return null; + used.Add(assembly); + return app; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/CoverageModel.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/CoverageModel.cs new file mode 100644 index 00000000..80d377aa --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/CoverageModel.cs @@ -0,0 +1,196 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Coverage; + +/// +/// Whether the roles of a requirement's identity grant it. +/// +public enum CoverageStatus +{ + /// + /// A role grants the privilege, at . Any depth counts. + /// + Granted, + + /// + /// No security role in the metadata mentions the table, so XrmMockup allows every operation on it. + /// + NotGoverned, + + /// + /// None of the roles grants the privilege. + /// + Missing, + + /// + /// Missing, but suppressed in XrmMockup:Permissions:Suppress. + /// + Suppressed, + + /// + /// No roles are known for the identity, so the requirement isn't checked. + /// + NotChecked, + + /// + /// Runs as SYSTEM, which needs no role. + /// + System, + + /// + /// A privilege not tied to a table, which the role metadata doesn't have: it was generated before those privileges + /// were downloaded. + /// + Unverifiable, +} + +/// Whether the requirement is covered. +/// The depth the roles grant, when . +/// Why it is suppressed, when . +public sealed record RequirementCoverage(CoverageStatus Status, PrivilegeDepth? Depth = null, string? Reason = null); + +/// +/// The roles one identity of an entry point is checked against, or why it isn't checked. +/// +/// The identity, without . +/// The roles, or null when none are known. +/// Why the identity isn't checked, when is null. +public sealed record IdentityRoles(RunsAs RunsAs, RoleSet? Roles, string? Note = null); + +/// +/// Role coverage for the requirements of one entry point or unreached method. +/// +public sealed class SectionCoverage( + IReadOnlyDictionary requirements, + IReadOnlyDictionary globalRequirements, + IReadOnlyList identities, + int unresolved, + int unresolvedNoRule, + int unresolvedCustomApi, + int unresolvedWorkflow) +{ + /// + /// The identities of the section's requirements, with their roles, sorted by identity. + /// + public IReadOnlyList Identities { get; } = identities; + + /// + /// Unresolved operations that would need a role, so not those running as SYSTEM. + /// + public int Unresolved { get; } = unresolved; + + /// + /// The part of that are requests without a rule. + /// + public int UnresolvedNoRule { get; } = unresolvedNoRule; + + /// + /// The part of that are custom API calls, whose code or execute privilege isn't known. + /// + public int UnresolvedCustomApi { get; } = unresolvedCustomApi; + + /// + /// The part of that are workflows from the metadata, whose steps aren't analyzed. + /// + public int UnresolvedWorkflow { get; } = unresolvedWorkflow; + + public RequirementCoverage For(Requirement requirement) => requirements[requirement]; + + public RequirementCoverage For(GlobalRequirement requirement) => globalRequirements[requirement]; + + internal IEnumerable All => requirements.Values.Concat(globalRequirements.Values); +} + +/// +/// Counts over every requirement of a , including privileges not tied to a table. , +/// and are the parts of that are requests +/// without a rule, custom API calls and fired workflows. counts the entry points and unreached methods +/// whose analysis stopped early. +/// +public sealed record CoverageSummary( + int Granted, + int NotGoverned, + int Missing, + int Suppressed, + int NotChecked, + int System, + int Unresolved, + int UnresolvedNoRule, + int UnresolvedCustomApi, + int UnresolvedWorkflow, + int Unverifiable, + int Truncated = 0) +{ + /// + /// Something the result doesn't cover: unresolved operations, identities without roles, privileges that + /// can't be checked or an analysis that stopped early. + /// + public bool Incomplete => Unresolved + NotChecked + Unverifiable + Truncated > 0; + + /// + /// Nothing is missing. With , everything was also checked: no unresolved operations, + /// unchecked identities, unverifiable privileges or analyses that stopped early. + /// + public bool Passed(bool strict) => Missing == 0 && (!strict || !Incomplete); +} + +/// +/// A privilege the roles of an identity don't grant, with every entry point and unreached method that needs it. +/// +/// The identity, without . +/// The roles that don't grant it. +/// Ids of the entry points and unreached methods that need it, sorted. +public sealed record MissingPrivilege(string Table, Privilege Privilege, RunsAs RunsAs, RoleSet Roles, IReadOnlyList In); + +/// +/// A privilege not tied to a table that the roles of an identity don't grant, with every entry point and unreached +/// method that needs it. +/// +/// The privilege name, such as prvActOnBehalfOfAnotherUser. +/// The identity, without . +/// The roles that don't grant it. +/// Ids of the entry points and unreached methods that need it, sorted. +public sealed record MissingGlobalPrivilege(string Privilege, RunsAs RunsAs, RoleSet Roles, IReadOnlyList In); + +/// +/// Role coverage for a whole manifest. +/// +public sealed class CoverageReport( + IReadOnlyDictionary entryPoints, + IReadOnlyDictionary unreached, + CoverageSummary summary, + IReadOnlyList missing, + IReadOnlyList missingGlobal, + bool usesConfiguredRoles, + IReadOnlyList? unusedPrincipals = null, + IReadOnlyList? unusedUsers = null) +{ + public CoverageSummary Summary { get; } = summary; + + /// + /// The missing requirements merged across entry points, sorted by table, privilege, identity and roles. + /// + public IReadOnlyList Missing { get; } = missing; + + /// + /// The missing privileges not tied to a table merged across entry points, sorted by privilege, identity and roles. + /// + public IReadOnlyList MissingGlobal { get; } = missingGlobal; + + /// + /// Some requirement was checked against roles from Principals or Users. + /// + public bool UsesConfiguredRoles { get; } = usesConfiguredRoles; + + /// + /// The Principals keys no analyzed entry point used, sorted; empty when --role replaces them. + /// + public IReadOnlyList UnusedPrincipals { get; } = unusedPrincipals ?? []; + + /// + /// The Users ids no analyzed operation runs as, sorted. + /// + public IReadOnlyList UnusedUsers { get; } = unusedUsers ?? []; + + public SectionCoverage For(IManifestSection section) => section is EntryPoint ? entryPoints[section.Id] : unreached[section.Id]; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/RoleCatalog.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/RoleCatalog.cs new file mode 100644 index 00000000..d45fb69b --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/RoleCatalog.cs @@ -0,0 +1,62 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Coverage; + +/// +/// The security roles in the metadata, found by name. +/// +public sealed class RoleCatalog(IReadOnlyList roles) +{ + public IReadOnlyList Roles { get; } = roles; + + /// + /// The roles with this name: an exact match, else a match ignoring case. Every business unit can have a copy + /// of a role, so there can be several. Empty when no role has the name. + /// + public IReadOnlyList Find(string name) + { + var exact = Roles.Where(r => r.Name == name).ToList(); + return exact.Count > 0 ? exact : Roles.Where(r => string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)).ToList(); + } + + /// + /// The role names closest to , for an error message: names containing it first, then by + /// edit distance, ignoring case. Names that are too different aren't suggested. + /// + public IReadOnlyList Suggest(string name, int count = 3) + { + var wanted = name.ToLowerInvariant(); + var maxDistance = Math.Max(2, wanted.Length / 3); + return Roles + .Select(r => r.Name) + .Distinct(StringComparer.Ordinal) + .Select(n => (Name: n, Lower: n.ToLowerInvariant())) + .Select(n => (n.Name, Contains: wanted.Length > 0 && (n.Lower.Contains(wanted) || wanted.Contains(n.Lower)), Distance: Distance(wanted, n.Lower))) + .Where(n => n.Contains || n.Distance <= maxDistance) + .OrderBy(n => n.Contains ? 0 : 1) + .ThenBy(n => n.Distance) + .ThenBy(n => n.Name, StringComparer.Ordinal) + .Take(count) + .Select(n => n.Name) + .ToList(); + } + + private static int Distance(string a, string b) + { + var previous = new int[b.Length + 1]; + var current = new int[b.Length + 1]; + for (var j = 0; j <= b.Length; j++) previous[j] = j; + + for (var i = 1; i <= a.Length; i++) + { + current[0] = i; + for (var j = 1; j <= b.Length; j++) + { + var substitution = previous[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1); + current[j] = Math.Min(substitution, Math.Min(previous[j], current[j - 1]) + 1); + } + (previous, current) = (current, previous); + } + return previous[b.Length]; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/RoleSet.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/RoleSet.cs new file mode 100644 index 00000000..d6aa25a7 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Coverage/RoleSet.cs @@ -0,0 +1,87 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Coverage; + +/// +/// The roles one identity is checked against, combined the way XrmMockup combines a principal's roles: the union of +/// their privileges, with the highest depth winning. +/// +public sealed class RoleSet +{ + private readonly Dictionary> _privileges; + private readonly Dictionary? _globalPrivileges; + + private RoleSet( + IReadOnlyList names, + string origin, + Dictionary> privileges, + Dictionary? globalPrivileges) + { + Names = names; + Origin = origin; + _privileges = privileges; + _globalPrivileges = globalPrivileges; + } + + /// + /// Role names, sorted. + /// + public IReadOnlyList Names { get; } + + /// + /// Where the roles were given, such as --role or Principals: Contoso.Functions. + /// + public string Origin { get; } + + public static RoleSet Combine(IEnumerable roles, string origin) + { + var names = new SortedSet(StringComparer.Ordinal); + var privileges = new Dictionary>(StringComparer.Ordinal); + var globalPrivileges = new Dictionary(StringComparer.OrdinalIgnoreCase); + var globalKnown = true; + foreach (var role in roles) + { + names.Add(role.Name); + if (role.GlobalPrivileges is null) globalKnown = false; + foreach (var global in role.GlobalPrivileges ?? new Dictionary()) + { + if (!globalPrivileges.TryGetValue(global.Key, out var depth) || global.Value > depth) globalPrivileges[global.Key] = global.Value; + } + + foreach (var table in role.Privileges) + { + if (!privileges.TryGetValue(table.Key, out var granted)) + { + granted = new Dictionary(); + privileges.Add(table.Key, granted); + } + + foreach (var privilege in table.Value) + { + if (!granted.TryGetValue(privilege.Key, out var depth) || privilege.Value > depth) granted[privilege.Key] = privilege.Value; + } + } + } + return new RoleSet(names.ToList(), origin, privileges, globalKnown ? globalPrivileges : null); + } + + /// + /// Every role has its privileges not tied to a table in the metadata, so can be trusted. + /// + public bool KnowsGlobalPrivileges => _globalPrivileges is not null; + + /// + /// The depth the roles grant the privilege at, or null when none of them grants it. + /// + public PrivilegeDepth? Depth(string table, Privilege privilege) => + _privileges.TryGetValue(table, out var granted) && granted.TryGetValue(privilege, out var depth) ? depth : null; + + /// + /// The depth the roles grant a privilege not tied to a table at, by name, or null when none of them grants + /// it or is false. + /// + public PrivilegeDepth? GlobalDepth(string privilege) => + _globalPrivileges is not null && _globalPrivileges.TryGetValue(privilege, out var depth) ? depth : null; + + public override string ToString() => $"{string.Join(", ", Names)} ({Origin})"; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Assumption.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Assumption.cs new file mode 100644 index 00000000..7de16729 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Assumption.cs @@ -0,0 +1,14 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// An operation whose identity couldn't be determined, so it is counted as running as the caller. +/// +public sealed class Assumption(string reason, RequirementSource source) +{ + /// + /// Why the identity is unknown, such as service comes from parameter 'service'. + /// + public string Reason { get; } = reason; + + public RequirementSource Source { get; } = source; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPoint.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPoint.cs new file mode 100644 index 00000000..e4097968 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPoint.cs @@ -0,0 +1,71 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A place where code starts running, with every privilege needed by the operations it reaches. +/// +public sealed class EntryPoint( + string id, + EntryPointKind kind, + string type, + string? assembly, + Trigger? trigger, + string? impersonatingUserId, + SourceLocation? declaration, + IReadOnlyList requirements, + IReadOnlyList unresolved, + IReadOnlyList assumptions, + IReadOnlyList? triggers = null, + IReadOnlyList? globalRequirements = null, + bool truncated = false) : IManifestSection +{ + /// + /// A stable id such as plugin:Contoso.AccountPostPlugin:Update:account:PostOperation. + /// + public string Id { get; } = id; + + public EntryPointKind Kind { get; } = kind; + + /// + /// The full name of the plugin, activity or class that declares the entry point. + /// + public string Type { get; } = type; + + /// + /// The assembly that declares the entry point, such as the function app. + /// + public string? Assembly { get; } = assembly; + + public Trigger? Trigger { get; } = trigger; + + /// + /// The user a plugin step runs as instead of the caller. + /// + public string? ImpersonatingUserId { get; } = impersonatingUserId; + + /// + /// Where the handler is declared. + /// + public SourceLocation? Declaration { get; } = declaration; + + /// + /// Requirements sorted by table, privilege, identity and basis. + /// + public IReadOnlyList Requirements { get; } = requirements; + + /// + /// Privileges not tied to a table, sorted by name, identity and basis. + /// + public IReadOnlyList GlobalRequirements { get; } = globalRequirements ?? []; + + public IReadOnlyList Unresolved { get; } = unresolved; + + public IReadOnlyList Assumptions { get; } = assumptions; + + /// + /// The ids of the plugin steps and custom APIs the entry point's operations fire, directly or through other + /// steps, sorted. Their requirements are part of . + /// + public IReadOnlyList Triggers { get; } = triggers ?? []; + + public bool Truncated { get; } = truncated; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPointIds.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPointIds.cs new file mode 100644 index 00000000..71dec862 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPointIds.cs @@ -0,0 +1,69 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// Builds the of each kind of entry point, and reads the name back out of one. +/// +internal static class EntryPointIds +{ + private const string PluginPrefix = "plugin:"; + private const string CustomApiPrefix = "custom-api:"; + private const string ActivityPrefix = "activity:"; + private const string FunctionPrefix = "function:"; + private const string MethodPrefix = "method:"; + private const string OperationPrefix = "operation:"; + private const string WorkflowPrefix = "workflow:"; + + /// + /// A plugin step, on any table when is null. + /// + public static string PluginStep(string type, string message, string? table, string stage) => + $"{PluginPrefix}{type}:{message}:{table ?? "any"}:{stage}"; + + /// + /// A plugin without known steps. + /// + public static string Plugin(string type) => PluginPrefix + type; + + public static string CustomApi(string name) => CustomApiPrefix + name; + + public static string Activity(string type) => ActivityPrefix + type; + + /// + /// A function, by its app's assembly, since two apps can have functions of the same name: such as + /// function:Contoso.Functions/ProcessOrder, the form Principals names it by. + /// + public static string Function(string? assembly, string name) => FunctionPrefix + (assembly is null ? "" : assembly + "/") + name; + + public static string Method(string methodId) => MethodPrefix + methodId; + + /// + /// A workflow from the metadata, run by on its table. Not an entry point: operations + /// only fire it. + /// + public static string Workflow(string name, string message, string table) => $"{WorkflowPrefix}{name}:{message}:{table}"; + + /// + /// A user operation, with the columns it sets when they are known. + /// + public static string Operation(string display, IReadOnlyList? columns) => + OperationPrefix + display + (columns is null ? "" : $"({string.Join(",", columns)})"); + + /// + /// The name of the function is the id of, without its assembly; null for any other id. + /// + public static string? FunctionName(string id) => After(id, FunctionPrefix) is { } qualified ? qualified.Substring(qualified.LastIndexOf('/') + 1) : null; + + /// + /// The assembly and name of the function is the id of, such as + /// Contoso.Functions/ProcessOrder; null for any other id. + /// + public static string? QualifiedFunctionName(string id) => After(id, FunctionPrefix); + + /// + /// The method id of the method entry is the id of; null for any other id. + /// + public static string? MethodId(string id) => After(id, MethodPrefix); + + private static string? After(string id, string prefix) => + id.StartsWith(prefix, StringComparison.Ordinal) ? id.Substring(prefix.Length) : null; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPointKind.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPointKind.cs new file mode 100644 index 00000000..8edc0468 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/EntryPointKind.cs @@ -0,0 +1,40 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// Where code starts running. +/// +public enum EntryPointKind +{ + /// + /// A plugin step registered in code (XrmPluginCore, DAXIF) or in the plugin metadata. + /// + PluginStep, + + /// + /// An IPlugin without known steps: its Execute(IServiceProvider). + /// + Plugin, + + CustomApi, + + /// + /// A workflow CodeActivity. + /// + CodeActivity, + + /// + /// An Azure Function, isolated ([Function]) or in-process ([FunctionName]). + /// + Function, + + /// + /// A method given with --entry or XrmMockup:Permissions:EntryPoints. + /// + Method, + + /// + /// A user operation on a table given with --operation, such as an update in an app, with the plugin + /// steps it fires. + /// + Operation, +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/GlobalRequirement.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/GlobalRequirement.cs new file mode 100644 index 00000000..2e3fc368 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/GlobalRequirement.cs @@ -0,0 +1,43 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A privilege not tied to a table that the code needs under one identity, such as the execute privilege of a custom +/// API or prvBulkDelete for a BulkDelete request, with every call site that needs it. +/// +public sealed class GlobalRequirement(string privilege, RunsAs runsAs, RequirementBasis basis, IReadOnlyList sources) +{ + /// + /// What setting CallerId needs on the identity that sets it. + /// + public const string ActOnBehalfOfAnotherUser = "prvActOnBehalfOfAnotherUser"; + + /// + /// What creating a record with overriddencreatedon set needs. + /// + public const string OverrideCreatedOnCreatedBy = "prvOverrideCreatedOnCreatedBy"; + + /// + /// What the BypassCustomPluginExecution parameter, or BypassPluginExecution on a ServiceClient, + /// needs. + /// + public const string BypassCustomPlugins = "prvBypassCustomPlugins"; + + /// + /// What the BypassBusinessLogicExecution and BypassBusinessLogicExecutionStepIds parameters need. + /// + public const string BypassCustomBusinessLogic = "prvBypassCustomBusinessLogic"; + + /// + /// The privilege name, such as prvActOnBehalfOfAnotherUser. + /// + public string Privilege { get; } = privilege; + + public RunsAs RunsAs { get; } = runsAs; + + public RequirementBasis Basis { get; } = basis; + + /// + /// Call sites that need this privilege, sorted by file and position. + /// + public IReadOnlyList Sources { get; } = sources; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/IManifestSection.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/IManifestSection.cs new file mode 100644 index 00000000..2beca477 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/IManifestSection.cs @@ -0,0 +1,31 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A part of the manifest with its own requirements: an or an unreached +/// . +/// +public interface IManifestSection +{ + string Id { get; } + + SourceLocation? Declaration { get; } + + /// + /// Requirements sorted by table, privilege, identity and basis. + /// + IReadOnlyList Requirements { get; } + + /// + /// Privileges not tied to a table, sorted by name, identity and basis. + /// + IReadOnlyList GlobalRequirements { get; } + + IReadOnlyList Unresolved { get; } + + IReadOnlyList Assumptions { get; } + + /// + /// The analysis stopped at its limit of calls, so requirements may be missing. + /// + bool Truncated { get; } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/LookupColumn.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/LookupColumn.cs new file mode 100644 index 00000000..c4561d5f --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/LookupColumn.cs @@ -0,0 +1,10 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A lookup column from the XrmMockup metadata, with the tables it can refer to. A polymorphic lookup, such as a +/// customer or regarding column, has several. +/// +/// Logical name of the table the column is on. +/// Logical name of the column. +/// Logical names of the tables the column can refer to. +public sealed record LookupColumn(string Table, string Column, IReadOnlyList Targets); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Manifest.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Manifest.cs new file mode 100644 index 00000000..a1152883 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Manifest.cs @@ -0,0 +1,48 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// The result of an analysis: every entry point with what it needs, sorted by id, and the operations no entry +/// point reaches. +/// +public sealed class Manifest( + IReadOnlyList entryPoints, + IReadOnlyList unreached, + IReadOnlyList? notRoleGoverned = null) +{ + public IReadOnlyList EntryPoints { get; } = entryPoints; + + /// + /// Methods with data operations that no entry point reaches, sorted by id. Empty when the analysis was + /// scoped to some entry points. + /// + public IReadOnlyList Unreached { get; } = unreached; + + /// + /// Required tables that no security role mentions. XrmMockup lets every operation on these through, + /// so they need no privilege. null when no roles were loaded. + /// + public IReadOnlyList? NotRoleGoverned { get; } = notRoleGoverned; + + /// + /// The entry points, then the unreached methods. + /// + public IReadOnlyList Sections { get; } = [.. entryPoints, .. unreached]; + + /// + /// Every requirement, of entry points and unreached methods. + /// + public IEnumerable AllRequirements => + Sections.SelectMany(s => s.Requirements); + + /// + /// Every requirement of a privilege not tied to a table, of entry points and unreached methods. + /// + public IEnumerable AllGlobalRequirements => + Sections.SelectMany(s => s.GlobalRequirements); + + /// + /// Every table that appears in a requirement, sorted. + /// + public IReadOnlyList Tables => + AllRequirements.Select(r => r.Table).Distinct().OrderBy(t => t, StringComparer.Ordinal).ToList(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Messages.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Messages.cs new file mode 100644 index 00000000..7e0a4398 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Messages.cs @@ -0,0 +1,18 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// The Dataverse messages the analysis handles itself. A misspelled constant fails to compile, where a misspelled +/// string never matches. +/// +internal static class Messages +{ + public const string Create = "Create"; + public const string Update = "Update"; + public const string Upsert = "Upsert"; + public const string Delete = "Delete"; + public const string Retrieve = "Retrieve"; + public const string RetrieveMultiple = "RetrieveMultiple"; + public const string Associate = "Associate"; + public const string Disassociate = "Disassociate"; + public const string Execute = "Execute"; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/MethodManifest.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/MethodManifest.cs new file mode 100644 index 00000000..82013a26 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/MethodManifest.cs @@ -0,0 +1,43 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// The privileges needed by the data operations written directly in one method that no entry point reaches. +/// +public sealed class MethodManifest( + string id, + SourceLocation? declaration, + IReadOnlyList requirements, + IReadOnlyList unresolved, + IReadOnlyList assumptions, + IReadOnlyList? globalRequirements = null, + bool truncated = false) : IManifestSection +{ + /// + /// Fully qualified method signature, e.g. Contoso.Plugins.AccountPostPlugin.Execute(LocalPluginContext). + /// + public string Id { get; } = id; + + public SourceLocation? Declaration { get; } = declaration; + + /// + /// Requirements sorted by table, privilege, identity and basis. + /// + public IReadOnlyList Requirements { get; } = requirements; + + /// + /// Privileges not tied to a table, sorted by name, identity and basis. + /// + public IReadOnlyList GlobalRequirements { get; } = globalRequirements ?? []; + + /// + /// Operations whose table could not be resolved, sorted by source location. + /// + public IReadOnlyList Unresolved { get; } = unresolved; + + /// + /// Operations counted as running as the caller because their identity is unknown, sorted by source location. + /// + public IReadOnlyList Assumptions { get; } = assumptions; + + public bool Truncated { get; } = truncated; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PluginStepRegistration.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PluginStepRegistration.cs new file mode 100644 index 00000000..6cdc843d --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PluginStepRegistration.cs @@ -0,0 +1,23 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A plugin step from the XrmMockup metadata, matched to a plugin class by and +/// , the way XrmMockup matches it. +/// +/// Full name of the plugin class. +/// Name of the assembly with the plugin class, when known. +/// SDK message, such as Update. +/// Primary table logical name; null for any table. +/// Pipeline stage: 10, 20, 30 or 40. +/// The user the step runs as, when it doesn't run as the caller. +/// The columns an Update step is filtered on; null for none. +/// Whether the step runs asynchronously. +public sealed record PluginStepRegistration( + string TypeName, + string? AssemblyName, + string Message, + string? Table, + int Stage, + string? ImpersonatingUserId, + IReadOnlyList? FilteredAttributes = null, + bool Asynchronous = false); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Privilege.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Privilege.cs new file mode 100644 index 00000000..135f365d --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Privilege.cs @@ -0,0 +1,16 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A table privilege as granted by a Dataverse security role. +/// +public enum Privilege +{ + Create, + Read, + Write, + Delete, + Append, + AppendTo, + Assign, + Share +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PrivilegeDefinition.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PrivilegeDefinition.cs new file mode 100644 index 00000000..b3b2b0ef --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PrivilegeDefinition.cs @@ -0,0 +1,20 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A privilege in the privilege catalog of the metadata, for looking up a privilege by name. +/// +/// The privilege name, such as prvReadAccount. +/// +/// The table privilege it grants on , or null when its access right isn't one. +/// +/// +/// Logical names of the tables it applies to. Empty for a privilege not tied to a table. +/// +public sealed record PrivilegeDefinition(string Name, Privilege? Privilege, IReadOnlyList Tables); + +/// +/// A custom API in the privilege catalog of the metadata. +/// +/// The message, such as ctx_Recalculate. +/// The privilege calling it needs, or null when it needs none. +public sealed record CustomApiDefinition(string UniqueName, string? ExecutePrivilegeName); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PrivilegeDepth.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PrivilegeDepth.cs new file mode 100644 index 00000000..bc7f21fc --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/PrivilegeDepth.cs @@ -0,0 +1,12 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// How far a granted privilege reaches, as shown in the security role editor. +/// +public enum PrivilegeDepth +{ + User, + BusinessUnit, + ParentChildBusinessUnit, + Organization +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequestRule.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequestRule.cs new file mode 100644 index 00000000..1df6c95b --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequestRule.cs @@ -0,0 +1,88 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// The privileges executing a request needs, such as Assign and Write on the Target of AssignRequest, +/// or prvBulkDelete for BulkDeleteRequest. A rule with no checks, global privileges, as, or requests marks a +/// request that needs no privilege. +/// +/// +/// The message, such as Assign. The request type name (AssignRequest) is accepted too. +/// +public sealed record RequestRule(string Message) +{ + public IReadOnlyList Checks { get; init; } = []; + + /// + /// Privileges the request needs by name, such as prvBulkDelete. Each is looked up in the privilege + /// catalog, where it is a privilege not tied to a table or one on the tables it applies to. + /// + public IReadOnlyList GlobalPrivileges { get; init; } = []; + + /// + /// What the analysis assumes about the request, such as that an email is sent as its sender, when what it needs + /// depends on data only known at runtime. + /// + public string? Assumption { get; init; } + + /// + /// Messages whose checks this request makes as well, such as Create and Update for Upsert. + /// + public IReadOnlyList As { get; init; } = []; + + /// + /// The member that holds several targets, such as Targets of CreateMultipleRequest. The checks of + /// the messages on Target apply to it instead. + /// + public string? Targets { get; init; } + + /// + /// The member that holds requests run as part of this one, such as Requests of ExecuteMultipleRequest. + /// + public string? Requests { get; init; } + + /// + /// Whether XrmMockup's handler for the message makes the checks. Dataverse makes them either way. + /// + public bool Enforced { get; init; } = true; + + /// + /// The table the request's plugin steps fire on, when it isn't that of its first check on a member: such as + /// opportunity for WinOpportunityRequest, whose first check is on its OpportunityClose. + /// + public string? FiresOn { get; init; } + + /// + /// The message the request's plugin steps are registered on, when it isn't the request's own: such as + /// Win for WinOpportunityRequest. + /// + public string? StepMessage { get; init; } +} + +/// +/// Privileges on the tables a request member refers to, or on a fixed table. +/// +/// The privileges needed on the table. +public sealed record RuleCheck(IReadOnlyList Privileges) +{ + /// + /// The request member that refers to the table, such as Target. + /// + public string? Member { get; init; } + + /// + /// A fixed table, such as email for SendEmailRequest, when no is set. + /// + public string? Table { get; init; } + + /// + /// A member that holds access rights, such as PrincipalAccess.AccessMask; each right it grants is needed + /// as well. + /// + public string? AccessMask { get; init; } + + /// + /// A boolean member that must be set for the check to apply, such as CreateAccount of + /// QualifyLeadRequest. + /// + public string? When { get; init; } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Requirement.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Requirement.cs new file mode 100644 index 00000000..0dd55645 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Requirement.cs @@ -0,0 +1,23 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A privilege on a table that the code needs under one identity, with every call site that needs it. +/// +public sealed class Requirement(string table, Privilege privilege, RunsAs runsAs, RequirementBasis basis, IReadOnlyList sources) +{ + /// + /// Table logical name. + /// + public string Table { get; } = table; + + public Privilege Privilege { get; } = privilege; + + public RunsAs RunsAs { get; } = runsAs; + + public RequirementBasis Basis { get; } = basis; + + /// + /// Call sites that need this privilege, sorted by file and position. + /// + public IReadOnlyList Sources { get; } = sources; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementBases.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementBases.cs new file mode 100644 index 00000000..dc95a753 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementBases.cs @@ -0,0 +1,9 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +internal static class RequirementBases +{ + /// + /// The basis of a requirement reached through both: the later of the two in . + /// + public static RequirementBasis Max(RequirementBasis a, RequirementBasis b) => a > b ? a : b; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementBasis.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementBasis.cs new file mode 100644 index 00000000..96bfae95 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementBasis.cs @@ -0,0 +1,33 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// Why a requirement is part of the requirement set. A basis is a fact about the code, not a likelihood. +/// +public enum RequirementBasis +{ + /// + /// Table and privilege resolved from the call itself: types, constants or local data flow. + /// + Direct, + + /// + /// The execute privilege of a custom API, which calling it needs. + /// + ExecutePrivilege, + + /// + /// Reached through an interface or abstract call that no dependency injection registration resolves, so + /// every implementation in the solution is included. + /// + AllImplementations, + + /// + /// The record a lookup refers to can't be determined, so every table the lookup column can refer to is included. + /// + AllLookupTargets, + + /// + /// From an Update plugin step filtered on columns, fired by an update whose columns can't all be determined. + /// + FilterUnknown, +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementSource.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementSource.cs new file mode 100644 index 00000000..757e777f --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RequirementSource.cs @@ -0,0 +1,19 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A call site that needs a privilege, with the call path from the entry point to the method that makes it. +/// +public sealed record RequirementSource(SourceLocation Location, IReadOnlyList Path) : IComparable +{ + public int CompareTo(RequirementSource? other) + { + if (other is null) return 1; + var result = Location.CompareTo(other.Location); + return result != 0 ? result : string.CompareOrdinal(string.Join("\n", Path), string.Join("\n", other.Path)); + } + + public bool Equals(RequirementSource? other) => + other is not null && Location.Equals(other.Location) && Path.SequenceEqual(other.Path, StringComparer.Ordinal); + + public override int GetHashCode() => Location.GetHashCode(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RoleDefinition.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RoleDefinition.cs new file mode 100644 index 00000000..a24f953c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RoleDefinition.cs @@ -0,0 +1,24 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A security role from the XrmMockup metadata: the privileges it grants per table, with their depth, and the +/// privileges not tied to a table that it grants. +/// +public sealed class RoleDefinition( + string name, + IReadOnlyDictionary> privileges, + IReadOnlyDictionary? globalPrivileges = null) +{ + public string Name { get; } = name; + + /// + /// Granted privileges keyed by table logical name. + /// + public IReadOnlyDictionary> Privileges { get; } = privileges; + + /// + /// Granted privileges not tied to a table, such as prvActOnBehalfOfAnotherUser, keyed by name. + /// null when the role was downloaded by a metadata generator that didn't download them. + /// + public IReadOnlyDictionary? GlobalPrivileges { get; } = globalPrivileges; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RunsAs.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RunsAs.cs new file mode 100644 index 00000000..27603701 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/RunsAs.cs @@ -0,0 +1,62 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// Who an operation runs as. This decides which security roles have to grant its privileges. +/// +public enum RunsAsKind +{ + /// + /// The user that triggered the plugin step, custom API or workflow. + /// + Caller, + + /// + /// A specific user, by : a constant id passed to CreateOrganizationService, + /// or the impersonating user of a plugin step. + /// + User, + + /// + /// The application user of app code, such as an Azure Function using ServiceClient. + /// + ApplicationUser, + + /// + /// App code acting for a user by setting CallerId. The user needs the privilege; the application user + /// needs to be allowed to act on behalf of other users. + /// + ImpersonatedCaller, + + /// + /// SYSTEM (CreateOrganizationService(null)). No role is needed; listed for information. + /// + System, +} + +/// +/// The identity an operation runs as. is set when the source of the service couldn't be +/// determined, and the analysis fell back to the caller. +/// +public sealed record RunsAs(RunsAsKind Kind, string? UserId = null, bool Assumed = false) : IComparable +{ + public static RunsAs Caller { get; } = new(RunsAsKind.Caller); + public static RunsAs System { get; } = new(RunsAsKind.System); + public static RunsAs ApplicationUser { get; } = new(RunsAsKind.ApplicationUser); + public static RunsAs ImpersonatedCaller { get; } = new(RunsAsKind.ImpersonatedCaller); + + public static RunsAs User(string userId) => new(RunsAsKind.User, userId.ToLowerInvariant()); + + public int CompareTo(RunsAs? other) + { + if (other is null) return 1; + var result = Kind.CompareTo(other.Kind); + if (result == 0) result = string.CompareOrdinal(UserId, other.UserId); + return result != 0 ? result : Assumed.CompareTo(other.Assumed); + } + + public override string ToString() + { + var text = UserId is null ? Kind.ToString() : $"{Kind} {UserId}"; + return Assumed ? text + " (assumed)" : text; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/SourceLocation.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/SourceLocation.cs new file mode 100644 index 00000000..5b3e2ca2 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/SourceLocation.cs @@ -0,0 +1,24 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A position in the analyzed source code. is relative to the analysis root +/// and always uses forward slashes, so output is identical across machines. +/// +public sealed record SourceLocation(string File, int Line, int Column) : IComparable +{ + public int CompareTo(SourceLocation? other) + { + if (other is null) return 1; + + var result = string.CompareOrdinal(File, other.File); + if (result != 0) return result; + + result = Line.CompareTo(other.Line); + return result != 0 ? result : Column.CompareTo(other.Column); + } + + /// + /// File:Line, or just for a location outside the code, such as --operation. + /// + public override string ToString() => Line == 0 ? File : $"{File}:{Line}"; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Trigger.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Trigger.cs new file mode 100644 index 00000000..f83c3109 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/Trigger.cs @@ -0,0 +1,21 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// What starts an entry point: the message, table and stage of a plugin step, or the trigger binding of an Azure +/// Function, such as HttpTrigger. are the columns an Update step is +/// filtered on, sorted; null when it runs on every update. is set for a step that +/// runs asynchronously. +/// +public sealed record Trigger( + string? Message = null, + string? Table = null, + string? Stage = null, + string? Binding = null, + IReadOnlyList? FilteredAttributes = null, + bool Asynchronous = false) +{ + /// + /// As in XrmMockup, a step's filtered attributes apply to Update only. Messages ignore case. + /// + internal static bool Filters(string? message) => string.Equals(message, Messages.Update, StringComparison.OrdinalIgnoreCase); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/UnresolvedOperation.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/UnresolvedOperation.cs new file mode 100644 index 00000000..be51bbaa --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/UnresolvedOperation.cs @@ -0,0 +1,27 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A data operation whose table could not be determined statically. It is reported instead of dropped, +/// because a privilege can't be named without a table. +/// +public sealed class UnresolvedOperation(string operation, IReadOnlyList privileges, string reason, RunsAs runsAs, RequirementSource source) +{ + /// + /// The service operation, e.g. Create or RetrieveMultiple. + /// + public string Operation { get; } = operation; + + /// + /// The privileges the operation needs on the unresolved table. + /// + public IReadOnlyList Privileges { get; } = privileges; + + /// + /// Why the table could not be resolved. + /// + public string Reason { get; } = reason; + + public RunsAs RunsAs { get; } = runsAs; + + public RequirementSource Source { get; } = source; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/WorkflowRegistration.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/WorkflowRegistration.cs new file mode 100644 index 00000000..87a5ab5c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Model/WorkflowRegistration.cs @@ -0,0 +1,21 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Model; + +/// +/// A workflow from the XrmMockup metadata that runs automatically on a table. Its steps aren't analyzed, so the +/// operations that fire it report it as unresolved. +/// +/// Name of the workflow. +/// Primary table logical name. +/// Whether it runs when a row is created. +/// Whether it runs when a row is deleted. +/// The columns whose update runs it; null when an update doesn't. +/// Whether it runs in the request (real-time) rather than in the background. +/// The user it runs as, its owner, when it doesn't run as the calling user. +public sealed record WorkflowRegistration( + string Name, + string Table, + bool OnCreate, + bool OnDelete, + IReadOnlyList? UpdateColumns, + bool RealTime, + string? RunsAsUserId); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionAnalysis.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionAnalysis.cs new file mode 100644 index 00000000..20ec3cfb --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionAnalysis.cs @@ -0,0 +1,72 @@ +using System.Reflection; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer; + +/// Reusable static source analysis. Checks do not execute code or prove record-level access. +public abstract class PermissionAnalysis +{ + /// + /// Loads source once. Enable XrmMockupEnablePermissionAnalysis in a .NET 10 test project. + /// The shared SDK libraries ship inside Core; no tool installation or extra NuGet package is needed. + /// + public static Task LoadAsync(string projectOrSolutionPath, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(projectOrSolutionPath)) throw new ArgumentException("A project or solution path is required.", nameof(projectOrSolutionPath)); + var loader = Type.GetType("DG.Tools.XrmMockup.PermissionAnalysisBootstrap, XrmMockup365", throwOnError: false) + ?? Type.GetType("XrmMockup.PermissionAnalyzer.Workspace.PermissionAnalysisLoader, XrmMockup.PermissionAnalyzer.Workspace", throwOnError: false) + ?? throw new InvalidOperationException("Enable XrmMockupEnablePermissionAnalysis in a .NET 10 Core test project to load permission analysis. Workspace loading is not supported on .NET Framework."); + try + { + return (Task)loader.GetMethod("LoadAsync", new[] { typeof(string), typeof(CancellationToken) })! + .Invoke(null, new object[] { projectOrSolutionPath, cancellationToken })!; + } + catch (TargetInvocationException ex) when (ex.InnerException is not null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + throw; + } + } + + /// Builds a fresh manifest against the current mockup metadata, reusing the loaded source graph. + public abstract Manifest Analyze(PermissionScope scope, PermissionMetadata metadata); +} + +/// Metadata supplied by the mockup at check time; no role coverage is cached. +public sealed class PermissionMetadata +{ + public IReadOnlyList PluginSteps { get; set; } = []; + public IReadOnlyList Lookups { get; set; } = []; + public IReadOnlyList? Workflows { get; set; } + public IReadOnlyList RoleGovernedTables { get; set; } = []; +} + +/// A typed plugin identity or a synthetic entity operation. Construct via PermissionSelector in Core. +public sealed class PermissionScope +{ + private PermissionScope(string? pluginType, string? assembly, string? message, string? stage, string? table, IReadOnlyList? columns) + { + PluginType = pluginType; Assembly = assembly; Message = message; Stage = stage; Table = table; Columns = columns; + } + public string? PluginType { get; } + public string? Assembly { get; } + public string? Message { get; } + public string? Stage { get; } + public string? Table { get; } + public IReadOnlyList? Columns { get; } + + public static PermissionScope ForPlugin(string fullTypeName, string assemblyName, string? message = null, string? stage = null) + { + if (string.IsNullOrWhiteSpace(fullTypeName) || string.IsNullOrWhiteSpace(assemblyName)) throw new ArgumentException("A full plugin type and assembly identity are required."); + if (message is not null && string.IsNullOrWhiteSpace(message)) throw new ArgumentException("A message cannot be blank.", nameof(message)); + return new PermissionScope(fullTypeName, assemblyName, message?.Trim(), stage, null, null); + } + + public static PermissionScope ForOperation(string message, string table, IReadOnlyList? columns = null) + { + if (string.IsNullOrWhiteSpace(message) || string.IsNullOrWhiteSpace(table)) throw new ArgumentException("An operation message and entity logical name are required."); + if (columns?.Any(string.IsNullOrWhiteSpace) == true) throw new ArgumentException("Attribute names cannot be blank.", nameof(columns)); + return new PermissionScope(null, null, message.Trim(), null, table.Trim().ToLowerInvariant(), columns is null ? null : Array.AsReadOnly(columns.Select(c => c.Trim().ToLowerInvariant()).Distinct().OrderBy(c => c, StringComparer.Ordinal).ToArray())); + } + public override string ToString() => PluginType is null ? $"{Message} {Table}" : $"{PluginType}, {Assembly} ({Message ?? "all messages"}, {Stage ?? "all stages"})"; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionAnalyzer.Abstractions.csproj b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionAnalyzer.Abstractions.csproj new file mode 100644 index 00000000..78d891c6 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionAnalyzer.Abstractions.csproj @@ -0,0 +1,16 @@ + + + netstandard2.0 + + 1.0.0.0 + XrmMockup.PermissionAnalyzer.Abstractions + + false + Lightweight contracts and role coverage for XrmMockup static permission checks. + + + + + + + diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionCheckResult.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionCheckResult.cs new file mode 100644 index 00000000..a2fb7cbb --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/PermissionCheckResult.cs @@ -0,0 +1,51 @@ +using System.Text; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer; + +/// Static privilege coverage, not execution of a scenario or proof of record access. +public sealed class PermissionCheckResult(Manifest manifest, CoverageReport coverage, RoleSet? primaryRoles = null) +{ + public Manifest Manifest { get; } = manifest; + public CoverageReport Coverage { get; } = coverage; + public bool Passed => Coverage.Summary.Passed(strict: true); + + /// Throws a framework-neutral exception for missing privileges or incomplete analysis. + public void ThrowIfFailed() + { + if (Passed) return; + var message = new StringBuilder("Static permission check failed (not a record-level access check)."); + var summary = Coverage.Summary; + message.AppendLine().Append($"Summary: {summary.Missing} missing, {summary.Unresolved} unresolved, {summary.NotChecked} unchecked, {summary.Unverifiable} unverifiable, {summary.Truncated} truncated."); + if (primaryRoles is not null) message.AppendLine().Append($"Primary roles: {primaryRoles}"); + foreach (var entry in Manifest.EntryPoints) + { + var section = Coverage.For(entry); + message.AppendLine().Append($"Entry point: {entry.Id} at {entry.Declaration?.ToString() ?? "synthetic operation"}"); + foreach (var identity in section.Identities) + message.AppendLine().Append($" Identity: {identity.RunsAs}; roles: {identity.Roles?.ToString() ?? "unknown"}; {identity.Note}"); + foreach (var requirement in entry.Requirements) + { + var status = section.For(requirement).Status; + if (status is CoverageStatus.Missing or CoverageStatus.NotChecked or CoverageStatus.Unverifiable) + message.AppendLine().Append($" {status}: {requirement.Table} {requirement.Privilege}, {requirement.RunsAs}, at {string.Join(", ", requirement.Sources.Select(s => s.Location))}"); + } + foreach (var requirement in entry.GlobalRequirements) + { + var status = section.For(requirement).Status; + if (status is CoverageStatus.Missing or CoverageStatus.NotChecked or CoverageStatus.Unverifiable) + message.AppendLine().Append($" {status}: {requirement.Privilege}, {requirement.RunsAs}, at {string.Join(", ", requirement.Sources.Select(s => s.Location))}"); + } + foreach (var unresolved in entry.Unresolved.Where(u => u.RunsAs.Kind != RunsAsKind.System)) + message.AppendLine().Append($" Unresolved: {unresolved.Operation}: {unresolved.Reason}, {unresolved.RunsAs}, at {unresolved.Source.Location}"); + if (entry.Truncated) message.AppendLine().Append(" Analysis truncated at the call limit."); + } + throw new PermissionCheckException(message.ToString(), this); + } +} + +public sealed class PermissionCheckException(string message, PermissionCheckResult result) : Exception(message) +{ + public PermissionCheckResult Result { get; } = result; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Polyfills/IsExternalInit.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Polyfills/IsExternalInit.cs new file mode 100644 index 00000000..5b331890 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/Polyfills/IsExternalInit.cs @@ -0,0 +1,6 @@ +// Enables init-only setters and records when targeting netstandard2.0. +namespace System.Runtime.CompilerServices; + +internal static class IsExternalInit +{ +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/RequestReasons.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/RequestReasons.cs new file mode 100644 index 00000000..3c7f9cde --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Abstractions/RequestReasons.cs @@ -0,0 +1,68 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +internal static class RequestReasons +{ + private const string NoRulePrefix = "no rule for message '"; + private const string CustomApiPrefix = "custom API '"; + private const string RealTimeWorkflowPrefix = "fires real-time workflow '"; + private const string BackgroundWorkflowPrefix = "fires background workflow '"; + + public static string NoRule(string message) => NoRulePrefix + message + "'"; + + /// + /// A custom API that neither the code nor the privilege catalog has, so neither its code nor its execute + /// privilege is known. + /// + public static string CustomApi(string message) => CustomApiPrefix + message + "' is called; its code and execute privilege are unknown"; + + /// + /// A custom API in the privilege catalog whose code isn't loaded: its execute privilege is checked, its code isn't. + /// + public static string CustomApiCode(string message) => CustomApiPrefix + message + "' is called; its code isn't analyzed"; + + public static string ExecutePrivilegeComputed(string message) => CustomApiPrefix + message + "' needs an execute privilege set at runtime"; + + public static string PrivilegeCatalogMissing(string message, string privilege) => + CustomApiPrefix + message + $"' needs execute privilege '{privilege}', which needs a privilege catalog (PrivilegeCatalog.xml) to look up"; + + public static string PrivilegeNotInCatalog(string message, string privilege) => + CustomApiPrefix + message + $"' needs execute privilege '{privilege}', which isn't in the privilege catalog"; + + public static string PrivilegeWithoutTablePrivilege(string message, string privilege) => + CustomApiPrefix + message + $"' needs execute privilege '{privilege}', whose access right isn't a table privilege"; + + /// + /// A privilege a request rule names that the privilege catalog doesn't have, such as one misspelled in a configured + /// rule. + /// + public static string NamedPrivilegeNotInCatalog(string message, string privilege) => + $"the {message} request needs privilege '{privilege}', which isn't in the privilege catalog"; + + public static string NamedPrivilegeWithoutTablePrivilege(string message, string privilege) => + $"the {message} request needs privilege '{privilege}', whose access right isn't a table privilege"; + + /// + /// The message of a reason, or null for any other reason. + /// + public static string? NoRuleMessage(string reason) => + reason.StartsWith(NoRulePrefix, StringComparison.Ordinal) && reason.EndsWith("'", StringComparison.Ordinal) + ? reason.Substring(NoRulePrefix.Length, reason.Length - NoRulePrefix.Length - 1) + : null; + + /// + /// A reason about calling a custom API: its code or its execute privilege. + /// + public static bool IsCustomApi(string reason) => reason.StartsWith(CustomApiPrefix, StringComparison.Ordinal); + + /// + /// A workflow from the metadata that an operation fires, whose steps aren't analyzed. + /// + public static string Workflow(string name, bool realTime) => + (realTime ? RealTimeWorkflowPrefix : BackgroundWorkflowPrefix) + name + "', whose steps aren't analyzed"; + + /// + /// A reason about a fired . + /// + public static bool IsWorkflow(string reason) => + reason.StartsWith(RealTimeWorkflowPrefix, StringComparison.Ordinal) || reason.StartsWith(BackgroundWorkflowPrefix, StringComparison.Ordinal); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/EntryPointSelector.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/EntryPointSelector.cs new file mode 100644 index 00000000..7372ac73 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/EntryPointSelector.cs @@ -0,0 +1,93 @@ +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Analysis; + +/// +/// Limits an analysis to some entry points: --plugin, --custom-api, --function or +/// --operation. +/// Explicit methods (--entry) are added with instead. +/// +public sealed class EntryPointSelector +{ + private readonly Func _matches; + private readonly string _text; + + private EntryPointSelector(string text, Func matches) + { + _text = text; + _matches = matches; + } + + /// + /// A plugin by simple or full type name, optionally narrowed to a message and stage: + /// AccountPostPlugin, AccountPostPlugin:Update or Contoso.AccountPostPlugin:Update:PostOperation. + /// + public static EntryPointSelector Plugin(string selector) + { + var parts = selector.Split(':'); + var type = parts[0]; + var message = parts.Length > 1 ? parts[1] : null; + var stage = parts.Length > 2 ? parts[2] : null; + return new EntryPointSelector($"--plugin {selector}", e => + e.Kind is EntryPointKind.PluginStep or EntryPointKind.Plugin + && TypeMatches(e.Type, type) + && (message is null || Same(e.Trigger?.Message, message)) + && (stage is null || Same(e.Trigger?.Stage, stage))); + } + + public static EntryPointSelector CustomApi(string name) => + new($"--custom-api {name}", e => e.Kind == EntryPointKind.CustomApi && Same(e.Trigger?.Message, name)); + + /// + /// Functions by name, in any app, or by their app's assembly and name, such as Contoso.Functions/ProcessOrder. + /// + public static EntryPointSelector Function(string name) => + new($"--function {name}", e => e.Kind == EntryPointKind.Function + && (Same(EntryPointIds.FunctionName(e.Id), name) || Same(EntryPointIds.QualifiedFunctionName(e.Id), name))); + + /// + /// Methods added with , by the same names. + /// + public static EntryPointSelector Methods(IReadOnlyList methods) => + new($"--entry {string.Join(" --entry ", methods)}", e => + e.Kind == EntryPointKind.Method + && EntryPointIds.MethodId(e.Id) is { } id + && methods.Any(m => ManifestBuilder.MatchesMethod(id, m))); + + /// + /// The operation added with for on + /// , by the same names: the message or its request type, such as CreateRequest. + /// + public static EntryPointSelector Operation(string message, string table) + { + message = message.Trim(); + table = table.Trim(); + var ofType = RequestRules.MessageOfType(message); + return new($"--operation {message} {table}", e => + e.Kind == EntryPointKind.Operation + && Same(e.Trigger?.Table, table) + && (Same(e.Trigger?.Message, message) || Same(e.Trigger?.Message, ofType))); + } + + /// Exact SDK plugin type and assembly identity, unlike the CLI's shorthand selector. + public static EntryPointSelector TypedPlugin(PermissionScope scope) => + new(scope.ToString(), e => e.Kind is EntryPointKind.PluginStep + && string.Equals(e.Type.Replace('+', '.'), scope.PluginType?.Replace('+', '.'), StringComparison.Ordinal) + && string.Equals(e.Assembly, scope.Assembly, StringComparison.Ordinal) + && (scope.Message is null || Same(e.Trigger?.Message, scope.Message)) + && (scope.Stage is null || Same(e.Trigger?.Stage, scope.Stage))); + + public bool Matches(EntryPoint entryPoint) => _matches(entryPoint); + + public override string ToString() => _text; + + private static bool TypeMatches(string fullName, string name) + { + if (Same(fullName, name)) return true; + var simple = fullName.Substring(Math.Max(fullName.LastIndexOf('.'), fullName.LastIndexOf('+')) + 1); + return Same(simple, name); + } + + private static bool Same(string? x, string y) => string.Equals(x, y, StringComparison.OrdinalIgnoreCase); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/ManifestBuilder.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/ManifestBuilder.cs new file mode 100644 index 00000000..5d946df5 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/ManifestBuilder.cs @@ -0,0 +1,638 @@ +using Microsoft.CodeAnalysis; +using XrmMockup.PermissionAnalyzer.Core.Discovery; +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Graph; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Analysis; + +/// +/// Builds a from one or more compilations: finds the entry points, follows the calls +/// from each and collects the privileges the reached operations need. A project that targets several +/// frameworks is added once per target; its duplicate findings merge into one. +/// +/// The directory source locations are reported relative to. +/// +/// Rules for the requests passed to Execute, which replace the built-in rule for their message or add one. +/// +/// +/// The lookup columns in the metadata, which give the tables a lookup can refer to when the code doesn't say. +/// +public sealed class ManifestBuilder(string rootDirectory, IEnumerable? rules = null, IEnumerable? lookups = null) +{ + /// Copies extracted source summaries, replacing check-time plugin and lookup metadata. + /// The graph is read-only during Build. Loaded compilations and metadata-dependent summaries are reused; + /// entry point evaluation and role coverage are always fresh. + public ManifestBuilder WithMetadata(PermissionMetadata metadata) + { + if (metadata is null) throw new ArgumentNullException(nameof(metadata)); + var key = LookupKey(metadata.Lookups); + var graphSource = this; + if (key != _lookupKey) + { + lock (_metadataGraphs) + { + if (!_metadataGraphs.TryGetValue(key, out graphSource)) + { + // Compilations are loaded once. Extract a metadata-dependent graph once per lookup + // catalog, then reuse it; role coverage and entry point evaluation are never cached. + graphSource = new ManifestBuilder(_rootDirectory, _customRules, metadata.Lookups); + foreach (var input in _sourceInputs) graphSource.Add(input.Compilation, input.Kind, default); + _metadataGraphs.Add(key, graphSource); + } + } + } + return new ManifestBuilder(this, graphSource, metadata); + } + + private static string LookupKey(IEnumerable columns) => string.Join("\n", columns + .Select(c => c.Table.ToLowerInvariant() + ":" + c.Column.ToLowerInvariant() + ":" + string.Join(",", c.Targets.Select(t => t.ToLowerInvariant()).OrderBy(t => t, StringComparer.Ordinal))) + .Distinct().OrderBy(c => c, StringComparer.Ordinal)); + private readonly string _lookupKey = LookupKey(lookups ?? []); + private readonly IReadOnlyList? _customRules = rules?.ToList(); + private readonly List<(Compilation Compilation, AddedCode Kind)> _sourceInputs = []; + private readonly Dictionary _metadataGraphs = new(StringComparer.Ordinal); + + private readonly string _rootDirectory = rootDirectory; + private ManifestBuilder(ManifestBuilder source, ManifestBuilder graphSource, PermissionMetadata metadata) : this(source._rootDirectory, source._customRules, metadata.Lookups) + { + _graph = graphSource._graph; _paths = source._paths; _rules = source._rules; + _lookups = new LookupColumns(metadata.Lookups); + _privilegeCatalog = source._privilegeCatalog is null ? null : new Dictionary(source._privilegeCatalog, StringComparer.OrdinalIgnoreCase); + foreach (var pair in graphSource._entries) _entries.Add(pair.Key, pair.Value); + foreach (var pair in graphSource._plugins) _plugins.Add(pair.Key, pair.Value); + _cascadeOnlyEntries.UnionWith(graphSource._cascadeOnlyEntries); + _cascadeOnlyPlugins.UnionWith(graphSource._cascadeOnlyPlugins); + _reportedNodes.UnionWith(graphSource._reportedNodes); + _entryMethods.AddRange(source._entryMethods); + _workflows.AddRange(metadata.Workflows ?? source._workflows); + foreach (var pair in source._catalogCustomApis) _catalogCustomApis.Add(pair.Key, pair.Value); + AddPluginSteps(metadata.PluginSteps); + } + + private const string InjectedAssumption = "service is injected"; + + private readonly SourcePaths _paths = new(rootDirectory); + private readonly RequestRules _rules = new(rules); + private readonly LookupColumns _lookups = new(lookups); + private readonly CallGraph _graph = new(); + private readonly Dictionary _entries = new(StringComparer.Ordinal); + private readonly Dictionary _plugins = new(StringComparer.Ordinal); + private readonly List _steps = []; + private readonly List _workflows = []; + private readonly List _entryMethods = []; + private readonly Dictionary _operations = new(StringComparer.Ordinal); + + // What only plugin code from other solutions has, which runs in cascades but isn't reported on its own + private readonly HashSet _cascadeOnlyEntries = new(StringComparer.Ordinal); + private readonly HashSet _cascadeOnlyPlugins = new(StringComparer.Ordinal); + private readonly HashSet _reportedNodes = new(StringComparer.Ordinal); + private readonly Dictionary _catalogCustomApis = new(StringComparer.OrdinalIgnoreCase); + private Dictionary? _privilegeCatalog; + + /// + /// Adds the code in . Returns false when the compilation doesn't + /// reference the Dataverse SDK, so it can't contain any operations. + /// + public bool Add(Compilation compilation, CancellationToken cancellationToken = default) => Add(compilation, AddedCode.Analyzed, cancellationToken); + + /// + /// Adds the code of a library the analyzed code references, such as a data access library that several apps share. + /// Its entry points are reported and what the analyzed code calls in it is analyzed, but its methods that no entry + /// point reaches aren't reported as unreached: other apps may call them. Code that + /// adds as well is reported. Returns false when the + /// compilation doesn't reference the Dataverse SDK. + /// + public bool AddReferencedCode(Compilation compilation, CancellationToken cancellationToken = default) => Add(compilation, AddedCode.Referenced, cancellationToken); + + /// + /// Adds plugin code from outside the analyzed solution, such as the plugins of the environment an Azure Function + /// app calls. Its plugin steps and custom APIs run when operations fire them, but its entry points and unreached + /// methods aren't reported, unless a scope selects them. Code that + /// adds as well is reported. Returns false when the compilation doesn't reference the Dataverse SDK. + /// + public bool AddPluginCode(Compilation compilation, CancellationToken cancellationToken = default) => Add(compilation, AddedCode.PluginCode, cancellationToken); + + /// + /// Whether the code the last Add, AddReferencedCode or AddPluginCode call added has code the + /// compiler couldn't bind, such as a call to a method or on a type it didn't find. Operations in that code are + /// missed. Its compile errors are worth reporting then; without it, the declarations and syntax are what's left to + /// check. + /// + public bool LastAddedHasUnboundCode { get; private set; } + + private enum AddedCode { Analyzed, Referenced, PluginCode } + + private bool Add(Compilation compilation, AddedCode added, CancellationToken cancellationToken) + { + var cascadesOnly = added == AddedCode.PluginCode; + LastAddedHasUnboundCode = false; + if (XrmSymbols.Create(compilation) is not { } symbols) return false; + + _sourceInputs.Add((compilation, added)); + _metadataGraphs.Clear(); + var extractor = new SummaryExtractor(compilation, symbols, _paths, _rules, _lookups); + var summaries = extractor.Extract(cancellationToken); + LastAddedHasUnboundCode = extractor.HasUnboundCode; + if (added == AddedCode.Analyzed) _reportedNodes.UnionWith(summaries.Nodes.Keys); + _graph.Merge(summaries); + + var discovery = new EntryPointDiscovery(compilation, symbols, _paths).Discover(cancellationToken); + foreach (var entry in discovery.Entries) + { + if (!cascadesOnly) _cascadeOnlyEntries.Remove(entry.Id); + else if (!_entries.ContainsKey(entry.Id)) _cascadeOnlyEntries.Add(entry.Id); + AddEntry(entry); + } + foreach (var plugin in discovery.Plugins) + { + var key = Key(plugin); + if (!cascadesOnly) _cascadeOnlyPlugins.Remove(key); + else if (!_plugins.ContainsKey(key)) _cascadeOnlyPlugins.Add(key); + + if (_plugins.TryGetValue(key, out var existing)) _plugins[key] = existing with { HasCodeSteps = existing.HasCodeSteps || plugin.HasCodeSteps }; + else _plugins.Add(key, plugin); + } + return true; + } + + /// + /// Adds the plugin steps registered in the environment, from the XrmMockup metadata. + /// + public void AddPluginSteps(IEnumerable steps) => _steps.AddRange(steps); + + /// + /// Adds the workflows that run automatically, from the XrmMockup metadata. Their steps aren't analyzed, so an + /// operation that fires one reports it as unresolved. + /// + public void AddWorkflows(IEnumerable workflows) => _workflows.AddRange(workflows); + + /// + /// Adds the privilege catalog from the metadata: the tables and table privilege of each privilege, by name, and + /// the execute privileges of the custom APIs in the environment. Without it, an execute privilege set by name + /// can't be looked up and is reported as unresolved. + /// + public void AddPrivilegeCatalog(IEnumerable privileges, IEnumerable customApis) + { + _privilegeCatalog ??= new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var privilege in privileges) _privilegeCatalog[privilege.Name] = privilege; + foreach (var api in customApis) _catalogCustomApis[api.UniqueName] = api; + } + + /// + /// Adds methods to analyze as entry points, such as Contoso.Sync.Importer.Run, which matches every + /// overload, or a full id with parameter types. + /// + public void AddEntryMethods(IEnumerable methods) => _entryMethods.AddRange(methods); + + /// + /// Adds a user operation to analyze as an entry point, such as Update on account made in an app: + /// the privileges its request needs as the caller, and those of the plugin steps it fires. + /// are the columns it sets, which decide the Update steps filtered on columns that it fires; without them those + /// steps fire with the basis . + /// + public void AddOperation(string message, string table, IEnumerable? columns = null) + { + var set = columns? + .Select(c => c.Trim().ToLowerInvariant()) + .Where(c => c.Length > 0) + .Distinct(StringComparer.Ordinal) + .OrderBy(c => c, StringComparer.Ordinal) + .ToList(); + var operation = new UserOperation(_rules.MessageNamed(message.Trim()), table.Trim().ToLowerInvariant(), set is { Count: > 0 } ? set : null); + var id = EntryPointIds.Operation(operation.Display, operation.Columns); + _operations[id] = operation; + } + + /// + /// Builds the manifest. Pass the tables that at least one security role mentions to fill + /// ; leave it null when no roles are known. With a + /// , only the matching entry points are analyzed and nothing is reported as unreached; + /// without one, the entry points of plugin code added with are left out. + /// + public Manifest Build(IEnumerable? roleGovernedTables = null, EntryPointSelector? scope = null) + { + var candidates = new Dictionary(_entries, StringComparer.Ordinal); + var cascadeOnly = new HashSet(_cascadeOnlyEntries, StringComparer.Ordinal); + var codeless = AddMetadataSteps(candidates, cascadeOnly); + AddMethodEntries(candidates); + foreach (var operation in _operations) + { + candidates[operation.Key] = new EntryCandidate(operation.Key, EntryPointKind.Operation, "", null, new Trigger(operation.Value.Message, operation.Value.Table), null, null, []); + } + codeless.AddRange(WorkflowSteps()); + var cascades = new Cascades(_graph, CascadeSteps(candidates.Values, codeless), (step, caller) => Context(caller, step.Trigger?.Table)); + + var resolver = new PrivilegeResolver(_privilegeCatalog, _catalogCustomApis, candidates.Values, _steps.Select(s => s.Message)); + + var entryPoints = new List(); + var reached = new HashSet(StringComparer.Ordinal); + foreach (var candidate in candidates.Values.OrderBy(c => c.Id, StringComparer.Ordinal)) + { + if (scope is not null && !scope.Matches(Describe(candidate, [], [], []))) continue; + + var context = Context(candidate); + var evaluator = new Evaluator(_graph, context); + if (scope is null && cascadeOnly.Contains(candidate.Id)) + { + // Not reported, but what it reaches isn't unreached + reached.UnionWith(evaluator.Evaluate(candidate.Handlers).Reached); + continue; + } + + var evaluation = _operations.TryGetValue(candidate.Id, out var user) + ? Unprefixed(evaluator.EvaluateAlone(user.Node(candidate.Id, _rules, _lookups), user.Display)) + : evaluator.Evaluate(candidate.Handlers); + var cascade = cascades.Expand(evaluation, candidate.Id, context.Caller); + reached.UnionWith(cascade.Result.Reached); + entryPoints.Add(Describe(candidate, cascade, context.Caller, resolver)); + } + + var unreached = scope is null ? Unreached(reached, resolver) : []; + var manifest = new Manifest(entryPoints, unreached); + if (roleGovernedTables is null) return manifest; + + var governed = new HashSet(roleGovernedTables.Select(t => t.ToLowerInvariant()), StringComparer.Ordinal); + return new Manifest(entryPoints, unreached, manifest.Tables.Where(t => !governed.Contains(t)).ToList()); + } + + /// + /// without call paths. A user operation's hits are at , + /// so the path of a step it fires starts at the operation. + /// + private static EvaluationResult Unprefixed(EvaluationResult result) + { + var unprefixed = new EvaluationResult { Truncated = result.Truncated }; + unprefixed.Requirements.AddRange(result.Requirements.Select(h => h with { Source = h.Source with { Path = [] } })); + unprefixed.Unresolved.AddRange(result.Unresolved.Select(h => h with { Source = h.Source with { Path = [] } })); + unprefixed.Assumptions.AddRange(result.Assumptions.Select(h => h with { Source = h.Source with { Path = [] } })); + unprefixed.Globals.AddRange(result.Globals.Select(h => h with { Source = h.Source with { Path = [] } })); + unprefixed.Triggers.AddRange(result.Triggers.Select(h => h with { Source = h.Source with { Path = [] } })); + return unprefixed; + } + + private void AddEntry(EntryCandidate entry) + { + if (!_entries.TryGetValue(entry.Id, out var existing)) + { + _entries.Add(entry.Id, entry); + return; + } + + // The same registration compiled for another target framework, or a step registered twice + var handlers = existing.Handlers.Concat(entry.Handlers).Distinct().ToList(); + _entries[entry.Id] = existing with + { + // Independent of the order compilations are added in + Assembly = First(existing.Assembly, entry.Assembly, string.CompareOrdinal), + Handlers = handlers.OrderBy(h => h.Target, StringComparer.Ordinal).ThenBy(h => h.ObjectType, StringComparer.Ordinal).ToList(), + Declaration = First(existing.Declaration, entry.Declaration, (x, y) => x.CompareTo(y)), + ImpersonatingUserId = First(existing.ImpersonatingUserId, entry.ImpersonatingUserId, string.CompareOrdinal), + }; + } + + /// + /// The value that sorts first, ignoring null. + /// + private static T? First(T? a, T? b, Func compare) where T : class => + a is null ? b : b is null ? a : compare(b, a) < 0 ? b : a; + + /// + /// Steps from the metadata. A step of a plugin that registers its steps in code adds the impersonating user + /// to the matching code step, or runs Execute when no code step matches. A plain IPlugin gets + /// one entry point per step, or one for the whole plugin when the metadata has no steps for it. Returns the + /// steps of plugins whose code isn't loaded. Adds the entry points of plugins that only plugin code from other + /// solutions has to . + /// + private List AddMetadataSteps(Dictionary candidates, HashSet cascadeOnly) + { + var codeless = new List(); + var classes = _plugins.Values.OrderBy(p => p.Type, StringComparer.Ordinal).ThenBy(p => p.Assembly, StringComparer.Ordinal).ToList(); + var classesByType = classes.ToLookup(c => c.Type, StringComparer.Ordinal); + var stepsByClass = new Dictionary>(); + foreach (var step in _steps) + { + var named = classesByType[step.TypeName]; + var matches = named.Where(c => step.AssemblyName is not null && c.Assembly == step.AssemblyName).ToList(); + if (matches.Count == 0) matches = named.ToList(); + if (matches.Count == 0 && !string.IsNullOrEmpty(step.Message)) + { + var table = Lower(step.Table); + var id = EntryPointIds.PluginStep(step.TypeName, step.Message, table, EntryPointDiscovery.StageName(step.Stage)); + codeless.Add(new CascadeStep(id, step.Message, table, Lower(step.ImpersonatingUserId), Filter(step), null, step.Asynchronous)); + } + foreach (var match in matches) + { + if (!stepsByClass.TryGetValue(match, out var list)) stepsByClass.Add(match, list = []); + list.Add(step); + } + } + + var bases = new HashSet( + classes.SelectMany(c => _graph.Types.TryGetValue(c.TypeId, out var type) ? type.Ancestors : []), + StringComparer.Ordinal); + + // The ids of the plugin step entry points of each plugin type, in the order added + var codeSteps = candidates.Values + .Where(c => c.Kind == EntryPointKind.PluginStep) + .GroupBy(c => c.Type, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.Select(c => c.Id).ToList(), StringComparer.Ordinal); + + foreach (var plugin in classes) + { + stepsByClass.TryGetValue(plugin, out var steps); + var handlers = plugin.Execute is null ? [] : new[] { new Handler(plugin.Execute, plugin.TypeId) }; + + if (steps is null || steps.Count == 0) + { + // A base class of other plugins, such as a DAXIF Plugin class, isn't registered itself + if (!plugin.HasCodeSteps && !bases.Contains(plugin.TypeId)) + { + var id = EntryPointIds.Plugin(plugin.Type); + if (!candidates.ContainsKey(id)) + { + candidates.Add(id, new EntryCandidate(id, EntryPointKind.Plugin, plugin.Type, plugin.Assembly, null, null, plugin.Declaration, handlers)); + if (IsCascadeOnly(plugin)) cascadeOnly.Add(id); + } + } + continue; + } + + foreach (var step in steps) + { + var stage = EntryPointDiscovery.StageName(step.Stage); + var table = Lower(step.Table); + var user = Lower(step.ImpersonatingUserId); + var filter = Filter(step); + + var code = plugin.HasCodeSteps && codeSteps.TryGetValue(plugin.Type, out var ids) + ? ids.Select(i => candidates[i]).FirstOrDefault(c => + string.Equals(c.Trigger?.Message, step.Message, StringComparison.OrdinalIgnoreCase) + && string.Equals(c.Trigger?.Table, table, StringComparison.OrdinalIgnoreCase) + && string.Equals(c.Trigger?.Stage, stage, StringComparison.OrdinalIgnoreCase)) + : null; + + var id = EntryPointIds.PluginStep(plugin.Type, step.Message, table, stage); + if ((code ?? (candidates.TryGetValue(id, out var existing) ? existing : null)) is { } registered) + { + candidates[registered.Id] = Registered(registered, user, filter, step.Asynchronous); + continue; + } + candidates.Add(id, new EntryCandidate(id, EntryPointKind.PluginStep, plugin.Type, plugin.Assembly, new Trigger(step.Message, table, stage, FilteredAttributes: filter, Asynchronous: step.Asynchronous), user, plugin.Declaration, handlers)); + if (!codeSteps.TryGetValue(plugin.Type, out var added)) codeSteps.Add(plugin.Type, added = []); + added.Add(id); + if (IsCascadeOnly(plugin)) cascadeOnly.Add(id); + } + } + return codeless; + } + + private bool IsCascadeOnly(PluginClass plugin) => _cascadeOnlyPlugins.Contains(Key(plugin)); + + private static string Key(PluginClass plugin) => plugin.Type + "\n" + plugin.Assembly; + + /// + /// A table or user id from the metadata, lowercased; null when it isn't set. + /// + private static string? Lower(string? value) => string.IsNullOrEmpty(value) ? null : value!.ToLowerInvariant(); + + /// + /// The columns an Update step from the metadata is filtered on, lowercased. + /// + private static IReadOnlyList? Filter(PluginStepRegistration step) => + Trigger.Filters(step.Message) ? step.FilteredAttributes : null; + + /// + /// with the user, filtered attributes and mode of its registration in the metadata, + /// where the code doesn't set them. + /// + private static EntryCandidate Registered(EntryCandidate candidate, string? user, IReadOnlyList? filter, bool asynchronous) + { + if (user is not null && candidate.ImpersonatingUserId is null) candidate = candidate with { ImpersonatingUserId = user }; + if (filter is not null && candidate.Trigger is { FilteredAttributes: null } trigger) candidate = candidate with { Trigger = trigger with { FilteredAttributes = filter } }; + if (asynchronous && candidate.Trigger is { Asynchronous: false } synchronous) candidate = candidate with { Trigger = synchronous with { Asynchronous = true } }; + return candidate; + } + + /// + /// The plugin steps and custom APIs that operations fire, by message: every one, whatever the scope. + /// + private static IEnumerable CascadeSteps(IEnumerable candidates, IEnumerable codeless) => + candidates + .Where(c => c.Kind is EntryPointKind.PluginStep or EntryPointKind.CustomApi && c.Trigger?.Message is not null) + .Select(c => new CascadeStep(c.Id, c.Trigger!.Message!, c.Trigger.Table, c.ImpersonatingUserId, c.Trigger.FilteredAttributes, c, c.Trigger.Asynchronous, c.Kind == EntryPointKind.CustomApi)) + .Concat(codeless.GroupBy(s => s.Id, StringComparer.Ordinal).Select(g => g.First())); + + /// + /// A step for each message that runs a workflow from the metadata. A workflow that runs as its owner runs as that + /// user, like a step that impersonates. + /// + private IEnumerable WorkflowSteps() + { + foreach (var workflow in _workflows) + { + var table = workflow.Table.ToLowerInvariant(); + var messages = new List<(string Message, IReadOnlyList? Columns)>(); + if (workflow.OnCreate) messages.Add((Messages.Create, null)); + if (workflow.UpdateColumns is { Count: > 0 } filter) messages.Add((Messages.Update, filter.Select(c => c.ToLowerInvariant()).ToList())); + if (workflow.OnDelete) messages.Add((Messages.Delete, null)); + foreach (var (message, columns) in messages) + { + yield return new CascadeStep( + EntryPointIds.Workflow(workflow.Name, message, table), message, table, Lower(workflow.RunsAsUserId), columns, null, !workflow.RealTime, Workflow: workflow.Name); + } + } + } + + private void AddMethodEntries(Dictionary candidates) + { + foreach (var method in _entryMethods) + { + var matches = _graph.Nodes.Values + .Where(n => n.Id == n.Member && MatchesMethod(n.Id, method)) + .OrderBy(n => n.Id, StringComparer.Ordinal); + foreach (var node in matches) + { + var id = EntryPointIds.Method(node.Id); + if (candidates.ContainsKey(id)) continue; + var type = node.Type is { } typeId ? typeId : ""; + candidates.Add(id, new EntryCandidate(id, EntryPointKind.Method, type, null, null, null, node.Declaration, [new Handler(node.Id, null)])); + } + } + } + + /// + /// A method name given to matches every overload of the method, generic ones too, + /// or one by its full id. + /// + internal static bool MatchesMethod(string id, string method) => + id == method || id.StartsWith(method + "(", StringComparison.Ordinal) || id.StartsWith(method + "<", StringComparison.Ordinal); + + /// + /// Method entries named in that match no method in the solution. + /// + public IReadOnlyList UnmatchedEntryMethods() => + _entryMethods + .Where(m => !_graph.Nodes.Values.Any(n => n.Id == n.Member && MatchesMethod(n.Id, m))) + .Distinct(StringComparer.Ordinal) + .OrderBy(m => m, StringComparer.Ordinal) + .ToList(); + + /// + /// Who the entry point's code runs as. Plugins and activities run as the calling user, or the step's + /// impersonating user; functions and other code as an application user. + /// + private static EntryContext Context(EntryCandidate candidate) => + candidate.Kind switch + { + EntryPointKind.Function => Context(RunsAs.ApplicationUser), + + // Who calls an explicit method isn't known; app code usually runs as its application user + EntryPointKind.Method => Context(RunsAs.ApplicationUser with { Assumed = true }), + + _ => Context(candidate.ImpersonatingUserId is { } user ? RunsAs.User(user) : RunsAs.Caller, candidate.Trigger?.Table), + }; + + /// + /// Code that runs as , with injected services assumed to run as it too, for a step on + /// . + /// + private static EntryContext Context(RunsAs caller, string? primaryTable = null) => + new(caller, new Identity(caller with { Assumed = true }, InjectedAssumption), primaryTable); + + /// + /// Methods with operations that no entry point reaches, each analyzed on its own. Referenced libraries and plugin code + /// from other solutions are left out. + /// + private List Unreached(HashSet reached, PrivilegeResolver resolver) + { + var evaluator = new Evaluator(_graph, Context(RunsAs.Caller)); + return _graph.Nodes.Values + .Where(n => n.Accesses.Count > 0 && !reached.Contains(n.Id) && _reportedNodes.Contains(n.Id)) + .GroupBy(n => n.Member, StringComparer.Ordinal) + .OrderBy(g => g.Key, StringComparer.Ordinal) + .Select(g => + { + var results = g.OrderBy(n => n.Id, StringComparer.Ordinal).Select(n => evaluator.EvaluateAlone(n, n.Display)).ToList(); + var member = _graph.Nodes.TryGetValue(g.Key, out var memberNode) ? memberNode : null; + var declaration = member?.Declaration ?? g.Select(n => n.MemberDeclaration).Where(d => d is not null).Min(); + var hits = resolver.Resolve(results); + var (requirements, unresolved, assumptions, globalRequirements) = Aggregate(hits, RunsAs.ApplicationUser with { Assumed = true }); + return new MethodManifest(g.Key, declaration, requirements, unresolved, assumptions, globalRequirements, hits.Truncated); + }) + .ToList(); + } + + private static EntryPoint Describe(EntryCandidate candidate, CascadeResult cascade, RunsAs caller, PrivilegeResolver resolver) + { + var hits = resolver.Resolve([cascade.Result], candidate.Kind == EntryPointKind.CustomApi ? candidate : null); + var (requirements, unresolved, assumptions, globalRequirements) = Aggregate(hits, caller); + return Describe(candidate, requirements, unresolved, assumptions, cascade.Fired, globalRequirements, hits.Truncated); + } + + private static EntryPoint Describe( + EntryCandidate candidate, + IReadOnlyList requirements, + IReadOnlyList unresolved, + IReadOnlyList assumptions, + IReadOnlyList? triggers = null, + IReadOnlyList? globalRequirements = null, + bool truncated = false) => + new( + candidate.Id, + candidate.Kind, + candidate.Type, + candidate.Assembly, + candidate.Trigger, + candidate.ImpersonatingUserId, + candidate.Declaration, + requirements, + unresolved, + assumptions, + triggers, + globalRequirements, + truncated); + + /// + /// Merges the hits of an evaluation: one requirement per table (or privilege not tied to a table), privilege and + /// identity, with the strongest basis and one source per location (the shortest call path), and one unresolved + /// operation per location, reason and identity, with the privileges of each. All sorted. Operations that act for + /// the user in CallerId need on + /// , the identity that sets it. + /// + private static (IReadOnlyList, IReadOnlyList, IReadOnlyList, IReadOnlyList) Aggregate( + ResolvedHits hits, + RunsAs impersonator) + { + hits.Globals.AddRange(hits.Requirements + .Where(h => h.RunsAs.Kind == RunsAsKind.ImpersonatedCaller) + .Select(h => new GlobalHit(GlobalRequirement.ActOnBehalfOfAnotherUser, impersonator, h.Basis, h.Source))); + hits.Globals.AddRange(hits.Unresolved + .Where(h => h.RunsAs.Kind == RunsAsKind.ImpersonatedCaller) + .Select(h => new GlobalHit(GlobalRequirement.ActOnBehalfOfAnotherUser, impersonator, RequirementBasis.Direct, h.Source))); + + var requirements = hits.Requirements + .GroupBy(h => (h.Table, h.Privilege, h.RunsAs)) + .Select(g => new Requirement( + g.Key.Table, + g.Key.Privilege, + g.Key.RunsAs, + g.Min(h => h.Basis), + FirstPerLocation(g.Select(h => h.Source)))) + .OrderBy(r => r.Table, StringComparer.Ordinal) + .ThenBy(r => r.Privilege) + .ThenBy(r => r.RunsAs) + .ThenBy(r => r.Basis) + .ToList(); + + var globalRequirements = hits.Globals + .GroupBy(h => (h.Privilege, h.RunsAs)) + .Select(g => new GlobalRequirement(g.Key.Privilege, g.Key.RunsAs, g.Min(h => h.Basis), FirstPerLocation(g.Select(h => h.Source)))) + .OrderBy(r => r.Privilege, StringComparer.Ordinal) + .ThenBy(r => r.RunsAs) + .ThenBy(r => r.Basis) + .ToList(); + + var unresolved = hits.Unresolved + .GroupBy(h => (h.Source.Location, h.Operation, h.Reason, h.RunsAs)) + .Select(g => g.First() with { Privileges = g.SelectMany(h => h.Privileges).Distinct().OrderBy(p => p).ToList() }) + .OrderBy(h => h.Source.Location) + .ThenBy(h => h.Operation, StringComparer.Ordinal) + .ThenBy(h => h.Reason, StringComparer.Ordinal) + .ThenBy(h => string.Join(",", h.Privileges), StringComparer.Ordinal) + .ThenBy(h => h.RunsAs) + .Select(h => new UnresolvedOperation(h.Operation, h.Privileges, h.Reason, h.RunsAs, h.Source)) + .ToList(); + + var assumptions = hits.Assumptions + .GroupBy(h => (h.Source.Location, h.Reason)) + .Select(g => g.First()) + .OrderBy(h => h.Source.Location) + .ThenBy(h => h.Reason, StringComparer.Ordinal) + .Select(h => new Assumption(h.Reason, h.Source)) + .ToList(); + + if (hits.Truncated) + { + var location = assumptions.FirstOrDefault()?.Source + ?? requirements.SelectMany(r => r.Sources).FirstOrDefault() + ?? unresolved.FirstOrDefault()?.Source + ?? globalRequirements.SelectMany(r => r.Sources).FirstOrDefault(); + if (location is not null) + { + assumptions.Insert(0, new Assumption($"analysis stopped after {Evaluator.MaxVisits} calls; requirements may be incomplete", location)); + } + } + + return (requirements, unresolved, assumptions, globalRequirements); + } + + /// + /// One source per location, the first found; the evaluation is breadth-first, so it has the shortest path. + /// + private static IReadOnlyList FirstPerLocation(IEnumerable sources) + { + var seen = new HashSet(); + return sources.Where(s => seen.Add(s.Location)).OrderBy(s => s).ToList(); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/PrivilegeResolver.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/PrivilegeResolver.cs new file mode 100644 index 00000000..3adbeab1 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Analysis/PrivilegeResolver.cs @@ -0,0 +1,169 @@ +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Graph; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Analysis; + +/// +/// Resolves what the hits of an evaluation need that the evaluation can't know on its own: the execute privileges +/// of the custom APIs it calls, and the privileges request rules name, looked up in the privilege catalog. +/// +internal sealed class PrivilegeResolver +{ + private readonly IReadOnlyDictionary? _catalog; + private readonly IReadOnlyDictionary _catalogCustomApis; + private readonly HashSet _customApis = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _customApiCode = new(StringComparer.OrdinalIgnoreCase); + + /// The privileges by name; null when there is no privilege catalog. + /// The custom APIs in the privilege catalog, by unique name. + /// The entry points, whose custom APIs are the code of the custom APIs. + /// The messages of the plugin steps in the metadata. + public PrivilegeResolver( + IReadOnlyDictionary? catalog, + IReadOnlyDictionary catalogCustomApis, + IEnumerable candidates, + IEnumerable stepMessages) + { + _catalog = catalog; + _catalogCustomApis = catalogCustomApis; + + // Messages the solution implements or registers steps on, which no rule knows, are its custom APIs + var list = candidates.ToList(); + _customApis.UnionWith(list.Where(c => c.Kind != EntryPointKind.Operation).Select(c => c.Trigger?.Message).Concat(stepMessages).OfType()); + foreach (var api in list.Where(c => c.Kind == EntryPointKind.CustomApi).OrderBy(c => c.Id, StringComparer.Ordinal)) + { + if (api.Trigger?.Message is { } message && !_customApiCode.ContainsKey(message)) _customApiCode[message] = api; + } + } + + /// + /// The hits of , with calls to custom APIs and privileges named by request rules + /// resolved. Pass the entry point of a custom API as to add its own execute + /// privilege, which its caller needs. + /// + public ResolvedHits Resolve(IReadOnlyList results, EntryCandidate? customApi = null) + { + var hits = new ResolvedHits { Truncated = results.Any(r => r.Truncated) }; + hits.Requirements.AddRange(results.SelectMany(r => r.Requirements)); + hits.Assumptions.AddRange(results.SelectMany(r => r.Assumptions)); + foreach (var hit in results.SelectMany(r => r.Unresolved)) + { + if (RequestReasons.NoRuleMessage(hit.Reason) is { } message && IsKnownCustomApi(message)) + { + ExecutePrivilegeHits(message, ExecutePrivilegeOf(message), hit.RunsAs, hit.Source, hits); + + // The code of a custom API runs as a cascade, so only a custom API without code stays unresolved + if (!_customApiCode.ContainsKey(message)) hits.Unresolved.Add(hit with { Reason = RequestReasons.CustomApiCode(message) }); + continue; + } + hits.Unresolved.Add(hit with { Reason = CustomApi(hit.Reason) }); + } + foreach (var hit in results.SelectMany(r => r.Globals)) + { + NamedPrivilegeHits(hit.Operation, hit.Privilege, hit.RunsAs, hit.Basis, hit.Source, hits); + } + if (customApi is { Trigger.Message: { } apiMessage, Declaration: { } declaration }) + { + ExecutePrivilegeHits(apiMessage, ExecutePrivilegeOf(apiMessage), RunsAs.Caller, new RequirementSource(declaration, []), hits); + } + return hits; + } + + /// + /// A request without a rule is a custom API call when the solution implements the message or registers steps on + /// it, or the message has a publisher prefix, as custom API and custom action names do. + /// + private string CustomApi(string reason) => + RequestReasons.NoRuleMessage(reason) is { } message && (_customApis.Contains(message) || message.IndexOf('_') > 0) + ? RequestReasons.CustomApi(message) + : reason; + + /// + /// The code or the privilege catalog has the custom API, so what calling it needs is known. + /// + private bool IsKnownCustomApi(string message) => _customApiCode.ContainsKey(message) || _catalogCustomApis.ContainsKey(message); + + /// + /// The execute privilege of a custom API: from its registration in code, else from the privilege catalog. + /// null when it needs none. + /// + private ExecutePrivilege? ExecutePrivilegeOf(string message) => + (_customApiCode.TryGetValue(message, out var code) ? code.ExecutePrivilege : null) + ?? (_catalogCustomApis.TryGetValue(message, out var api) && !string.IsNullOrEmpty(api.ExecutePrivilegeName) ? new ExecutePrivilege(api.ExecutePrivilegeName) : null); + + /// + /// What calling the custom API needs for : table + /// privileges, a privilege not tied to a table, or an unresolved operation when the privilege can't be looked up. + /// A privilege name is only looked up in the privilege catalog, never derived from its spelling. + /// + private void ExecutePrivilegeHits(string message, ExecutePrivilege? privilege, RunsAs runsAs, RequirementSource source, ResolvedHits hits) + { + if (privilege is null) return; + if (privilege is { Table: { } table, Privilege: { } tablePrivilege }) + { + hits.Requirements.Add(new RequirementHit(table, tablePrivilege, runsAs, RequirementBasis.ExecutePrivilege, source)); + return; + } + + void Unresolved(string reason) => hits.Unresolved.Add(new UnresolvedHit(message, [], reason, runsAs, source)); + if (privilege.Name is not { } name) Unresolved(RequestReasons.ExecutePrivilegeComputed(message)); + else if (_catalog is null) Unresolved(RequestReasons.PrivilegeCatalogMissing(message, name)); + else if (!_catalog.TryGetValue(name, out var definition)) Unresolved(RequestReasons.PrivilegeNotInCatalog(message, name)); + else if (!CatalogHits(definition, runsAs, RequirementBasis.ExecutePrivilege, source, hits)) Unresolved(RequestReasons.PrivilegeWithoutTablePrivilege(message, name)); + } + + /// + /// What needs for , a privilege its request rule names. + /// Without a privilege catalog it is taken as a privilege not tied to a table; with one, it is looked up there, + /// as it may be tied to tables instead. + /// + private void NamedPrivilegeHits(string operation, string privilege, RunsAs runsAs, RequirementBasis basis, RequirementSource source, ResolvedHits hits) + { + void Unresolved(string reason) => hits.Unresolved.Add(new UnresolvedHit(operation, [], reason, runsAs, source)); + if (_catalog is null) hits.Globals.Add(new GlobalHit(privilege, runsAs, basis, source)); + else if (!_catalog.TryGetValue(privilege, out var definition)) Unresolved(RequestReasons.NamedPrivilegeNotInCatalog(operation, privilege)); + else if (!CatalogHits(definition, runsAs, basis, source, hits)) Unresolved(RequestReasons.NamedPrivilegeWithoutTablePrivilege(operation, privilege)); + } + + /// + /// Adds what grants: a privilege not tied to a table, or its table privilege on each + /// of its tables. false when it is tied to tables but its access right isn't a table privilege, so no role + /// can be checked for it. + /// + private static bool CatalogHits(PrivilegeDefinition definition, RunsAs runsAs, RequirementBasis basis, RequirementSource source, ResolvedHits hits) + { + if (definition.Tables.Count == 0) + { + hits.Globals.Add(new GlobalHit(definition.Name, runsAs, basis, source)); + return true; + } + if (definition.Privilege is not { } granted) return false; + foreach (var table in definition.Tables) + { + hits.Requirements.Add(new RequirementHit(table.ToLowerInvariant(), granted, runsAs, basis, source)); + } + return true; + } +} + +/// +/// What evaluations need once has resolved them, in the order found. +/// +internal sealed class ResolvedHits +{ + public List Requirements { get; } = []; + public List Unresolved { get; } = []; + public List Assumptions { get; } = []; + public List Globals { get; } = []; + + /// + /// Set when an evaluation stopped at , so the hits may be incomplete. + /// + public bool Truncated { get; init; } +} + +/// +/// A privilege not tied to a table that an operation needs. +/// +internal sealed record GlobalHit(string Privilege, RunsAs RunsAs, RequirementBasis Basis, RequirementSource Source); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Discovery/EntryPointDiscovery.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Discovery/EntryPointDiscovery.cs new file mode 100644 index 00000000..5720f1a2 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Discovery/EntryPointDiscovery.cs @@ -0,0 +1,361 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Graph; +using XrmMockup.PermissionAnalyzer.Core.Model; +using static XrmMockup.PermissionAnalyzer.Core.Extraction.Operations; + +namespace XrmMockup.PermissionAnalyzer.Core.Discovery; + +/// +/// Finds where code starts running: plugin steps and custom APIs registered in plugin constructors +/// (XrmPluginCore and DAXIF style), plain IPlugin classes, workflow activities and Azure Functions. +/// +internal sealed class EntryPointDiscovery(Compilation compilation, XrmSymbols symbols, SourcePaths paths) +{ + private static readonly HashSet StepMethods = new(StringComparer.Ordinal) { "RegisterPluginStep", "RegisterStep" }; + private static readonly HashSet ApiMethods = new(StringComparer.Ordinal) { "RegisterCustomAPI", "RegisterAPI" }; + + /// + /// A message, stage or custom API name that is set at runtime. + /// + private const string Unknown = "?"; + + private static readonly IReadOnlyDictionary StageNames = new Dictionary + { + [10] = "PreValidation", + [20] = "PreOperation", + [30] = "MainOperation", + [40] = "PostOperation", + }; + + private static readonly string[] FunctionAttributes = + [ + "Microsoft.Azure.Functions.Worker.FunctionAttribute", + "Microsoft.Azure.WebJobs.FunctionNameAttribute", + ]; + + public List Entries { get; } = []; + + public List Plugins { get; } = []; + + public static string StageName(int stage) => StageNames.TryGetValue(stage, out var name) ? name : stage.ToString(); + + public EntryPointDiscovery Discover(CancellationToken cancellationToken = default) + { + var codeActivity = compilation.GetTypeByMetadataName("System.Activities.CodeActivity"); + foreach (var tree in compilation.SyntaxTrees) + { + var model = compilation.GetSemanticModel(tree); + foreach (var syntax in tree.GetRoot(cancellationToken).DescendantNodes()) + { + cancellationToken.ThrowIfCancellationRequested(); + switch (syntax) + { + case ClassDeclarationSyntax declaration when model.GetDeclaredSymbol(declaration, cancellationToken) is INamedTypeSymbol { IsAbstract: false } type + && IsFirstDeclaration(type, declaration): + if (XrmSymbols.Implements(type, symbols.Plugin)) Plugin(model, type); + if (codeActivity is not null && symbols.Is(type, codeActivity)) Activity(type); + break; + + case MethodDeclarationSyntax declaration when model.GetDeclaredSymbol(declaration, cancellationToken) is IMethodSymbol method: + Function(method); + break; + } + } + } + return this; + } + + private void Plugin(SemanticModel model, INamedTypeSymbol type) + { + var typeId = Nodes.TypeId(type); + var name = ReflectionName(type); + var steps = new List(); + + foreach (var constructor in type.InstanceConstructors) + { + foreach (var reference in constructor.DeclaringSyntaxReferences) + { + var syntax = reference.GetSyntax(); + var constructorModel = syntax.SyntaxTree == model.SyntaxTree ? model : compilation.GetSemanticModel(syntax.SyntaxTree); + if (constructorModel.GetOperation(syntax) is not { } body) continue; + + foreach (var invocation in body.DescendantsAndSelf().OfType()) + { + if (!XrmSymbols.Implements(invocation.TargetMethod.ContainingType, symbols.Plugin)) continue; + if (Registration(invocation, type, typeId, name) is { } step) steps.Add(step); + } + } + } + + Entries.AddRange(steps); + var execute = symbols.Plugin?.GetMembers(SdkNames.Execute).OfType().FirstOrDefault() is { } member + && type.FindImplementationForInterfaceMember(member) is IMethodSymbol implementation + && IsInSource(implementation) + ? Nodes.Id(implementation) + : null; + Plugins.Add(new PluginClass(name, compilation.AssemblyName, paths.Declaration(type), typeId, execute, steps.Count > 0)); + } + + /// + /// A RegisterPluginStep, RegisterStep, RegisterCustomAPI or RegisterAPI call in a + /// plugin constructor. + /// + private EntryCandidate? Registration(IInvocationOperation invocation, INamedTypeSymbol type, string typeId, string name) + { + var method = invocation.TargetMethod; + var isStep = StepMethods.Contains(method.Name); + if (!isStep && !ApiMethods.Contains(method.Name)) return null; + + var arguments = invocation.Arguments.Where(a => a.Parameter is not null).OrderBy(a => a.Parameter!.Ordinal).ToList(); + // The handler comes after a step's message and stage, and after an API's name + var handler = arguments.LastOrDefault(a => a.Parameter!.Type.TypeKind == TypeKind.Delegate || a.Parameter.Ordinal >= (isStep ? 2 : 1)); + var service = method.TypeArguments.Length == 2 ? method.TypeArguments[1] + : method.Name == "RegisterAPI" && method.TypeArguments.Length == 1 ? method.TypeArguments[0] + : null; + var handlers = Handlers(handler?.Value, typeId, service); + var declaration = paths.Of(invocation.Syntax.GetLocation()); + + if (!isStep) + { + var api = arguments.FirstOrDefault()?.Value.ConstantValue is { HasValue: true, Value: string apiName } ? apiName : Unknown; + return new EntryCandidate(EntryPointIds.CustomApi(api), EntryPointKind.CustomApi, name, compilation.AssemblyName, new Trigger(Message: api), null, declaration, handlers, ExecutePrivilegeOf(invocation)); + } + + var message = Name(arguments.ElementAtOrDefault(0)?.Value) ?? Unknown; + var stage = Name(arguments.ElementAtOrDefault(1)?.Value) ?? Unknown; + var table = method.TypeArguments.Length > 0 ? symbols.LogicalNameOf(method.TypeArguments[0]) : null; + var impersonation = UserContext(invocation); + var filter = Trigger.Filters(message) ? FilteredAttributes(invocation) : null; + + return new EntryCandidate( + EntryPointIds.PluginStep(name, message, table, stage), + EntryPointKind.PluginStep, + name, + compilation.AssemblyName, + new Trigger(message, table, stage, FilteredAttributes: filter, Asynchronous: IsAsynchronous(invocation)), + impersonation, + declaration, + handlers); + } + + /// + /// The code a registration runs: a lambda or method of the plugin, or a method of a service, by name or lambda. + /// + private static IReadOnlyList Handlers(IOperation? value, string pluginType, ITypeSymbol? service) + { + switch (Unwrap(value)) + { + case IDelegateCreationOperation { Target: IAnonymousFunctionOperation lambda }: + return [new Handler(Nodes.Id(lambda.Symbol), pluginType)]; + + case IDelegateCreationOperation { Target: IMethodReferenceOperation reference }: + return [new Handler(Nodes.Id(reference.Method), reference.Method.IsStatic ? null : pluginType)]; + + case { ConstantValue: { HasValue: true, Value: string methodName } } when service is INamedTypeSymbol serviceType: + // nameof(IAccountService.HandleUpdate): every overload, dispatched like a call on the service + return serviceType.GetMembers(methodName) + .Concat(serviceType.AllInterfaces.SelectMany(i => i.GetMembers(methodName))) + .OfType() + .Select(m => new Handler(Nodes.Id(m), null, Nodes.TypeId(serviceType))) + .Distinct() + .OrderBy(h => h.Target, StringComparer.Ordinal) + .ToList(); + + default: + return []; + } + } + + /// + /// .SetUserContext(userId) on the step configuration: the step runs as that user. + /// + private static string? UserContext(IInvocationOperation registration) => + Configuration(registration) + .Where(c => c.TargetMethod.Name == "SetUserContext" && c.Arguments.Length > 0) + .Select(c => GuidConstant(c.Arguments[0].Value)) + .FirstOrDefault(); + + /// + /// .WithExecutePrivilegeName("prvReadctx_Order"), .WithExecutePrivilege<T>(Privilege.Read) or + /// .WithExecutePrivilege("ctx_Order", Privilege.Read) on the custom API configuration; the last one wins. + /// The last two give the table privilege directly: a schema name is the logical name with another casing. + /// + private ExecutePrivilege? ExecutePrivilegeOf(IInvocationOperation registration) + { + ExecutePrivilege? found = null; + foreach (var call in Configuration(registration)) + { + var arguments = call.Arguments.Where(a => a.Parameter is not null).OrderBy(a => a.Parameter!.Ordinal).Select(a => Unwrap(a.Value)).ToList(); + switch (call.TargetMethod.Name) + { + case "WithExecutePrivilegeName" when arguments.Count == 1: + found = new ExecutePrivilege(arguments[0]?.ConstantValue is { HasValue: true, Value: string { Length: > 0 } privilege } ? privilege : null); + break; + + case "WithExecutePrivilege" when call.TargetMethod.TypeArguments.Length == 1 && arguments.Count == 1: + found = TablePrivilege(symbols.LogicalNameOf(call.TargetMethod.TypeArguments[0]), arguments[0]); + break; + + case "WithExecutePrivilege" when arguments.Count == 2: + var table = arguments[0]?.ConstantValue is { HasValue: true, Value: string { Length: > 0 } schemaName } ? schemaName.ToLowerInvariant() : null; + found = TablePrivilege(table, arguments[1]); + break; + } + } + return found; + } + + private static ExecutePrivilege TablePrivilege(string? table, IOperation? privilege) => + table is not null && Name(privilege) is { } name && Enum.TryParse(name, out var parsed) && Enum.IsDefined(typeof(Privilege), parsed) + ? new ExecutePrivilege(null, table, parsed) + : new ExecutePrivilege(null); + + /// + /// .AddFilteredAttributes(x => x.Name, …) or .AddFilteredAttributes("name", …) on the step + /// configuration, lowercased and sorted. null when there are none, or when one can't be read, so the step + /// is treated as running on every update. + /// + private IReadOnlyList? FilteredAttributes(IInvocationOperation registration) + { + var columns = new SortedSet(StringComparer.Ordinal); + foreach (var call in Configuration(registration).Where(c => c.TargetMethod.Name is "AddFilteredAttributes" or "AddFilteredAttribute")) + { + foreach (var argument in call.Arguments) + { + var values = argument.Value is IArrayCreationOperation { Initializer: { } initializer } ? initializer.ElementValues : [argument.Value]; + foreach (var value in values) + { + if (Column(value) is not { } column) return null; + columns.Add(column); + } + } + } + return columns.Count > 0 ? columns.ToList() : null; + } + + /// + /// .SetExecutionMode(ExecutionMode.Asynchronous) on the step configuration. A mode set at runtime is taken + /// as synchronous, the default. + /// + private static bool IsAsynchronous(IInvocationOperation registration) => + Configuration(registration) + .Where(c => c.TargetMethod.Name == "SetExecutionMode" && c.Arguments.Length > 0) + .Any(c => Unwrap(c.Arguments[0].Value) is var mode + && (mode is IFieldReferenceOperation { Field: { Name: "Asynchronous", ContainingType.TypeKind: TypeKind.Enum } } + || mode?.ConstantValue is { HasValue: true, Value: 1 })); // ExecutionMode.Asynchronous + + /// + /// The column a filtered attribute names: a constant, or the early-bound property a lambda selects. + /// + private string? Column(IOperation value) + { + var op = Unwrap(value); + if (op?.ConstantValue is { HasValue: true, Value: string { Length: > 0 } name }) return name.ToLowerInvariant(); + + while (op is IDelegateCreationOperation delegateCreation) op = Unwrap(delegateCreation.Target); + if (op is IAnonymousFunctionOperation lambda) + { + var returned = lambda.Body.Operations.OfType().FirstOrDefault()?.ReturnedValue; + if (Unwrap(returned) is IPropertyReferenceOperation property) return symbols.AttributeNameOf(property.Property)?.ToLowerInvariant(); + } + return null; + } + + /// + /// The calls chained on a step registration to configure it, such as .AddImage(…).SetUserContext(…). + /// + private static IEnumerable Configuration(IInvocationOperation registration) + { + IOperation current = registration; + while (current.Parent is { } parent) + { + if (parent is IConversionOperation) + { + current = parent; + continue; + } + if (parent is not IInvocationOperation call || !ReferenceEquals(call.Instance, current)) yield break; + yield return call; + current = call; + } + } + + private void Activity(INamedTypeSymbol type) + { + for (var current = type; current is not null; current = current.BaseType) + { + var execute = current.GetMembers(SdkNames.Execute).OfType() + .FirstOrDefault(m => m.IsOverride && m.Parameters.Length == 1 && IsInSource(m)); + if (execute is null) continue; + + var name = ReflectionName(type); + Entries.Add(new EntryCandidate( + EntryPointIds.Activity(name), + EntryPointKind.CodeActivity, + name, + compilation.AssemblyName, + null, + null, + paths.Declaration(type), + [new Handler(Nodes.Id(execute), Nodes.TypeId(type))])); + return; + } + } + + private void Function(IMethodSymbol method) + { + var attribute = method.GetAttributes().FirstOrDefault(a => a.AttributeClass is { } c && FunctionAttributes.Contains(c.ToDisplayString())); + if (attribute is null || attribute.ConstructorArguments.FirstOrDefault().Value is not string name) return; + + var binding = method.Parameters + .SelectMany(p => p.GetAttributes()) + .Select(a => a.AttributeClass?.Name) + .FirstOrDefault(n => n is not null && n.EndsWith("TriggerAttribute", StringComparison.Ordinal)); + if (binding is not null) binding = binding.Substring(0, binding.Length - "Attribute".Length); + + Entries.Add(new EntryCandidate( + EntryPointIds.Function(compilation.AssemblyName, name), + EntryPointKind.Function, + ReflectionName(method.ContainingType), + compilation.AssemblyName, + new Trigger(Binding: binding), + null, + paths.Declaration(method), + [new Handler(Nodes.Id(method), method.IsStatic ? null : Nodes.TypeId(method.ContainingType))])); + } + + /// + /// The name of an enum value or a string constant, such as EventOperation.Update or "Update". + /// + private static string? Name(IOperation? operation) + { + var op = Unwrap(operation); + if (op is IFieldReferenceOperation { Field.ContainingType.TypeKind: TypeKind.Enum } field) return field.Field.Name; + if (op?.ConstantValue is { HasValue: true, Value: string text }) return text; + if (op?.ConstantValue is { HasValue: true, Value: int stage }) return StageName(stage); + return null; + } + + /// + /// The name a type has at runtime, such as Contoso.Plugins.Outer+Inner, which plugin metadata uses. + /// + public static string ReflectionName(INamedTypeSymbol type) + { + var name = type.MetadataName; + for (var outer = type.ContainingType; outer is not null; outer = outer.ContainingType) + { + name = outer.MetadataName + "+" + name; + } + var ns = type.ContainingNamespace; + return ns is null || ns.IsGlobalNamespace ? name : ns.ToDisplayString() + "." + name; + } + + /// + /// A partial class is looked at once, from its first declaration. + /// + private static bool IsFirstDeclaration(INamedTypeSymbol type, SyntaxNode declaration) => + type.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() == declaration; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/LookupColumns.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/LookupColumns.cs new file mode 100644 index 00000000..1e5534be --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/LookupColumns.cs @@ -0,0 +1,30 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// The tables each lookup column can refer to, from the metadata. Table and column names are matched ignoring case. +/// +internal sealed class LookupColumns +{ + private readonly Dictionary> _targets = new(StringComparer.OrdinalIgnoreCase); + + public LookupColumns(IEnumerable? columns = null) + { + foreach (var column in columns ?? []) + { + var key = Key(column.Table, column.Column); + if (!_targets.TryGetValue(key, out var targets)) _targets[key] = targets = new SortedSet(StringComparer.Ordinal); + targets.UnionWith(column.Targets.Where(t => t.Length > 0).Select(t => t.ToLowerInvariant())); + } + } + + /// + /// The tables on can refer to; empty when the metadata + /// doesn't know the column. + /// + public IReadOnlyCollection TargetsOf(string table, string column) => + _targets.TryGetValue(Key(table, column), out var targets) ? targets : []; + + private static string Key(string table, string column) => table + "\n" + column; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/Nodes.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/Nodes.cs new file mode 100644 index 00000000..3790113f --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/Nodes.cs @@ -0,0 +1,159 @@ +using System.Runtime.CompilerServices; +using Microsoft.CodeAnalysis; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// Ids and display names of call graph nodes: members, plus the lambdas and local functions inside them, +/// which are nodes of their own so a lambda can be a plugin step handler. +/// +internal static class Nodes +{ + private static readonly SymbolDisplayFormat TypeFormat = new( + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); + + // Parameter types with their namespaces, for overloads that only differ in those + private static readonly SymbolDisplayFormat QualifiedParameterFormat = new( + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, + miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays); + + private static readonly SymbolDisplayFormat ShortTypeFormat = new( + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, + genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); + + // Display strings are slow and the same members and types are named at every call to them + private static readonly ConditionalWeakTable MemberIds = new(); + private static readonly ConditionalWeakTable TypeIds = new(); + + /// + /// A stable id such as Contoso.Plugins.AccountPlugin.Execute(IServiceProvider), with the type parameters + /// of a generic method (Load<T>(IOrganizationService)), and with namespaces on the parameter types + /// when another overload would have the same id without them. A lambda adds its position to the id of the + /// member that contains it: Contoso.Plugins.AccountPlugin..ctor()=>12:9. + /// + public static string Id(ISymbol symbol) + { + symbol = Definition(symbol); + if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } lambda) + { + return $"{Id(lambda.ContainingSymbol)}=>{Position(lambda)}"; + } + if (symbol is IMethodSymbol { MethodKind: MethodKind.LocalFunction } local) + { + return $"{Id(local.ContainingSymbol)}.{local.Name}@{Position(local)}"; + } + return MemberId(symbol); + } + + /// + /// The member a node belongs to: the node itself, or the member that declares the lambda or local function. + /// + public static ISymbol? Member(ISymbol? symbol) + { + while (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction or MethodKind.LocalFunction }) + { + symbol = symbol.ContainingSymbol; + } + return symbol?.ContainingType is null ? null : Definition(symbol); + } + + /// + /// A short name for call paths, such as AccountPlugin.Execute. + /// + public static string Display(ISymbol symbol) + { + symbol = Definition(symbol); + if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } lambda) + { + return $"{Display(lambda.ContainingSymbol)} (lambda, line {Line(lambda)})"; + } + if (symbol is IMethodSymbol { MethodKind: MethodKind.LocalFunction } local) + { + return $"{Display(local.ContainingSymbol)}.{local.Name}"; + } + + var type = symbol.ContainingType?.ToDisplayString(ShortTypeFormat) ?? ""; + var name = symbol is IMethodSymbol method + ? method.MethodKind switch + { + MethodKind.Constructor => "ctor", + MethodKind.StaticConstructor => "cctor", + MethodKind.PropertyGet or MethodKind.PropertySet => method.AssociatedSymbol?.Name ?? method.Name, + _ => method.Name, + } + : symbol.Name; + return $"{type}.{name}"; + } + + public static string TypeId(ITypeSymbol type) => TypeIds.GetValue(type.OriginalDefinition, definition => definition.ToDisplayString(TypeFormat)); + + /// + /// The type parameters of as declared, after those of the types it is nested in. + /// + public static List TypeParameters(INamedTypeSymbol type) => + TypeArguments(type.OriginalDefinition).Cast().ToList(); + + /// + /// The type arguments of , in the order of . + /// + public static List TypeArguments(INamedTypeSymbol type) + { + var result = type.ContainingType is { } outer ? TypeArguments(outer) : []; + result.AddRange(type.TypeArguments); + return result; + } + + /// + /// The symbol as declared: generic methods and members of generic types are not constructed, an extension + /// method is not reduced and a partial method is its definition. + /// + public static ISymbol Definition(ISymbol symbol) + { + if (symbol is IMethodSymbol method) + { + method = method.ReducedFrom ?? method; + method = method.OriginalDefinition; + return method.PartialDefinitionPart ?? method; + } + return symbol.OriginalDefinition; + } + + private static string MemberId(ISymbol member) => MemberIds.GetValue(member, NewMemberId); + + private static string NewMemberId(ISymbol member) + { + var type = member.ContainingType.ToDisplayString(TypeFormat); + if (member is not IMethodSymbol method) return $"{type}.{member.Name}"; + + var name = method.MethodKind switch + { + MethodKind.Constructor => ".ctor", + MethodKind.StaticConstructor => ".cctor", + _ => method.Name, + }; + if (method.TypeParameters.Length > 0) name += $"<{string.Join(", ", method.TypeParameters.Select(t => t.Name))}>"; + + var parameters = Parameters(method, SymbolDisplayFormat.MinimallyQualifiedFormat); + var clashes = method.ContainingType.GetMembers(method.Name) + .OfType() + .Any(other => !SymbolEqualityComparer.Default.Equals(other, method) + && other.TypeParameters.Length == method.TypeParameters.Length + && Parameters(other, SymbolDisplayFormat.MinimallyQualifiedFormat) == parameters); + if (clashes) parameters = Parameters(method, QualifiedParameterFormat); + return $"{type}.{name}({parameters})"; + } + + private static string Parameters(IMethodSymbol method, SymbolDisplayFormat format) => + string.Join(", ", method.Parameters.Select(p => + (p.RefKind == RefKind.None ? "" : p.RefKind.ToString().ToLowerInvariant() + " ") + p.Type.ToDisplayString(format))); + + private static string Position(ISymbol symbol) + { + var span = symbol.Locations.FirstOrDefault()?.GetLineSpan().StartLinePosition ?? default; + return $"{span.Line + 1}:{span.Character + 1}"; + } + + private static int Line(ISymbol symbol) => (symbol.Locations.FirstOrDefault()?.GetLineSpan().StartLinePosition.Line ?? 0) + 1; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/Operations.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/Operations.cs new file mode 100644 index 00000000..b25c9e06 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/Operations.cs @@ -0,0 +1,142 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Operations; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// Reads Roslyn operations the same way for table resolution, method summaries and entry point discovery. +/// +internal static class Operations +{ + /// + /// The value under conversions, arguments, parentheses and out var declarations. + /// + public static IOperation? Unwrap(IOperation? operation) + { + while (UnwrapOnce(operation) is { } inner) operation = inner; + return operation; + } + + public static IOperation? UnwrapOnce(IOperation? operation) => operation switch + { + IConversionOperation conversion => conversion.Operand, + IArgumentOperation argument => argument.Value, + IParenthesizedOperation parenthesized => parenthesized.Operand, + IDeclarationExpressionOperation declaration => declaration.Expression, + _ => null, + }; + + /// + /// The body an operation is part of. + /// + public static IOperation Root(IOperation operation) + { + while (operation.Parent is not null) operation = operation.Parent; + return operation; + } + + public static bool IsLocal(IOperation? operation, ILocalSymbol local) => + Unwrap(operation) is ILocalReferenceOperation reference && SymbolEqualityComparer.Default.Equals(reference.Local, local); + + public static bool IsParameter(IOperation? operation, IParameterSymbol parameter) => + Unwrap(operation) is IParameterReferenceOperation reference && SymbolEqualityComparer.Default.Equals(reference.Parameter, parameter); + + public static bool IsInSource(ISymbol? symbol) => symbol?.Locations.Any(l => l.IsInSource) == true; + + /// + /// A call into the .NET libraries, such as LINQ, whose results come from its arguments. + /// + public static bool IsSystemCall(IInvocationOperation invocation) => + !IsInSource(invocation.TargetMethod) + && invocation.TargetMethod.ContainingNamespace?.ToDisplayString() is { } name + && (name == "System" || name.StartsWith("System.", StringComparison.Ordinal)); + + /// + /// A type of the .NET libraries or the SDK, under the System or Microsoft namespaces, whose + /// virtual methods the solution doesn't implement. + /// + public static bool IsFrameworkType(INamedTypeSymbol? type) + { + var root = type?.ContainingNamespace; + while (root is { ContainingNamespace.IsGlobalNamespace: false }) root = root.ContainingNamespace; + return root?.Name is "System" or "Microsoft"; + } + + /// + /// The value passed for the parameter at , whatever order the arguments are written in. + /// + public static IOperation? Argument(IInvocationOperation invocation, int ordinal) => + invocation.Arguments.FirstOrDefault(a => a.Parameter?.Ordinal == ordinal)?.Value; + + /// + /// A user id written in code: new Guid("…") or Guid.Parse("…"). + /// + public static string? GuidConstant(IOperation operation) + { + var arguments = operation switch + { + IObjectCreationOperation creation when creation.Type?.ToDisplayString() == "System.Guid" => creation.Arguments, + IInvocationOperation { TargetMethod.Name: "Parse" } invocation when invocation.TargetMethod.ContainingType.ToDisplayString() == "System.Guid" => invocation.Arguments, + _ => default, + }; + return !arguments.IsDefaultOrEmpty + && arguments[0].Value.ConstantValue is { HasValue: true, Value: string text } + && Guid.TryParse(text, out var id) + ? id.ToString("D") + : null; + } + + /// + /// Every value assigned to in . For a foreach variable + /// that's the collection it iterates. is told why an assignment can't be followed. + /// + public static List LocalValues(ILocalSymbol local, IOperation root, Action? failed) + { + var values = new List(); + foreach (var node in root.DescendantsAndSelf()) + { + switch (node) + { + case IVariableDeclaratorOperation declarator when SymbolEqualityComparer.Default.Equals(declarator.Symbol, local): + if (declarator.GetVariableInitializer() is { } initializer) values.Add(new LocalValue(initializer.Value, false)); + break; + + case ISimpleAssignmentOperation assignment when IsLocal(assignment.Target, local): + values.Add(new LocalValue(assignment.Value, false)); + break; + + case ICoalesceAssignmentOperation coalesce when IsLocal(coalesce.Target, local): + values.Add(new LocalValue(coalesce.Value, false)); + break; + + case ICompoundAssignmentOperation compound when IsLocal(compound.Target, local): + failed?.Invoke($"local '{local.Name}' is changed by a compound assignment"); + break; + + case IArgumentOperation { Parameter.RefKind: RefKind.Ref or RefKind.Out } argument when IsLocal(argument.Value, local): + failed?.Invoke($"local '{local.Name}' is passed by ref or out"); + break; + + case IForEachLoopOperation loop when loop.Locals.Contains(local, SymbolEqualityComparer.Default): + values.Add(new LocalValue(loop.Collection, true)); + break; + + case IDeclarationPatternOperation pattern when SymbolEqualityComparer.Default.Equals(pattern.DeclaredSymbol, local): + failed?.Invoke($"local '{local.Name}' is declared by a pattern"); + break; + + case IDeconstructionAssignmentOperation deconstruction when deconstruction.Target.DescendantsAndSelf().Any(t => IsLocal(t, local)): + failed?.Invoke($"local '{local.Name}' is assigned by deconstruction"); + break; + } + } + return values; + } + + /// + /// Why a foreach variable is unknown where its elements aren't followed. + /// + public static string LoopVariable(ILocalSymbol local) => $"local '{local.Name}' is a loop variable"; + + public readonly record struct LocalValue(IOperation Operation, bool IsLoopCollection); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/RequestRules.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/RequestRules.cs new file mode 100644 index 00000000..7ea7dff1 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/RequestRules.cs @@ -0,0 +1,226 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// The rules for the requests passed to Execute: the built-in ones, which follow Dataverse, replaced or +/// extended by configured ones. A rule names its message as is or as its request type, such as AssignRequest; +/// a message is matched to a rule by its name first, ignoring case. +/// +internal sealed class RequestRules +{ + /// + /// The rules for the SDK requests, as Dataverse checks them. is false + /// where XrmMockup's handler doesn't make the checks. + /// + public static IReadOnlyList BuiltIn { get; } = + [ + Rule(Messages.Create, On(SdkNames.Target, Privilege.Create)), + Rule(Messages.Update, On(SdkNames.Target, Privilege.Write)), + Rule(Messages.Delete, On(SdkNames.Target, Privilege.Delete)), + Rule(Messages.Retrieve, On(SdkNames.Target, Privilege.Read)), + Rule(Messages.RetrieveMultiple, On(SdkNames.Query, Privilege.Read)), + Rule(Messages.Associate, On(SdkNames.Target, Privilege.Read, Privilege.AppendTo), On("RelatedEntities", Privilege.Read, Privilege.Append)), + Rule(Messages.Disassociate, On(SdkNames.Target, Privilege.Read, Privilege.AppendTo), On("RelatedEntities", Privilege.Read, Privilege.Append)), + new(Messages.Upsert) { As = [Messages.Create, Messages.Update] }, + new("CreateMultiple") { Targets = "Targets", As = [Messages.Create] }, + new("UpdateMultiple") { Targets = "Targets", As = [Messages.Update] }, + new("UpsertMultiple") { Targets = "Targets", As = [Messages.Upsert] }, + new("DeleteMultiple") { Targets = "Targets", As = [Messages.Delete] }, + new("ExecuteMultiple") { Requests = "Requests" }, + new("ExecuteTransaction") { Requests = "Requests" }, + Rule("SetState", On("EntityMoniker", Privilege.Write)) with { Enforced = false }, + Rule("Assign", On(SdkNames.Target, Privilege.Assign, Privilege.Write)), + Rule("GrantAccess", On(SdkNames.Target, Privilege.Share) with { AccessMask = "PrincipalAccess.AccessMask" }), + Rule("ModifyAccess", On(SdkNames.Target, Privilege.Share) with { AccessMask = "PrincipalAccess.AccessMask" }), + Rule("RevokeAccess", On(SdkNames.Target, Privilege.Share)), + Rule("Merge", On(SdkNames.Target, Privilege.Read, Privilege.Write)) with { GlobalPrivileges = ["prvMerge"] }, + Rule( + "QualifyLead", + On("LeadId", Privilege.Write), + OnTable("account", Privilege.Create) with { When = "CreateAccount" }, + OnTable("contact", Privilege.Create) with { When = "CreateContact" }, + OnTable("opportunity", Privilege.Create) with { When = "CreateOpportunity" }), + Rule("SendEmail", OnTable("email", Privilege.Read, Privilege.Write)) with + { + Assumption = "SendEmail sends the email as the calling user; sending it as another user needs prvSendAsUser", + }, + // Closing a record creates its close activity, but the steps fire on the record, and for opportunities and + // quotes on the Win or Lose message, as in XrmMockup + Rule("CloseIncident", On("IncidentResolution", Privilege.Create), OnTable("incident", Privilege.Write)) with { FiresOn = "incident" }, + Rule("WinOpportunity", On("OpportunityClose", Privilege.Create), OnTable("opportunity", Privilege.Write)) with { FiresOn = "opportunity", StepMessage = "Win" }, + Rule("LoseOpportunity", On("OpportunityClose", Privilege.Create), OnTable("opportunity", Privilege.Write)) with { FiresOn = "opportunity", StepMessage = "Lose" }, + Rule("WinQuote", On("QuoteClose", Privilege.Create), OnTable("quote", Privilege.Write)) with { FiresOn = "quote", StepMessage = "Win" }, + Rule("CloseQuote", On("QuoteClose", Privilege.Create), OnTable("quote", Privilege.Write)) with { FiresOn = "quote", StepMessage = "Lose" }, + Rule("ReviseQuote", OnTable("quote", Privilege.Read, Privilege.Create)), + Rule("InitializeFileBlocksUpload", On(SdkNames.Target, Privilege.Write)) with { Enforced = false }, + Rule("InitializeFileBlocksDownload", On(SdkNames.Target, Privilege.Read)) with { Enforced = false }, + + // Block transfers continue one that was initialized, and checked, above + new("UploadBlock"), + new("CommitFileBlocksUpload"), + new("DownloadBlock"), + + // Privileges not tied to a table + Global("BulkDelete", "prvBulkDelete"), + Global("ImportSolution", "prvImportCustomization"), + Global("ImportSolutionAsync", "prvImportCustomization"), + Global("ExportSolution", "prvExportCustomization"), + Global("ExportSolutionAsync", "prvExportCustomization"), + Global("PublishXml", "prvPublishCustomization"), + Global("PublishAllXml", "prvPublishCustomization"), + Global("ExecuteWorkflow", "prvWorkflowExecution"), + Global("DeleteRecordChangeHistory", "prvDeleteRecordChangeHistory"), + Global("DeleteAuditData", "prvDeleteAuditPartitions"), + Global("RetrieveAuditDetails", "prvReadRecordAuditHistory", "prvReadAuditSummary"), + Global("RetrieveAttributeChangeHistory", "prvReadRecordAuditHistory", "prvReadAuditSummary"), + Global("RetrieveRecordChangeHistory", "prvReadRecordAuditHistory", "prvReadAuditSummary"), + + // Metadata and organization information, readable by every user + new("RetrieveEntity"), + new("RetrieveAttribute"), + new("RetrieveAllEntities"), + new("RetrieveAllOptionSets"), + new("RetrieveOptionSet"), + new("RetrieveRelationship"), + new("RetrieveMetadataChanges"), + new("WhoAmI"), + new("RetrieveVersion"), + new("FetchXmlToQueryExpression"), + new("QueryExpressionToFetchXml"), + new("RetrieveCurrentOrganization"), + new("RetrieveExchangeRate"), + new("IsValidStateTransition"), + new("RetrievePrincipalAccess"), + ]; + + private const string RequestSuffix = "Request"; + + private readonly Dictionary _builtIn = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _configured = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _expanded = new(StringComparer.OrdinalIgnoreCase); + + /// Rules that replace the built-in rule for their message, or add one. + public RequestRules(IEnumerable? rules = null) + { + foreach (var rule in BuiltIn) _builtIn[rule.Message] = rule; + foreach (var rule in rules ?? []) _configured[rule.Message] = rule; + } + + /// + /// The message of a request type: AssignRequest is Assign. Only a type name has the suffix to + /// remove; a message such as contoso_ApprovalRequest is called by its name. + /// + public static string MessageOfType(string typeName) => + typeName.Length > RequestSuffix.Length && typeName.EndsWith(RequestSuffix, StringComparison.Ordinal) + ? typeName.Substring(0, typeName.Length - RequestSuffix.Length) + : typeName; + + /// + /// The message a person names in a rule's or with --operation: the name, or + /// when only the request type has a rule, its message, so CreateRequest is Create. + /// + public string MessageNamed(string name) => + RuleOf(name) is null && MessageOfType(name) is var message && message != name && RuleOf(message) is not null ? message : name; + + /// + /// The checks of with those of its messages, or + /// null when there is no rule for it. + /// + public ExpandedRule? Find(string message) => Expand(message, new HashSet(StringComparer.OrdinalIgnoreCase)); + + /// + /// The rule for , named as the message or its request type; a configured rule goes + /// before the built-in one. + /// + private RequestRule? RuleOf(string message) + { + foreach (var rules in new[] { _configured, _builtIn }) + { + if (rules.TryGetValue(message, out var rule) || rules.TryGetValue(message + RequestSuffix, out rule)) return rule; + } + return null; + } + + private ExpandedRule? Expand(string message, HashSet visiting) + { + if (_expanded.TryGetValue(message, out var known)) return known; + if (RuleOf(message) is not { } rule) return null; + + // A rule that is, through others, its own as-rule adds nothing more + if (!visiting.Add(message)) return new ExpandedRule([], [], [], [], [], []); + + var checks = new List(rule.Checks); + var globals = new List(rule.GlobalPrivileges); + var assumptions = new List(); + if (rule.Assumption is { } assumption) assumptions.Add(assumption); + var requests = new List(); + var missing = new List(); + var messages = new List { rule.StepMessage ?? message }; + var firesOn = rule.FiresOn; + if (rule.Requests is { } nested) requests.Add(nested); + foreach (var other in rule.As.Select(MessageNamed)) + { + if (Expand(other, visiting) is not { } expanded) + { + missing.Add(other); + messages.Add(other); + continue; + } + messages.AddRange(expanded.Messages); + checks.AddRange(rule.Targets is { } targets ? expanded.Checks.Select(c => c.Member == SdkNames.Target ? c with { Member = targets } : c) : expanded.Checks); + requests.AddRange(expanded.Requests); + missing.AddRange(expanded.Missing); + globals.AddRange(expanded.GlobalPrivileges); + assumptions.AddRange(expanded.Assumptions); + firesOn ??= expanded.FiresOn; + } + visiting.Remove(message); + + var result = new ExpandedRule( + checks, + requests.Distinct(StringComparer.Ordinal).ToList(), + missing.Distinct(StringComparer.Ordinal).ToList(), + messages.Distinct(StringComparer.OrdinalIgnoreCase).ToList(), + globals.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(g => g, StringComparer.Ordinal).ToList(), + assumptions.Distinct(StringComparer.Ordinal).OrderBy(a => a, StringComparer.Ordinal).ToList(), + firesOn?.ToLowerInvariant()); + // A rule expanded inside a cycle misses the part of the cycle above it, so only complete ones are kept + if (visiting.Count == 0) _expanded[message] = result; + return result; + } + + private static RequestRule Rule(string message, params RuleCheck[] checks) => new(message) { Checks = checks }; + + private static RequestRule Global(string message, params string[] privileges) => new(message) { GlobalPrivileges = privileges }; + + private static RuleCheck On(string member, params Privilege[] privileges) => new(privileges) { Member = member }; + + private static RuleCheck OnTable(string table, params Privilege[] privileges) => new(privileges) { Table = table }; +} + +/// +/// A rule with the checks of its as-rules included. +/// +/// Every check the request makes. +/// The members that hold requests run as part of this one. +/// As-messages that have no rule. +/// +/// The messages the request fires plugin steps for: its own, or its , and its +/// as-messages, as Dataverse runs the steps of Create and Update for Upsert. +/// +/// The privileges the request needs by name, sorted. +/// What the analysis assumes about the request, sorted. +/// The table the request's plugin steps fire on, when the rule or an as-rule names one. +internal sealed record ExpandedRule( + IReadOnlyList Checks, + IReadOnlyList Requests, + IReadOnlyList Missing, + IReadOnlyList Messages, + IReadOnlyList GlobalPrivileges, + IReadOnlyList Assumptions, + string? FiresOn = null); + +/// +/// The reasons a request isn't checked, built and recognized in one place, so the coverage summary can count them. +/// diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/RuleApplication.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/RuleApplication.cs new file mode 100644 index 00000000..b11d317e --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/RuleApplication.cs @@ -0,0 +1,139 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// The members of a request a rule reads: those set where the request is created in code, or those of an +/// operation a user makes, given with --operation. +/// +internal interface IRequestMembers +{ + /// + /// The tables a member refers to, such as the table of Target. + /// + TableResolution Tables(string message, string member); + + /// + /// The columns set on the entity a member holds, such as the Target of an UpdateRequest; + /// null when they aren't known. + /// + TableResolution? Columns(string member); + + /// + /// Whether a boolean member may be set, so a check that depends on it applies. + /// + bool MayBeSet(string member); + + /// + /// The privileges of the access rights in the member at , such as + /// PrincipalAccess.AccessMask, and in why some of them aren't known. + /// + IReadOnlyList Rights(string path, out TableResolution reasons); + + /// + /// The tables of the lookups set on the entity a member holds, read as + /// or . + /// + TableResolution Lookups(string member, TableShape shape); + + /// + /// What the requests a member holds need, read as . + /// + TableResolution Requests(string member, TableShape shape); + + /// + /// The privileges the bypass parameters of the request need, and in the plugin steps + /// they certainly skip. + /// + TableResolution Bypass(string message, out PluginBypass bypass); +} + +/// +/// Reads a request by its rule, in one way for requests in code and operations users make. +/// +internal static class RuleApplication +{ + /// + /// The tables needs the privilege of on. The privileges a + /// request needs by name, its assumptions and the steps it fires go with , + /// so they are added once. + /// + public static TableResolution Apply(string message, ExpandedRule rule, IRequestMembers members, TableShape shape) + { + var result = new List(); + foreach (var missing in rule.Missing) result.Add(RequestShapes.Other(shape, RequestReasons.NoRule(missing))); + foreach (var nested in rule.Requests) result.Add(members.Requests(nested, shape)); + if (shape == TableShape.RequestOther) + { + foreach (var global in rule.GlobalPrivileges) result.Add(TableResolution.Global(global, message)); + foreach (var assumption in rule.Assumptions) result.Add(TableResolution.Assumed(assumption)); + result.Add(members.Bypass(message, out var bypass)); + result.Add(Fired(message, rule, members, bypass)); + } + + var privilege = RequestShapes.PrivilegeOf(shape); + foreach (var check in rule.Checks) + { + if (check.When is { } when && !members.MayBeSet(when)) continue; + + var needed = privilege is { } p && check.Privileges.Contains(p); + if (check.AccessMask is { } mask) + { + var rights = members.Rights(mask, out var reasons); + if (shape == TableShape.RequestOther) result.Add(reasons); + needed |= privilege is { } granted && rights.Contains(granted); + } + // A request that writes an entity, such as Create or Update, sets its lookups too + if (shape is TableShape.RequestAppend or TableShape.RequestAppendTo && check.Member is { } written + && (check.Privileges.Contains(Privilege.Create) || check.Privileges.Contains(Privilege.Write))) + { + result.Add(members.Lookups(written, shape == TableShape.RequestAppend ? TableShape.LookupHolder : TableShape.LookupTarget)); + } + + if (!needed) continue; + + if (check.Table is { } table) + { + result.Add(TableResolution.Table(table)); + } + else if (check.Member is { } member) + { + result.Add(members.Tables(message, member)); + } + } + return TableResolution.Union(result); + } + + /// + /// The member a request's plugin steps fire on: that of its first check on a member, usually Target. + /// null when the rule names the table they fire on (). + /// + public static string? PrimaryMember(ExpandedRule rule) => + rule.FiresOn is null ? rule.Checks.FirstOrDefault(c => c.Member is not null)?.Member : null; + + /// + /// The plugin steps a request fires: those of each of its messages, on the table the rule names, or else that + /// of its , or else of its first check on a fixed table. A request whose checks name + /// no table fires on no table. + /// + private static TableResolution Fired(string message, ExpandedRule rule, IRequestMembers members, PluginBypass bypass) + { + var tables = TableResolution.Empty; + TableResolution? columns = null; + if (rule.FiresOn is { } firesOn) + { + tables = TableResolution.Table(firesOn); + } + else if (PrimaryMember(rule) is { } member) + { + tables = members.Tables(message, member); + columns = members.Columns(member); + } + else if (rule.Checks.FirstOrDefault(c => c.Table is not null)?.Table is { } table) + { + tables = TableResolution.Table(table); + } + + return TableResolution.Union(rule.Messages.Select(fired => TableResolution.Fires(fired, tables, columns, bypass))); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/SdkNames.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/SdkNames.cs new file mode 100644 index 00000000..c17de6f6 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/SdkNames.cs @@ -0,0 +1,38 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// The names of the Dataverse SDK members the analysis reads in code. +/// +internal static class SdkNames +{ + // Entity, EntityReference and EntityCollection + public const string LogicalName = "LogicalName"; + public const string Attributes = "Attributes"; + public const string ToEntity = "ToEntity"; + public const string ToEntityReference = "ToEntityReference"; + public const string EntityName = "EntityName"; + public const string Entities = "Entities"; + + // Queries + public const string Query = "Query"; + public const string AddLink = "AddLink"; + public const string LinkEntities = "LinkEntities"; + + // Requests + public const string Target = "Target"; + public const string RequestName = "RequestName"; + public const string Parameters = "Parameters"; + + // Plugin execution context and service clients + public const string PrimaryEntityName = "PrimaryEntityName"; + public const string UserId = "UserId"; + public const string InitiatingUserId = "InitiatingUserId"; + public const string CallerId = "CallerId"; + public const string CallerAADObjectId = "CallerAADObjectId"; + public const string CreateOrganizationService = "CreateOrganizationService"; + + /// + /// IPlugin.Execute and CodeActivity.Execute. + /// + public const string Execute = "Execute"; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/SourcePaths.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/SourcePaths.cs new file mode 100644 index 00000000..ca7a78f4 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/SourcePaths.cs @@ -0,0 +1,59 @@ +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// Turns Roslyn locations into s relative to the analysis root. +/// +internal sealed class SourcePaths +{ + private static readonly StringComparison PathComparison = + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + private readonly string _root; + private readonly ConcurrentDictionary _relative = new(StringComparer.Ordinal); + + public SourcePaths(string rootDirectory) + { + var root = Path.GetFullPath(rootDirectory); + _root = root.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) ? root : root + Path.DirectorySeparatorChar; + } + + public SourceLocation Of(Location location) + { + var span = location.GetLineSpan(); + return new SourceLocation(Relative(span.Path), span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1); + } + + /// + /// Where a symbol is declared in source; null for a symbol from a referenced assembly. + /// + public SourceLocation? Declaration(ISymbol symbol) => + symbol.Locations.FirstOrDefault(l => l.IsInSource) is { } location ? Of(location) : null; + + /// + /// The path relative to the root, with ../ for a file outside it, such as plugin code in a solution next to + /// the analyzed one. A file on another drive keeps its full path. + /// + private string Relative(string path) => _relative.GetOrAdd(path ?? "", NewRelative); + + private string NewRelative(string path) + { + if (string.IsNullOrEmpty(path)) return ""; + + var full = Path.GetFullPath(path); + if (full.StartsWith(_root, PathComparison)) return full.Substring(_root.Length).Replace('\\', '/'); + + var separators = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; + var rootParts = _root.TrimEnd(separators).Split(separators); + var parts = full.Split(separators); + var common = 0; + while (common < rootParts.Length && common < parts.Length - 1 && string.Equals(rootParts[common], parts[common], PathComparison)) common++; + + if (common == 0) return full.Replace('\\', '/'); + return string.Concat(Enumerable.Repeat("../", rootParts.Length - common)) + string.Join("/", parts.Skip(common)); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/TableResolution.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/TableResolution.cs new file mode 100644 index 00000000..02baba8a --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/TableResolution.cs @@ -0,0 +1,442 @@ +using XrmMockup.PermissionAnalyzer.Core.Graph; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// The tables a value can refer to. A value can resolve partly: flag ? "account" : name resolves to +/// account plus a reason for the parameter. An empty resolution carries no information yet, such as +/// new Entity() before its LogicalName is set. +/// +/// +/// A value that comes from a method parameter is kept as a , so the call graph can fill +/// it in from the argument at each call site. Where no call site binds it, the slot's reason is reported. A value +/// returned by a method in the solution is kept as a , resolved from the method's +/// return values in the context of the call. The plugin steps an operation fires are kept per message in +/// , with the tables they fire on, bound the same way. +/// A resolution doesn't change once made, so resolutions can be shared; +/// makes a new one. +/// +internal sealed class TableResolution +{ + private readonly SortedSet _tables = new(StringComparer.Ordinal); + private readonly SortedSet _reasons = new(StringComparer.Ordinal); + private readonly SortedSet _lookupTargets = new(StringComparer.Ordinal); + private readonly SortedSet _slots = new(); + private readonly SortedSet _returns = new(); + private readonly SortedDictionary _fired = new(StringComparer.OrdinalIgnoreCase); + private readonly SortedSet _globals = new(); + private readonly SortedSet _assumptions = new(StringComparer.Ordinal); + private TableResolution? _columns; + private PluginBypass _bypass; + + public IReadOnlyCollection Tables => _tables; + + /// + /// Why part of the value couldn't be resolved, one entry per distinct cause. + /// + public IReadOnlyCollection Reasons => _reasons; + + /// + /// Tables a lookup can refer to, by the metadata, where the record it refers to can't be determined. They are + /// required with the basis . + /// + public IReadOnlyCollection LookupTargets => _lookupTargets; + + /// + /// Parameters the value depends on, resolved per call site. + /// + public IReadOnlyCollection Slots => _slots; + + /// + /// Calls whose return value the value depends on, resolved per call context. + /// + public IReadOnlyCollection Returns => _returns; + + /// + /// The messages an operation fires plugin steps for, such as Upsert, Create and Update for an + /// UpsertRequest, each with the tables it fires on. A message with neither tables nor reasons fires on no + /// table; one with reasons fires on a table that isn't known. + /// + public IReadOnlyDictionary Fired => _fired; + + /// + /// For a message in : the columns the operation sets, in , with a reason + /// for each way more can be set, which an Update step filtered on columns runs for. + /// + public TableResolution? Columns => _columns; + + /// + /// For a message in : the plugin steps the request skips, by the bypass parameters set on it. + /// + public PluginBypass Bypass => _bypass; + + /// + /// Privileges not tied to a table that the operation needs, such as prvBulkDelete, each with the message + /// that needs it. + /// + public IReadOnlyCollection Globals => _globals; + + /// + /// What the analysis assumes about the operation, such as who an email is sent as. + /// + public IReadOnlyCollection Assumptions => _assumptions; + + /// + /// Set when nothing in the value depends on the call context: no parameter and no method's return value. + /// + public bool IsBound => _slots.Count == 0 && _returns.Count == 0 && _fired.Values.All(f => f.IsBound) && (_columns?.IsBound ?? true); + + public bool IsEmpty => + _tables.Count == 0 && _reasons.Count == 0 && _lookupTargets.Count == 0 && _fired.Count == 0 && _globals.Count == 0 && _assumptions.Count == 0 && IsBound; + + public static TableResolution Empty { get; } = new(); + + public static TableResolution Table(string logicalName) + { + var result = new TableResolution(); + result._tables.Add(logicalName.ToLowerInvariant()); + return result; + } + + public static TableResolution Unresolved(string reason) + { + var result = new TableResolution(); + result._reasons.Add(reason); + return result; + } + + public static TableResolution LookupTarget(string logicalName) + { + var result = new TableResolution(); + result._lookupTargets.Add(logicalName.ToLowerInvariant()); + return result; + } + + public static TableResolution Slot(TableSlot slot) + { + var result = new TableResolution(); + result._slots.Add(slot); + return result; + } + + public static TableResolution Returned(ReturnedTables returned) + { + var result = new TableResolution(); + result._returns.Add(returned); + return result; + } + + public static TableResolution Global(string privilege, string message) + { + var result = new TableResolution(); + result._globals.Add(new GlobalNeed(privilege, message)); + return result; + } + + public static TableResolution Assumed(string assumption) + { + var result = new TableResolution(); + result._assumptions.Add(assumption); + return result; + } + + /// + /// fired on , setting ; without + /// columns, those set aren't known. are the steps the request skips. + /// + public static TableResolution Fires(string message, TableResolution tables, TableResolution? columns = null, PluginBypass bypass = PluginBypass.None) + { + var fired = tables.Copy(); + fired._columns = columns ?? Unresolved("the columns set aren't known"); + fired._bypass = bypass; + var result = new TableResolution(); + result._fired.Add(message, fired); + return result; + } + + public TableResolution Union(TableResolution other) => Union([this, other]); + + public static TableResolution Union(IEnumerable parts) + { + // A single part with information is returned as is, so most unions make nothing new + TableResolution? first = null; + TableResolution? result = null; + foreach (var part in parts) + { + if (part.IsBlank) continue; + if (first is null) + { + first = part; + continue; + } + if (result is null) + { + result = first.Copy(); + } + result.UnionWith(part); + } + return result ?? first ?? Empty; + } + + // Only for a resolution being made, before anything else sees it + private void UnionWith(TableResolution other) + { + _tables.UnionWith(other._tables); + _reasons.UnionWith(other._reasons); + _lookupTargets.UnionWith(other._lookupTargets); + _slots.UnionWith(other._slots); + _returns.UnionWith(other._returns); + _globals.UnionWith(other._globals); + _assumptions.UnionWith(other._assumptions); + foreach (var fired in other._fired) + { + // A step is only known to be skipped when every request that fires the message skips it + if (!_fired.TryGetValue(fired.Key, out var existing)) + { + _fired[fired.Key] = fired.Value; + continue; + } + var merged = existing.Union(fired.Value).Copy(); + merged._bypass = existing._bypass & fired.Value._bypass; + _fired[fired.Key] = merged; + } + if (other._columns is { } columns) _columns = _columns is null ? columns : _columns.Union(columns); + } + + /// + /// The parts that don't depend on the call context: without , and + /// , which are bound per call context. + /// + public TableResolution WithoutContext() + { + var result = new TableResolution(); + result._tables.UnionWith(_tables); + result._reasons.UnionWith(_reasons); + result._lookupTargets.UnionWith(_lookupTargets); + result._globals.UnionWith(_globals); + result._assumptions.UnionWith(_assumptions); + return result; + } + + private bool IsBlank => IsEmpty && _columns is null && _bypass == PluginBypass.None; + + private TableResolution Copy() + { + var result = new TableResolution(); + result.UnionWith(this); + result._bypass = _bypass; + return result; + } + + /// + /// Turns "no information" into an explicit reason, so a final result is never silently empty. + /// + public TableResolution OrUnresolved(string reason) => IsEmpty ? Unresolved(reason) : this; + + /// + /// The value of a lookup that can refer to only. With one target that is its table. + /// With several, what can't be resolved here becomes all of them. + /// + public TableResolution WithinTargets(IReadOnlyCollection targets) + { + if (targets.Count != 1 && _reasons.Count == 0) return this; + + var result = Copy(); + result._reasons.Clear(); + if (targets.Count == 1) + { + result._tables.Clear(); + result._lookupTargets.Clear(); + result._slots.Clear(); + result._returns.Clear(); + result._tables.Add(targets.First().ToLowerInvariant()); + } + else + { + result._lookupTargets.UnionWith(targets.Select(t => t.ToLowerInvariant())); + } + return result; + } + + /// + /// A stable text form, used to tell call contexts apart. + /// + public override string ToString() => + string.Join("|", _tables) + "?" + string.Join("|", _reasons) + "*" + string.Join("|", _lookupTargets) + "$" + string.Join("|", _slots) + "^" + string.Join("|", _returns) + + "!" + string.Join("|", _fired.Select(f => $"{f.Key}=({f.Value})")) + (_columns is null ? "" : $"#({_columns})") + + (_bypass == PluginBypass.None ? "" : $"~{_bypass}") + "&" + string.Join("|", _globals) + "%" + string.Join("|", _assumptions); +} + +/// +/// A privilege not tied to a table, such as prvBulkDelete, that needs. The name is +/// looked up in the privilege catalog, never derived from its spelling. +/// +internal sealed record GlobalNeed(string Privilege, string Message) : IComparable +{ + public int CompareTo(GlobalNeed? other) + { + if (other is null) return 1; + var result = string.CompareOrdinal(Privilege, other.Privilege); + return result != 0 ? result : string.CompareOrdinal(Message, other.Message); + } + + public override string ToString() => $"{Privilege}@{Message}"; +} + +/// +/// The plugin steps a request skips, by its BypassCustomPluginExecution or BypassBusinessLogicExecution +/// parameter. +/// +[Flags] +internal enum PluginBypass +{ + None = 0, + Synchronous = 1, + Asynchronous = 2, +} + +/// +/// How a parameter value is read for its table, because a string can be a table name or FetchXML, and a query +/// can count its linked tables or only its main table. +/// +internal enum TableShape +{ + Name, + Entity, + Query, + QueryMainTable, + Fetch, + FetchMainTable, + EntityReferences, + Records, + + // An entity, or a collection of entities, read for the lookups set on it: the tables that need Append because + // a lookup is set on them, and the tables the lookups refer to, which need AppendTo + LookupHolder, + LookupTarget, + + // An entity read for the columns set on it, which decide the Update steps filtered on columns it fires + Columns, + + // A request, or a collection of requests, read for the tables it needs one privilege on (see RequestShapes) + RequestCreate, + RequestRead, + RequestWrite, + RequestDelete, + RequestAppend, + RequestAppendTo, + RequestAssign, + RequestShare, + + /// + /// A request read for what can't be tied to a privilege: requests without a rule, or of unknown type, and the + /// plugin steps it fires. + /// + RequestOther, +} + +/// +/// The shapes a request is read as: one per privilege, plus . +/// +internal static class RequestShapes +{ + public static IReadOnlyList All { get; } = + [.. Enum.GetValues(typeof(Privilege)).Cast().Select(For), TableShape.RequestOther]; + + public static TableShape For(Privilege privilege) => privilege switch + { + Privilege.Create => TableShape.RequestCreate, + Privilege.Read => TableShape.RequestRead, + Privilege.Write => TableShape.RequestWrite, + Privilege.Delete => TableShape.RequestDelete, + Privilege.Append => TableShape.RequestAppend, + Privilege.AppendTo => TableShape.RequestAppendTo, + Privilege.Assign => TableShape.RequestAssign, + Privilege.Share => TableShape.RequestShare, + _ => throw new ArgumentOutOfRangeException(nameof(privilege), privilege, null), + }; + + /// + /// The privilege a request shape is read for; null for and the + /// other shapes. + /// + public static Privilege? PrivilegeOf(TableShape shape) => shape switch + { + TableShape.RequestCreate => Privilege.Create, + TableShape.RequestRead => Privilege.Read, + TableShape.RequestWrite => Privilege.Write, + TableShape.RequestDelete => Privilege.Delete, + TableShape.RequestAppend => Privilege.Append, + TableShape.RequestAppendTo => Privilege.AppendTo, + TableShape.RequestAssign => Privilege.Assign, + TableShape.RequestShare => Privilege.Share, + _ => null, + }; + + public static bool IsRequest(TableShape shape) => shape >= TableShape.RequestCreate; + + /// + /// A reason that is reported under only, as it applies to no privilege. + /// + public static TableResolution Other(TableShape shape, string reason) => + shape == TableShape.RequestOther ? TableResolution.Unresolved(reason) : TableResolution.Empty; +} + +/// +/// A table that depends on parameter , on a type parameter of a generic method (see +/// ) of , or on a type parameter of its type (see +/// ), read as . +/// is reported when no call site provides the argument; an empty reason reports nothing, for +/// a request read for one privilege, whose reason is reported once under . +/// +internal sealed record TableSlot(string Method, int Ordinal, TableShape Shape, string Reason) : IComparable +{ + /// + /// The of the slot for the execution context's PrimaryEntityName, which the entry + /// point fills in: the table of the plugin step it runs for. + /// + public const string PrimaryEntity = ""; + + /// + /// The ordinal a method's type parameter is bound under. Negative, so it never clashes with a parameter: a + /// call binds type argument i as if it were argument -1 - i, read as . + /// + public static int TypeParameterOrdinal(int ordinal) => -1 - ordinal; + + /// + /// The ordinal a type parameter of the method's type, or of a type it is nested in, is bound under: its + /// position among , below the ordinals of a method's type parameters. + /// + public static int TypeArgumentOrdinal(int ordinal) => -(1 << 20) - ordinal; + + public int CompareTo(TableSlot? other) + { + if (other is null) return 1; + var result = string.CompareOrdinal(Method, other.Method); + if (result == 0) result = Ordinal.CompareTo(other.Ordinal); + if (result == 0) result = Shape.CompareTo(other.Shape); + return result != 0 ? result : string.CompareOrdinal(Reason, other.Reason); + } + + public override string ToString() => $"{Method}#{Ordinal}:{Shape}"; +} + +/// +/// The tables of the value returns, read as , such as a query built by a +/// helper method. is reported when the method isn't in the call graph or returns nothing known; +/// an empty reason reports nothing, as for . +/// +internal sealed record ReturnedTables(CallFact Call, TableShape Shape, string Reason) : IComparable +{ + public int CompareTo(ReturnedTables? other) + { + if (other is null) return 1; + var result = Call.Source.CompareTo(other.Call.Source); + if (result == 0) result = string.CompareOrdinal(SummaryKeys.Call(Call), SummaryKeys.Call(other.Call)); + if (result == 0) result = Shape.CompareTo(other.Shape); + return result != 0 ? result : string.CompareOrdinal(Reason, other.Reason); + } + + public override string ToString() => $"{SummaryKeys.Call(Call)}:{Shape}:{Reason}"; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/TableResolver.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/TableResolver.cs new file mode 100644 index 00000000..27e21869 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/TableResolver.cs @@ -0,0 +1,1278 @@ +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Operations; +using XrmMockup.PermissionAnalyzer.Core.Graph; +using XrmMockup.PermissionAnalyzer.Core.Model; +using static XrmMockup.PermissionAnalyzer.Core.Extraction.Operations; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// Works out which tables a value refers to: early-bound types, constants, FetchXML and assignments to locals +/// in the same method. Anything else becomes a reason in the resolution, never a guess. +/// +/// +/// Parameters and type parameters of the method become slots, filled in per call site. +/// turns a call to a method in the solution into the call graph's view of it, so the tables of its return value +/// are resolved per call context too; without it such a value is unresolved. Requests are read through +/// , and the tables a lookup refers to are narrowed by . A type +/// parameter of the type of becomes a slot of it, filled in from the call's receiver. +/// +internal sealed class TableResolver( + XrmSymbols symbols, + RequestRules? rules = null, + Func? calls = null, + LookupColumns? lookups = null, + IMethodSymbol? method = null) +{ + // The access rights of AccessRights, as in PrincipalAccess.AccessMask + private static readonly (int Bit, Privilege Privilege)[] AccessRights = + [ + (1, Privilege.Read), (2, Privilege.Write), (4, Privilege.Append), (16, Privilege.AppendTo), + (32, Privilege.Create), (65536, Privilege.Delete), (262144, Privilege.Share), (524288, Privilege.Assign), + ]; + + private readonly RequestRules _rules = rules ?? new RequestRules(); + + // Stands in for runtime text inside a FetchXML template. Private use area, so real FetchXML never contains it. + private const char Hole = ''; + + // Concatenating locals with several assignments multiplies the variants; stop before that gets out of hand. + private const int MaxTemplates = 64; + + private const int MaxNesting = 4; + private const string NotFetch = "FetchXML could not be parsed"; + private static readonly char[] XmlWhitespace = [' ', '\t', '\r', '\n']; + private const string NestedLinksReason = "tables linked through LinkEntities, LinkEntity.AddLink or new LinkEntity are not analyzed yet"; + + private readonly HashSet _visiting = new(SymbolEqualityComparer.Default); + + /// + /// A table logical name, such as the entityName argument of Retrieve. + /// + public TableResolution Name(IOperation? operation) + { + var op = Unwrap(operation); + if (op is null) return TableResolution.Unresolved("table name argument is missing"); + + if (op.ConstantValue.HasValue) + { + return op.ConstantValue.Value is string { Length: > 0 } name + ? TableResolution.Table(name) + : TableResolution.Unresolved("table name is null or empty"); + } + + return op switch + { + ILocalReferenceOperation local => FromLocal(local, Name), + IPropertyReferenceOperation { Property.Name: SdkNames.LogicalName, Instance: { } instance } property + when IsEntityOrReference(property.Property.ContainingType) => Entity(instance), + IPropertyReferenceOperation { Property.Name: SdkNames.PrimaryEntityName } property + when symbols.Is(property.Property.ContainingType, symbols.ExecutionContext) => + TableResolution.Slot(new TableSlot(TableSlot.PrimaryEntity, 0, TableShape.Name, Describe(op, "table name"))), + _ when Branches(op) is { } branches => Union(branches, Name), + _ => Unknown(op, "table name", TableShape.Name), + }; + } + + /// + /// The table of an Entity or EntityReference value. + /// + public TableResolution Entity(IOperation? operation) + { + var op = operation; + while (true) + { + if (op is null) return TableResolution.Unresolved("entity argument is missing"); + if (symbols.LogicalNameOf(op.Type) is { } logicalName) return TableResolution.Table(logicalName); + if (op.Type is ITypeParameterSymbol typeParameter) return TypeParameter(typeParameter); + + var inner = UnwrapOnce(op); + if (inner is null) break; + op = inner; + } + + switch (op) + { + // Writing a null entity throws, and a null lookup refers to nothing, so such a value needs nothing + case { ConstantValue: { HasValue: true, Value: null } }: + return TableResolution.Empty; + + case IObjectCreationOperation creation: + return AssignedMember(creation.Initializer, SdkNames.LogicalName, Name) + ?? (FirstStringArgument(creation) is { } nameArgument ? Name(nameArgument.Value) : TableResolution.Empty); + + case ILocalReferenceOperation local: + return FromLocal(local, Entity, EntityElements, (node, symbol) => + node is ISimpleAssignmentOperation { Target: IPropertyReferenceOperation { Property.Name: SdkNames.LogicalName } property } assignment + && IsLocal(property.Instance, symbol) + ? Name(assignment.Value) + : null); + + case IInvocationOperation { TargetMethod.Name: SdkNames.ToEntityReference, Instance: { } instance }: + return Entity(instance); + + case IPropertyReferenceOperation property when EntitiesOf(property) is { } records: + return Records(records); + + case IParameterReferenceOperation parameter when LambdaSource(parameter) is { } source: + return EntityElements(source); + + case { } when Branches(op) is { } branches: + return Union(branches, Entity); + + // The record Retrieve returns is of the table it is asked for + case IInvocationOperation retrieve when symbols.ServiceOperation(retrieve.TargetMethod) == Messages.Retrieve: + return Name(Argument(retrieve, 0)); + + case IPropertyReferenceOperation { Property.IsIndexer: false } property when LookupTargets(property) is { Count: > 0 } targets: + return Unknown(op, "entity", TableShape.Entity).WithinTargets(targets); + + default: + return Unknown(op, "entity", TableShape.Entity); + } + } + + /// + /// The tables a QueryBase value reads: the main table plus, with , + /// every linked table. The records a query returns belong to the main table only. + /// + public TableResolution Query(IOperation? operation, bool includeLinks = true) + { + var op = Unwrap(operation); + switch (op) + { + case null: + return TableResolution.Unresolved("query argument is missing"); + + case IObjectCreationOperation creation when symbols.Is(creation.Type, symbols.FetchExpression): + return AssignedMember(creation.Initializer, SdkNames.Query, v => Fetch(v, includeLinks)) + ?? (FirstStringArgument(creation) is { } fetchArgument ? Fetch(fetchArgument.Value, includeLinks) : TableResolution.Empty); + + case IObjectCreationOperation creation when IsTableQuery(creation.Type): + { + var result = AssignedMember(creation.Initializer, SdkNames.EntityName, Name) + ?? (FirstStringArgument(creation) is { } nameArgument ? Name(nameArgument.Value) : TableResolution.Empty); + return includeLinks && symbols.Is(creation.Type, symbols.QueryExpression) ? result.Union(NestedLinks(creation)) : result; + } + + case ILocalReferenceOperation local: + { + var result = FromLocal(local, v => Query(v, includeLinks), null, (node, symbol) => node switch + { + ISimpleAssignmentOperation { Target: IPropertyReferenceOperation property } assignment when IsLocal(property.Instance, symbol) => + property.Property.Name switch + { + SdkNames.EntityName => Name(assignment.Value), + SdkNames.Query when symbols.Is(property.Property.ContainingType, symbols.FetchExpression) => Fetch(assignment.Value, includeLinks), + _ => null, + }, + IInvocationOperation { TargetMethod.Name: SdkNames.AddLink } addLink + when includeLinks && IsLocal(addLink.Instance, symbol) && symbols.Is(addLink.TargetMethod.ContainingType, symbols.QueryExpression) => + FirstStringArgument(addLink) is { } linkArgument ? Name(linkArgument.Value) : null, + _ => null, + }); + return includeLinks && symbols.Is(local.Type, symbols.QueryExpression) ? result.Union(NestedLinks(local)) : result; + } + + case { } when Branches(op) is { } branches: + return Union(branches, v => Query(v, includeLinks)); + + default: + return Unknown(op, "query", includeLinks ? TableShape.Query : TableShape.QueryMainTable); + } + } + + /// + /// The tables of the records in an EntityReferenceCollection, such as the related records of Associate. + /// + public TableResolution EntityReferences(IOperation? operation) + { + var op = Unwrap(operation); + switch (op) + { + case null: + return TableResolution.Unresolved("related records argument is missing"); + + case IObjectCreationOperation creation when symbols.Is(creation.Type, symbols.EntityReferenceCollection): + return Filled(creation, IsEntityOrRecords, EntityOrReferences); + + case ILocalReferenceOperation local: + return FromLocal(local, EntityReferences, null, (node, symbol) => Added(node, symbol, IsEntityOrRecords, EntityOrReferences)); + + default: + return Elements(op); + } + } + + /// + /// The tables named in FetchXML: the entity element plus, with , + /// every link-entity. + /// + public TableResolution Fetch(IOperation? operation, bool includeLinks = true) + { + var result = new List(); + foreach (var template in Templates(operation, topLevel: true, result, includeLinks)) + { + result.Add(ParseFetch(template, includeLinks)); + } + return TableResolution.Union(result); + } + + /// + /// The tables of a value read as , such as an argument bound to a parameter slot. + /// + public TableResolution Resolve(IOperation? operation, TableShape shape) => shape switch + { + TableShape.Name => Name(operation), + TableShape.Entity => Entity(operation), + TableShape.Query => Query(operation), + TableShape.QueryMainTable => Query(operation, includeLinks: false), + TableShape.Fetch => Fetch(operation), + TableShape.FetchMainTable => Fetch(operation, includeLinks: false), + TableShape.EntityReferences => EntityReferences(operation), + TableShape.Records => Records(operation), + TableShape.LookupHolder or TableShape.LookupTarget => Lookups(operation, shape), + TableShape.Columns => Columns(operation), + _ => Requests(operation, shape), + }; + + /// + /// The table of a type argument, such as Account in repository.Retrieve<Account>(). + /// + public TableResolution TypeArgument(ITypeSymbol type) => + symbols.LogicalNameOf(type) is { } logicalName ? TableResolution.Table(logicalName) + : type is ITypeParameterSymbol typeParameter ? TypeParameter(typeParameter) + : TableResolution.Unresolved($"type '{type.Name}' has no table"); + + /// + /// The shapes a parameter of can be read as; empty when it can't name a table. A type + /// parameter is read as its constraints allow, so an unconstrained one names no table. + /// + public IReadOnlyList ShapesOf(ITypeSymbol type) + { + if (type is ITypeParameterSymbol typeParameter) return typeParameter.ConstraintTypes.Select(ShapesOf).FirstOrDefault(s => s.Count > 0) ?? []; + if (type.SpecialType == SpecialType.System_String) return [TableShape.Name, TableShape.Fetch, TableShape.FetchMainTable]; + if (symbols.Is(type, symbols.EntityReference)) return [TableShape.Entity]; + if (symbols.Is(type, symbols.Entity)) return [TableShape.Entity, TableShape.LookupHolder, TableShape.LookupTarget, TableShape.Columns]; + if (symbols.Is(type, symbols.QueryBase)) return [TableShape.Query, TableShape.QueryMainTable]; + if (symbols.Is(type, symbols.EntityReferenceCollection)) return [TableShape.EntityReferences]; + if (symbols.Is(type, symbols.EntityCollection)) return [TableShape.Records, TableShape.LookupHolder, TableShape.LookupTarget]; + if (IsRequestLike(type)) return RequestShapes.All; + if (ElementType(type) is { } element && IsEntityLike(element)) + { + return symbols.Is(element, symbols.EntityReference) ? [TableShape.Records] : [TableShape.Records, TableShape.LookupHolder, TableShape.LookupTarget]; + } + return []; + } + + /// + /// The tables a request, or every request in a collection of them, needs the privilege of + /// on, by the request's rule. Read as , it gives + /// what can't be tied to a privilege instead: requests without a rule, and requests that can't be followed. + /// + public TableResolution Requests(IOperation? operation, TableShape shape) + { + var op = Unwrap(operation); + switch (op) + { + case null: + return RequestShapes.Other(shape, "request argument is missing"); + + // Executing null throws, so such a branch, usually one the caller guards against, needs nothing + case { ConstantValue: { HasValue: true, Value: null } }: + return TableResolution.Empty; + + case IObjectCreationOperation creation when symbols.Is(creation.Type, symbols.OrganizationRequest): + return Request(creation, null, shape); + + // A collection of requests, such as OrganizationRequestCollection or List + case IObjectCreationOperation creation: + return Filled(creation, t => IsRequestLike(t), value => Requests(value, shape)); + + case IArrayCreationOperation or ICollectionExpressionOperation: + return Union(CollectionElements(op), element => Requests(element, shape)); + + case ILocalReferenceOperation local: + return FromLocal( + local, + value => Unwrap(value) is IObjectCreationOperation creation && symbols.Is(creation.Type, symbols.OrganizationRequest) + ? Request(creation, local.Local, shape) + : Requests(value, shape), + collection => Requests(collection, shape), + (node, symbol) => Added(node, symbol, t => IsRequestLike(t), value => Requests(value, shape))); + + case IParameterReferenceOperation parameter when LambdaSource(parameter) is { } source: + return Requests(source, shape); + + case IInvocationOperation invocation when IsSystemCall(invocation): + return Passthrough(invocation, t => IsRequestLike(t), value => Requests(value, shape), value => Requests(value, shape)) ?? UnknownRequest(op, shape); + + case { } when Branches(op) is { } branches: + return Union(branches, v => Requests(v, shape)); + + default: + return UnknownRequest(op, shape); + } + } + + /// + /// A created request, read by the rule for its type, or for its RequestName when it is an + /// OrganizationRequest. Its members are set in its initializer or, for , through + /// the local it is assigned to. + /// + private TableResolution Request(IObjectCreationOperation creation, ILocalSymbol? owner, TableShape shape) + { + List Members(string member) => MemberValues(creation, owner, member); + + if (!SymbolEqualityComparer.Default.Equals(creation.Type?.OriginalDefinition, symbols.OrganizationRequest)) + { + return Apply(RequestRules.MessageOfType(creation.Type!.Name), Members, shape); + } + + var names = Members(SdkNames.RequestName); + if (FirstStringArgument(creation) is { } nameArgument) names.Add(nameArgument.Value); + if (names.Count == 0) return RequestShapes.Other(shape, "request has no name"); + + return TableResolution.Union(names.Select(name => Unwrap(name)?.ConstantValue is { HasValue: true, Value: string { Length: > 0 } message } + ? Apply(message, Members, shape) + : RequestShapes.Other(shape, "request name is computed at runtime"))); + } + + /// + /// The tables needs the privilege of on, by its rule, with the + /// values of the request's members from . + /// + private TableResolution Apply(string message, Func> members, TableShape shape) + { + var request = new CodeMembers(this, members); + if (_rules.Find(message) is not { } rule) + { + // Steps registered on a message without a rule, such as a custom action, fire on no table + var unknown = RequestShapes.Other(shape, RequestReasons.NoRule(message)); + if (shape != TableShape.RequestOther) return unknown; + var bypassed = request.Bypass(message, out var unknownBypass); + return TableResolution.Union([unknown, bypassed, TableResolution.Fires(message, TableResolution.Empty, bypass: unknownBypass)]); + } + return RuleApplication.Apply(message, rule, request, shape); + } + + /// + /// The members of a request created in code, read from the values they are set to. + /// + private sealed class CodeMembers(TableResolver resolver, Func> values) : IRequestMembers + { + public TableResolution Tables(string message, string member) => resolver.MemberTables(message, member, values(member)); + + public TableResolution? Columns(string member) + { + var written = values(member); + return written.Count > 0 && written.All(resolver.IsEntity) + ? Union(written, resolver.Columns) + : null; + } + + public bool MayBeSet(string member) => values(member).Any(MayBeTrue); + + public IReadOnlyList Rights(string path, out TableResolution reasons) => resolver.Rights(path, values, out reasons); + + public TableResolution Lookups(string member, TableShape shape) => Union(values(member), value => resolver.Lookups(value, shape)); + + public TableResolution Requests(string member, TableShape shape) => Union(values(member), value => resolver.Requests(value, shape)); + + public TableResolution Bypass(string message, out PluginBypass bypass) => TableResolver.Bypass(message, values, out bypass); + } + + /// + /// The privileges the bypass parameters of a request need, and in the plugin steps + /// they certainly skip. BypassCustomPluginExecution skips synchronous steps and needs + /// prvBypassCustomPlugins; BypassBusinessLogicExecution skips the synchronous steps for CustomSync + /// and the asynchronous ones for CustomAsync, and needs prvBypassCustomBusinessLogic, as does + /// BypassBusinessLogicExecutionStepIds. The steps that one skips aren't known, as the analysis doesn't + /// know step ids, so they are taken to run. A value set at runtime needs the privilege but skips no step. + /// + private static TableResolution Bypass(string message, Func> members, out PluginBypass bypass) + { + var result = new List(); + bypass = PluginBypass.None; + + var plugins = members(BypassCustomPluginExecution); + if (plugins.Any(MayBeTrue)) + { + result.Add(TableResolution.Global(GlobalRequirement.BypassCustomPlugins, message)); + } + if (plugins.Count > 0 && plugins.All(v => Unwrap(v)?.ConstantValue is { HasValue: true, Value: true })) + { + bypass |= PluginBypass.Synchronous; + } + + var logic = members(BypassBusinessLogicExecution); + var stepIds = members(BypassBusinessLogicExecutionStepIds); + if (logic.Concat(stepIds).Any(v => !IsEmptyConstant(v))) + { + result.Add(TableResolution.Global(GlobalRequirement.BypassCustomBusinessLogic, message)); + } + if (logic.Count > 0) + { + // Only what every value set skips is certain + bypass |= logic.Aggregate(PluginBypass.Synchronous | PluginBypass.Asynchronous, (skipped, value) => skipped & Skipped(value)); + } + return TableResolution.Union(result); + } + + private const string BypassCustomPluginExecution = "BypassCustomPluginExecution"; + private const string BypassBusinessLogicExecution = "BypassBusinessLogicExecution"; + private const string BypassBusinessLogicExecutionStepIds = "BypassBusinessLogicExecutionStepIds"; + + private static bool IsEmptyConstant(IOperation value) => + Unwrap(value)?.ConstantValue is { HasValue: true, Value: null or "" }; + + /// + /// The steps a BypassBusinessLogicExecution value skips: CustomSync, CustomAsync, or both, + /// separated by commas. None when it is set at runtime. + /// + private static PluginBypass Skipped(IOperation value) + { + if (Unwrap(value)?.ConstantValue is not { HasValue: true, Value: string text }) return PluginBypass.None; + var skipped = PluginBypass.None; + foreach (var part in text.Split(',')) + { + if (part.Trim().Equals("CustomSync", StringComparison.OrdinalIgnoreCase)) skipped |= PluginBypass.Synchronous; + else if (part.Trim().Equals("CustomAsync", StringComparison.OrdinalIgnoreCase)) skipped |= PluginBypass.Asynchronous; + } + return skipped; + } + + /// + /// The tables of a request member's value, read by its type: an entity or reference, a table name, a query, or + /// a collection of records. + /// + private TableResolution MemberTables(IOperation value) + { + var op = Unwrap(value); + var shapes = op?.Type is { } type ? ShapesOf(type).Where(s => !RequestShapes.IsRequest(s)).ToList() : []; + return shapes.Count > 0 ? Resolve(op, shapes[0]) : TableResolution.Unresolved(Describe(op, "request member")); + } + + private TableResolution MemberTables(string message, string member, List values) + { + if (values.Count == 0) return TableResolution.Unresolved($"{member} of the {message} request isn't set where the request is created"); + return Union(values, MemberTables); + } + + /// + /// Whether a flag can be set: anything but the constant false. + /// + private static bool MayBeTrue(IOperation value) => Unwrap(value)?.ConstantValue is not { HasValue: true, Value: false }; + + /// + /// The privileges of the access rights in the member at , such as + /// PrincipalAccess.AccessMask. + /// + private List Rights(string path, Func> members, out TableResolution reasons) + { + var segments = path.Split('.'); + var values = members(segments[0]); + foreach (var segment in segments.Skip(1)) values = values.SelectMany(v => ObjectMemberValues(v, segment)).ToList(); + + var failures = new List(); + if (values.Count == 0) failures.Add(TableResolution.Unresolved($"{path} isn't set where the request is created")); + + var privileges = new List(); + foreach (var value in values) + { + if (Unwrap(value)?.ConstantValue is { HasValue: true, Value: { } constant } && constant is int or uint or long) + { + var mask = Convert.ToInt64(constant); + privileges.AddRange(AccessRights.Where(r => (mask & r.Bit) != 0).Select(r => r.Privilege)); + } + else + { + failures.Add(TableResolution.Unresolved($"{path} is computed at runtime")); + } + } + reasons = TableResolution.Union(failures); + return privileges; + } + + /// + /// The values a member of a created object is set to: by its constructor argument of the same name, in its + /// initializer, and, for , through the local that holds it. A Parameters + /// entry or indexer with the member's name counts as the member. + /// + private List MemberValues(IObjectCreationOperation creation, ILocalSymbol? owner, string member) + { + var values = creation.Arguments + .Where(a => string.Equals(a.Parameter?.Name, member, StringComparison.OrdinalIgnoreCase)) + .Select(a => a.Value) + .ToList(); + if (creation.Initializer is { } initializer) values.AddRange(Inside(initializer).SelectMany(node => SetMember(node, IsImplicitReceiver, member))); + if (owner is not null) values.AddRange(Root(creation).DescendantsAndSelf().SelectMany(node => SetMember(node, instance => IsLocal(instance, owner), member))); + return values; + } + + /// + /// The values a member is set to on an object that is created here or held in a local. + /// + private List ObjectMemberValues(IOperation value, string member) => Unwrap(value) switch + { + IObjectCreationOperation creation => MemberValues(creation, null, member), + ILocalReferenceOperation local => LocalValues(local.Local, Root(local), null) + .Where(v => !v.IsLoopCollection) + .SelectMany(v => Unwrap(v.Operation) is IObjectCreationOperation creation ? MemberValues(creation, null, member) : []) + .Concat(Root(local).DescendantsAndSelf().SelectMany(node => SetMember(node, instance => IsLocal(instance, local.Local), member))) + .ToList(), + _ => [], + }; + + /// + /// The value sets to on an object + /// accepts: o.Member = x, o["Member"] = x, o.Parameters["Member"] = x, + /// o.Parameters.Add("Member", x), or what o.Member.Add(x) adds to a collection member. + /// + private static IEnumerable SetMember(IOperation node, Func isObject, string member) + { + bool IsOwnedBy(IOperation? instance) => + isObject(instance) || (Unwrap(instance) is IPropertyReferenceOperation { Property.Name: SdkNames.Parameters } parameters && isObject(parameters.Instance)); + + switch (node) + { + case ISimpleAssignmentOperation { Target: IPropertyReferenceOperation { Property.IsIndexer: false } property } assignment + when property.Property.Name == member && isObject(property.Instance): + return [assignment.Value]; + + case ISimpleAssignmentOperation { Target: IPropertyReferenceOperation { Property.IsIndexer: true } indexer } assignment + when IsOwnedBy(indexer.Instance) && indexer.Arguments.Length == 1 && Key(indexer.Arguments[0].Value) == member: + return [assignment.Value]; + + case IInvocationOperation { TargetMethod.Name: "Add", Arguments.Length: 2 } add + when IsOwnedBy(add.Instance) && Key(add.Arguments[0].Value) == member: + return [add.Arguments[1].Value]; + + case IInvocationOperation { TargetMethod.Name: "Add" or "AddRange" } add + when Unwrap(add.Instance) is IPropertyReferenceOperation collection && collection.Property.Name == member && isObject(collection.Instance): + return add.Arguments.Select(a => a.Value); + + case IMemberInitializerOperation { InitializedMember: IPropertyReferenceOperation property, Initializer: { } initializer } + when property.Property.Name == member && isObject(property.Instance): + return initializer.Initializers.OfType().SelectMany(add => add.Arguments.Select(a => a.Value)); + + default: + return []; + } + } + + /// + /// The operations of an object initializer, without those of objects created inside it, whose members are + /// their own. + /// + private static IEnumerable Inside(IOperation initializer) + { + var pending = new Stack([initializer]); + while (pending.Count > 0) + { + var node = pending.Pop(); + yield return node; + foreach (var child in node.ChildOperations.Reverse()) + { + if (child is not (IObjectCreationOperation or IAnonymousObjectCreationOperation or IAnonymousFunctionOperation)) pending.Push(child); + } + } + } + + private static bool IsImplicitReceiver(IOperation? operation) => operation is IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ImplicitReceiver }; + + /// + /// The table of the records in an EntityCollection, such as the result of RetrieveMultiple. + /// + /// + /// Any collection of entities is read the same way: a list or array of early-bound entities by its element + /// type, and other collections by what is put in them. + /// + private TableResolution Records(IOperation? operation) + { + var op = Unwrap(operation); + if (symbols.Is(op?.Type, symbols.EntityReferenceCollection)) return EntityReferences(op); + if (ElementType(op?.Type) is { } elementType && (symbols.LogicalNameOf(elementType) is not null || (elementType is ITypeParameterSymbol && IsEntityLike(elementType)))) + { + return TypeArgument(elementType); + } + + switch (op) + { + case null: + return TableResolution.Unresolved("records argument is missing"); + + case IInvocationOperation invocation when symbols.ServiceOperation(invocation.TargetMethod) == Messages.RetrieveMultiple: + return Query(Argument(invocation, 0), includeLinks: false).OrUnresolved("query has no table name"); + + case IPropertyReferenceOperation property when EntitiesOf(property) is { } records: + return Records(records); + + case IObjectCreationOperation creation: + return Filled(creation, IsEntityOrRecords, EntityOrRecords).Union(AssignedMember(creation.Initializer, SdkNames.EntityName, Name) ?? TableResolution.Empty); + + case IArrayCreationOperation or ICollectionExpressionOperation: + return Union(CollectionElements(op), EntityOrRecords); + + case ILocalReferenceOperation local: + return FromLocal(local, Records, Records, (node, symbol) => node switch + { + _ when Added(node, symbol, IsEntityOrRecords, EntityOrRecords) is { } added => added, + ISimpleAssignmentOperation { Target: IPropertyReferenceOperation { Property.Name: SdkNames.EntityName } property } assignment when IsLocal(property.Instance, symbol) => + Name(assignment.Value), + _ => null, + }); + + case IParameterReferenceOperation parameter when LambdaSource(parameter) is { } source: + return Records(source); + + case IInvocationOperation invocation when IsSystemCall(invocation): + return Passthrough(invocation, IsEntityOrRecords, Records, EntityOrRecords) ?? Unknown(op, "records", TableShape.Records); + + case { } when Branches(op) is { } branches: + return Union(branches, Records); + + default: + return Unknown(op, "records", TableShape.Records); + } + } + + /// + /// What the lookups set on an entity, or on every entity in a collection of them, need. Read as + /// : the tables of the entities that get a lookup, which need Append. Read + /// as : the tables the lookups refer to, which need AppendTo. + /// + /// + /// Only lookups set in the code are seen, and an entity from elsewhere, such as one that is retrieved, adds + /// nothing for those it already holds. Nothing is reported for such an entity here: its table is reported where + /// that can't be resolved. ownerid is left out, as XrmMockup leaves it out. + /// + public TableResolution Lookups(IOperation? operation, TableShape shape) + { + var op = Unwrap(operation); + switch (op) + { + case null: + case { ConstantValue: { HasValue: true, Value: null } }: + return TableResolution.Empty; + + case { Type: var type } when symbols.Is(type, symbols.EntityReference) || symbols.Is(type, symbols.EntityReferenceCollection): + return TableResolution.Empty; + + case IObjectCreationOperation creation when IsEntityLike(creation.Type): + return Set(creation, creation.Initializer is { } members ? Inside(members).SelectMany(node => SetLookup(node, IsImplicitReceiver)) : [], shape); + + // A collection of entities, such as EntityCollection or List + case IObjectCreationOperation creation: + return Filled(creation, IsEntityOrRecords, value => Lookups(value, shape)); + + case IArrayCreationOperation or ICollectionExpressionOperation: + return Union(CollectionElements(op), element => Lookups(element, shape)); + + case IPropertyReferenceOperation property when EntitiesOf(property) is { } records: + return Lookups(records, shape); + + case IInvocationOperation { TargetMethod.Name: SdkNames.ToEntity, Instance: { } instance } when IsEntityLike(instance.Type): + return Lookups(instance, shape); + + case ILocalReferenceOperation local: + { + var result = FromLocal(local, value => Lookups(value, shape), collection => Lookups(collection, shape), + (node, symbol) => Added(node, symbol, IsEntityOrRecords, value => Lookups(value, shape)), silent: true); + + // Lookups set through the local, once it is no longer being resolved, so its table can be + return IsEntityLike(local.Type) + ? result.Union(Set(local, Root(local).DescendantsAndSelf().SelectMany(node => SetLookup(node, instance => IsLocal(instance, local.Local))), shape)) + : result; + } + + case IParameterReferenceOperation parameter when LambdaSource(parameter) is { } source: + return Lookups(source, shape); + + case IParameterReferenceOperation parameter: + { + // The caller's lookups, and those set on the parameter here + var result = Unknown(op, "entity", shape, silent: true); + return IsEntityLike(parameter.Type) + ? result.Union(Set(parameter, Root(parameter).DescendantsAndSelf().SelectMany(node => SetLookup(node, instance => IsParameter(instance, parameter.Parameter))), shape)) + : result; + } + + case IInvocationOperation invocation when IsSystemCall(invocation): + return Passthrough(invocation, IsEntityOrRecords, value => Lookups(value, shape), value => Lookups(value, shape)) ?? TableResolution.Empty; + + case { } when Branches(op) is { } branches: + return Union(branches, v => Lookups(v, shape)); + + default: + return Unknown(op, "entity", shape, silent: true); + } + } + + /// + /// The columns set on an entity, in , with a reason for each way more can be + /// set: a column whose name is computed at runtime, an entity from elsewhere, such as one that is retrieved, or + /// an entity passed to a method in the solution, which can set more. + /// + public TableResolution Columns(IOperation? operation) + { + var op = Unwrap(operation); + switch (op) + { + case null: + case { ConstantValue: { HasValue: true, Value: null } }: + return TableResolution.Empty; + + case IObjectCreationOperation creation when IsEntityLike(creation.Type): + return creation.Initializer is { } members + ? Union(Inside(members), node => ColumnsSet(node, IsImplicitReceiver, null)) + : TableResolution.Empty; + + case IInvocationOperation { TargetMethod.Name: SdkNames.ToEntity, Instance: { } instance } when IsEntityLike(instance.Type): + return Columns(instance); + + case ILocalReferenceOperation local when IsEntityLike(local.Type): + return FromLocal(local, Columns, use: (node, symbol) => ColumnsSet(node, instance => IsLocal(instance, symbol), CallOf(local))); + + case IParameterReferenceOperation parameter when IsEntityLike(parameter.Type) && LambdaSource(parameter) is null: + { + // The caller's columns, and those set on the parameter here + var set = Root(parameter).DescendantsAndSelf().Select(node => ColumnsSet(node, instance => IsParameter(instance, parameter.Parameter), CallOf(parameter))); + return TableResolution.Union(set.Prepend(Unknown(op, "entity", TableShape.Columns))); + } + + case { } when Branches(op) is { } branches: + return Union(branches, Columns); + + default: + return Unknown(op, "entity", TableShape.Columns); + } + } + + /// + /// The columns sets on an entity accepts, or a reason when it + /// passes the entity to a method in the solution other than , the one being resolved for. + /// + private TableResolution ColumnsSet(IOperation node, Func isObject, IInvocationOperation? call) + { + if (SetColumn(node, isObject) is { } set) + { + return set.Column is { } column ? TableResolution.Table(column) : TableResolution.Unresolved("a column name is computed at runtime"); + } + // Only whether the method is in the solution, as building its call would resolve its arguments in turn + if (node is IInvocationOperation invocation && !ReferenceEquals(invocation, call) && calls is not null + && IsInSource(invocation.TargetMethod) && invocation.Arguments.Any(a => isObject(Unwrap(a.Value)))) + { + return TableResolution.Unresolved($"entity is passed to '{invocation.TargetMethod.Name}', which can set more columns"); + } + return TableResolution.Empty; + } + + /// + /// The call is an argument of. + /// + private static IInvocationOperation? CallOf(IOperation operation) + { + var current = operation.Parent; + while (current is IConversionOperation or IParenthesizedOperation) current = current.Parent; + return current is IArgumentOperation { Parent: IInvocationOperation invocation } ? invocation : null; + } + + /// + /// What the lookups on need, read as . + /// The table a lookup refers to is narrowed to the tables its column can refer to, when the metadata knows it. + /// + private TableResolution Set(IOperation entity, IEnumerable<(string? Column, IOperation Value)> set, TableShape shape) + { + var values = set.ToList(); + if (values.Count == 0) return TableResolution.Empty; + if (shape == TableShape.LookupHolder) return Entity(entity); + + var tables = lookups is not null && values.Any(l => l.Column is not null) ? Entity(entity).Tables : []; + var result = new List(); + foreach (var (column, value) in values) + { + var targets = column is null ? [] : tables.SelectMany(table => lookups!.TargetsOf(table, column)).Distinct(StringComparer.Ordinal).ToList(); + result.Add(targets.Count > 0 ? Entity(value).WithinTargets(targets) : Entity(value)); + } + return TableResolution.Union(result); + } + + // XrmMockup doesn't check AppendTo on the owner a lookup sets, so ownerid is no lookup here + private const string OwnerColumn = "ownerid"; + + /// + /// The lookup sets on an entity accepts, with its column when + /// known, where the value is an EntityReference (see ). + /// + private IEnumerable<(string? Column, IOperation Value)> SetLookup(IOperation node, Func isObject) + { + if (SetColumn(node, isObject) is { } lookup && symbols.Is(Unwrap(lookup.Value)?.Type, symbols.EntityReference) && lookup.Column != OwnerColumn) yield return lookup; + } + + /// + /// The column sets on an entity accepts, with its name when + /// known: e.Name = v, e["name"] = v, e.Attributes["name"] = v or + /// e.Attributes.Add("name", v). An early-bound property that isn't a column, such as Id, sets none. + /// + private (string? Column, IOperation Value)? SetColumn(IOperation node, Func isObject) + { + bool IsAttributes(IOperation? instance) => + isObject(instance) || (Unwrap(instance) is IPropertyReferenceOperation { Property.Name: SdkNames.Attributes } attributes && isObject(attributes.Instance)); + + return node switch + { + ISimpleAssignmentOperation { Target: IPropertyReferenceOperation { Property.IsIndexer: false } property } assignment + when isObject(property.Instance) && IsEntityLike(property.Property.ContainingType) && symbols.AttributeNameOf(property.Property) is { } column => + (column, assignment.Value), + ISimpleAssignmentOperation { Target: IPropertyReferenceOperation { Property.IsIndexer: true, Arguments.Length: 1 } indexer } assignment + when IsAttributes(indexer.Instance) => + (Key(indexer.Arguments[0].Value)?.ToLowerInvariant(), assignment.Value), + IInvocationOperation { TargetMethod.Name: "Add", Arguments.Length: 2 } add + when Unwrap(add.Instance) is IPropertyReferenceOperation { Property.Name: SdkNames.Attributes } attributes && isObject(attributes.Instance) => + (Key(add.Arguments[0].Value)?.ToLowerInvariant(), add.Arguments[1].Value), + _ => null, + }; + } + + /// + /// The tables an early-bound lookup property, such as contact.ParentCustomerId, can refer to by the + /// metadata; empty when the property isn't a lookup the metadata knows. + /// + private IReadOnlyCollection LookupTargets(IPropertyReferenceOperation property) + { + if (lookups is null || !symbols.Is(property.Type, symbols.EntityReference)) return []; + if (symbols.AttributeNameOf(property.Property) is not { } column) return []; + return symbols.LogicalNameOf(property.Instance?.Type ?? property.Property.ContainingType) is { } table ? lookups.TargetsOf(table, column) : []; + } + + private static string? Key(IOperation operation) => operation.ConstantValue is { HasValue: true, Value: string key } ? key : null; + + private TableResolution EntityOrRecords(IOperation value) => IsEntityLike(Unwrap(value)?.Type) ? Entity(value) : Records(value); + + private TableResolution EntityOrReferences(IOperation value) => IsEntityLike(Unwrap(value)?.Type) ? Entity(value) : EntityReferences(value); + + /// + /// The collection whose EntityCollection.Entities reads. + /// + private IOperation? EntitiesOf(IPropertyReferenceOperation property) => + property is { Property.Name: SdkNames.Entities, Instance: { } records } && symbols.Is(property.Property.ContainingType, symbols.EntityCollection) ? records : null; + + // How a collection is read, the same for records, entity references, requests and the lookups on records: the + // values put into it of a type it accepts, each an element or a collection of them, read with resolve + + /// + /// What a collection is created with: the collections passed to its constructor, the values its initializer + /// adds, and the Entities it sets. + /// + private TableResolution Filled(IObjectCreationOperation creation, Func accepts, Func resolve) + { + var added = creation.Initializer?.Initializers.OfType().SelectMany(add => add.Arguments) ?? []; + var entities = creation.Initializer is { } initializer ? Inside(initializer).SelectMany(node => SetMember(node, IsImplicitReceiver, SdkNames.Entities)) : []; + return Union(creation.Arguments.Concat(added).Select(a => a.Value).Concat(entities).Where(v => Accepts(accepts, v)), resolve); + } + + /// + /// What adds to the local or to its Entities; + /// null when it adds nothing. + /// + private TableResolution? Added(IOperation node, ILocalSymbol symbol, Func accepts, Func resolve) => + node is IInvocationOperation { TargetMethod.Name: "Add" or "AddRange" or "Insert" or "InsertRange" } add + && (IsLocal(add.Instance, symbol) || (Unwrap(add.Instance) is IPropertyReferenceOperation { Property.Name: SdkNames.Entities } entities && IsLocal(entities.Instance, symbol))) + ? Union(add.Arguments.Select(a => a.Value).Where(v => Accepts(accepts, v)), resolve) + : null; + + private static bool Accepts(Func accepts, IOperation value) => accepts(value.Type) || accepts(Unwrap(value)?.Type); + + /// + /// What a framework call such as ToList, Chunk or Select passes on from the collections it + /// is given: the receiver and arguments of a type , read with + /// , and the values returned by lambdas, read with . + /// null when nothing is passed on. + /// + private TableResolution? Passthrough( + IInvocationOperation invocation, + Func accepts, + Func resolve, + Func resolveReturned) + { + List? result = null; + var sources = invocation.Instance is { } instance ? invocation.Arguments.Select(a => a.Value).Prepend(instance) : invocation.Arguments.Select(a => a.Value); + foreach (var source in sources) + { + if (Unwrap(source) is IDelegateCreationOperation { Target: IAnonymousFunctionOperation lambda } && accepts(lambda.Symbol.ReturnType)) + { + foreach (var returned in Returned(lambda)) (result ??= []).Add(resolveReturned(returned)); + } + else if (accepts(source.Type) || accepts(Unwrap(source)?.Type)) + { + (result ??= []).Add(resolve(source)); + } + } + return result is null ? null : TableResolution.Union(result); + } + + /// + /// The values a lambda returns, without those of lambdas inside it. + /// + private static IEnumerable Returned(IAnonymousFunctionOperation lambda) => + Inside(lambda.Body).OfType().Where(r => r.ReturnedValue is not null).Select(r => r.ReturnedValue!); + + /// + /// The collection whose elements a lambda parameter receives, such as accounts for a in + /// accounts.Select(a => …); null when the lambda isn't passed to a framework call. + /// + private static IOperation? LambdaSource(IParameterReferenceOperation parameter) + { + if (parameter.Parameter is not { Ordinal: 0, ContainingSymbol: IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } lambdaSymbol }) return null; + + var lambda = parameter.Parent; + while (lambda is not null && !(lambda is IAnonymousFunctionOperation function && SymbolEqualityComparer.Default.Equals(function.Symbol, lambdaSymbol))) lambda = lambda.Parent; + if (lambda?.Parent is not IDelegateCreationOperation { Parent: IArgumentOperation { Parent: IInvocationOperation invocation } argument } || !IsSystemCall(invocation)) return null; + + return invocation.Instance ?? invocation.Arguments.FirstOrDefault(a => a != argument && a.Parameter?.Ordinal == 0)?.Value; + } + + private static IEnumerable CollectionElements(IOperation operation) => operation switch + { + IArrayCreationOperation { Initializer: { } initializer } => initializer.ElementValues, + ICollectionExpressionOperation collection => collection.Elements.Select(e => e is ISpreadOperation spread ? spread.Operand : e), + _ => [], + }; + + /// + /// The tables of the elements of a collection that a loop variable iterates. + /// + private TableResolution EntityElements(IOperation collection) => Unwrap(collection) switch + { + IArrayCreationOperation or ICollectionExpressionOperation => Elements(collection), + var op when IsRecordsLike(op?.Type) => Records(op), + var op => Entity(op), + }; + + private TableResolution Elements(IOperation? operation) + { + var op = Unwrap(operation); + if (op is IArrayCreationOperation { Initializer: not null } or ICollectionExpressionOperation) return Union(CollectionElements(op), EntityOrRecords); + return IsRecordsLike(op?.Type) && !symbols.Is(op?.Type, symbols.EntityReferenceCollection) ? Records(op) : Unknown(op, "related records", TableShape.EntityReferences); + } + + /// + /// The possible texts of a FetchXML string. Runtime parts become , so the structure around + /// them can still be parsed. Values that are runtime as a whole are reported in . + /// + private List Templates(IOperation? operation, bool topLevel, List failures, bool includeLinks = true) + { + var op = Unwrap(operation); + if (op is null) + { + failures.Add(TableResolution.Unresolved("FetchXML argument is missing")); + return []; + } + + if (op.ConstantValue is { HasValue: true, Value: string constant }) return [constant]; + + switch (op) + { + case IInterpolatedStringOperation interpolated: + { + var builder = new StringBuilder(); + foreach (var part in interpolated.Parts) + { + builder.Append(part switch + { + IInterpolatedStringTextOperation text => text.Text.ConstantValue.Value as string, + IInterpolationOperation { Expression.ConstantValue: { HasValue: true, Value: var value } } => value?.ToString(), + _ => Hole.ToString(), + }); + } + return [builder.ToString()]; + } + + case IBinaryOperation { OperatorKind: BinaryOperatorKind.Add } binary when op.Type?.SpecialType == SpecialType.System_String: + { + var left = Templates(binary.LeftOperand, topLevel: false, failures); + var right = Templates(binary.RightOperand, topLevel: false, failures); + if (left.Count * right.Count > MaxTemplates) + { + failures.Add(TableResolution.Unresolved("FetchXML is built in too many ways to analyze")); + return []; + } + return left.SelectMany(l => right.Select(r => l + r)).ToList(); + } + + case ILocalReferenceOperation local: + { + // A local built from itself, such as links = links + "...", repeats a part the analysis can't count + if (!_visiting.Add(local.Local)) return topLevel ? [] : [Hole.ToString()]; + try + { + var templates = new List(); + foreach (var value in LocalValues(local.Local, Root(local), Failed(failures))) + { + if (value.IsLoopCollection) failures.Add(TableResolution.Unresolved(LoopVariable(local.Local))); + else templates.AddRange(Templates(value.Operation, topLevel, failures, includeLinks)); + } + return templates.Distinct(StringComparer.Ordinal).ToList(); + } + finally + { + _visiting.Remove(local.Local); + } + } + + case { } when Branches(op) is { } branches: + return branches.SelectMany(b => Templates(b, topLevel, failures, includeLinks)).ToList(); + + default: + if (!topLevel) return [Hole.ToString()]; + failures.Add(Unknown(op, "FetchXML", includeLinks ? TableShape.Fetch : TableShape.FetchMainTable)); + return []; + } + } + + private static TableResolution ParseFetch(string template, bool includeLinks) + { + // Every string passed to a method is read as FetchXML too, so plain text is turned away before it can throw + XDocument document; + try + { + if (!template.TrimStart(XmlWhitespace).StartsWith("<", StringComparison.Ordinal)) return TableResolution.Unresolved(NotFetch); + document = XDocument.Parse(template); + } + catch (XmlException) + { + return TableResolution.Unresolved(NotFetch); + } + + var result = new List(); + foreach (var element in document.Descendants().Where(e => e.Name.LocalName == "entity" || (includeLinks && e.Name.LocalName == "link-entity"))) + { + var name = (string?)element.Attribute("name"); + result.Add( + string.IsNullOrEmpty(name) ? TableResolution.Unresolved("FetchXML entity has no name") + : name!.IndexOf(Hole) >= 0 ? TableResolution.Unresolved("FetchXML table name is computed at runtime") + : TableResolution.Table(name)); + } + return TableResolution.Union(result).OrUnresolved("FetchXML has no entity element"); + } + + /// + /// Resolves a local from every value assigned to it in its method. The union is taken, because the analysis + /// doesn't follow control flow. sees every operation in the method, to pick up + /// changes made through the local, such as entity.LogicalName = "account". A + /// local reports nothing for assignments it can't follow, as for any value from an unknown source. + /// + private TableResolution FromLocal( + ILocalReferenceOperation reference, + Func resolve, + Func? resolveElements = null, + Func? use = null, + bool silent = false) + { + var local = reference.Local; + if (!_visiting.Add(local)) return TableResolution.Empty; + try + { + var root = Root(reference); + var result = new List(); + foreach (var value in LocalValues(local, root, silent ? null : Failed(result))) + { + if (!value.IsLoopCollection) + { + result.Add(resolve(value.Operation)); + } + else + { + result.Add(resolveElements is not null + ? resolveElements(value.Operation) + : TableResolution.Unresolved(LoopVariable(local))); + } + } + + if (use is not null) + { + foreach (var node in root.DescendantsAndSelf()) + { + if (use(node, local) is { } resolution) result.Add(resolution); + } + } + return TableResolution.Union(result); + } + finally + { + _visiting.Remove(local); + } + } + + /// + /// Links that can't be tied to a query local are not followed yet. Any of them in the method makes the + /// query's linked tables unknown, so they are reported instead of missed. + /// + private TableResolution NestedLinks(IOperation query) + { + var hasNestedLinks = Root(query).DescendantsAndSelf().Any(node => node switch + { + IPropertyReferenceOperation { Property.Name: SdkNames.LinkEntities } => true, + IInvocationOperation { TargetMethod.Name: SdkNames.AddLink } call => symbols.Is(call.TargetMethod.ContainingType, symbols.LinkEntity), + IObjectCreationOperation creation => symbols.Is(creation.Type, symbols.LinkEntity), + _ => false, + }); + return hasNestedLinks ? TableResolution.Unresolved(NestedLinksReason) : TableResolution.Empty; + } + + private TableResolution? AssignedMember(IObjectOrCollectionInitializerOperation? initializer, string member, Func resolve) + { + var assignments = initializer?.Initializers + .OfType() + .Where(a => a.Target is IPropertyReferenceOperation property && property.Property.Name == member) + .ToList(); + + return assignments is { Count: > 0 } ? Union(assignments.Select(a => a.Value), resolve) : null; + } + + private static IArgumentOperation? FirstStringArgument(IOperation call) + { + var arguments = call switch + { + IObjectCreationOperation creation => creation.Arguments, + IInvocationOperation invocation => invocation.Arguments, + _ => [], + }; + return arguments.FirstOrDefault(a => a.Parameter is { Ordinal: 0, Type.SpecialType: SpecialType.System_String }); + } + + /// + /// An entity, not a reference to one, so its columns can be set. + /// + private bool IsEntity(IOperation value) => IsEntityLike(Unwrap(value)?.Type) && !symbols.Is(Unwrap(value)?.Type, symbols.EntityReference); + + private bool IsEntityOrReference(ITypeSymbol? type) => + symbols.Is(type, symbols.Entity) || symbols.Is(type, symbols.EntityReference); + + /// + /// An entity or reference, or a type parameter constrained to one. + /// + private bool IsEntityOrRecords(ITypeSymbol? type) => IsEntityLike(type) || IsRecordsLike(type); + + private bool IsEntityLike(ITypeSymbol? type) => + IsEntityOrReference(type) || (type is ITypeParameterSymbol typeParameter && typeParameter.ConstraintTypes.Any(IsEntityLike)); + + /// + /// A collection of entities or references: an EntityCollection, or a list or array of them. + /// + private bool IsRecordsLike(ITypeSymbol? type, int depth = 0) => + symbols.Is(type, symbols.EntityCollection) || symbols.Is(type, symbols.EntityReferenceCollection) + || (Nested(type, depth) is { } element && (IsEntityLike(element) || IsRecordsLike(element, depth + 1))); + + /// + /// A request, or a collection of requests, of collections of them, and so on. + /// + private bool IsRequestLike(ITypeSymbol? type, int depth = 0) => + symbols.Is(type, symbols.OrganizationRequest) + || (Nested(type, depth) is { } element && IsRequestLike(element, depth + 1)); + + /// + /// The element type of a collection nested levels deep. Types that are collections of + /// themselves, such as JToken, stop at . + /// + private static ITypeSymbol? Nested(ITypeSymbol? type, int depth) => + depth < MaxNesting && type?.SpecialType != SpecialType.System_String ? ElementType(type) : null; + + private static ITypeSymbol? ElementType(ITypeSymbol? type) => type switch + { + null => null, + IArrayTypeSymbol array => array.ElementType, + INamedTypeSymbol named when named.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T => named.TypeArguments[0], + _ => type.AllInterfaces.FirstOrDefault(i => i.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T)?.TypeArguments[0], + }; + + private bool IsTableQuery(ITypeSymbol? type) => + symbols.Is(type, symbols.QueryExpression) || symbols.Is(type, symbols.QueryByAttribute); + + /// + /// The values a conditional or coalesce can take; null for any other value. + /// + private static IOperation[]? Branches(IOperation? operation) => operation switch + { + IConditionalOperation { WhenFalse: { } whenFalse } conditional => [conditional.WhenTrue, whenFalse], + ICoalesceOperation coalesce => [coalesce.Value, coalesce.WhenNull], + _ => null, + }; + + private static TableResolution Union(IEnumerable values, Func resolve) => + TableResolution.Union(values.Select(resolve)); + + private static Action Failed(List failures) => reason => failures.Add(TableResolution.Unresolved(reason)); + + private static string Indexer(IPropertyReferenceOperation indexer) + { + var target = Unwrap(indexer.Instance) switch + { + IPropertyReferenceOperation property => property.Property.Name, + ILocalReferenceOperation local => local.Local.Name, + IParameterReferenceOperation parameter => parameter.Parameter.Name, + IFieldReferenceOperation field => field.Field.Name, + _ => "an indexer", + }; + var arguments = indexer.Arguments.Select(a => Key(a.Value) is { } key ? $"\"{key}\"" : "…"); + return $"{target}[{string.Join(", ", arguments)}]"; + } + + /// + /// A value the resolver can't follow here. A method parameter becomes a slot for the call graph to fill in, and + /// a call to a method in the solution is resolved from what that method returns. + /// + /// + /// A value reports nothing where it stays unknown: a request read for one privilege, + /// whose reason is reported once, under . + /// + private TableResolution Unknown(IOperation? operation, string what, TableShape shape, bool silent = false) + { + var reason = silent ? "" : Describe(operation, what); + return operation switch + { + IParameterReferenceOperation { Parameter.ContainingSymbol: IMethodSymbol method } parameter => + TableResolution.Slot(new TableSlot(Nodes.Id(method), parameter.Parameter.Ordinal, shape, reason)), + IInvocationOperation invocation when calls?.Invoke(invocation) is { } call => + TableResolution.Returned(new ReturnedTables(call, shape, reason)), + _ => silent ? TableResolution.Empty : TableResolution.Unresolved(reason), + }; + } + + private TableResolution UnknownRequest(IOperation? operation, TableShape shape) => + Unknown(operation, "request", shape, silent: shape != TableShape.RequestOther); + + /// + /// A type parameter of a generic method becomes a slot for the type argument at each call site, and one of the + /// method's type a slot for the type argument of the receiver. + /// + private TableResolution TypeParameter(ITypeParameterSymbol typeParameter) + { + var reason = $"table depends on type parameter '{typeParameter.Name}'"; + if (typeParameter.DeclaringMethod is { } declaringMethod) + { + return TableResolution.Slot(new TableSlot(Nodes.Id(declaringMethod), TableSlot.TypeParameterOrdinal(typeParameter.Ordinal), TableShape.Entity, reason)); + } + + var ordinal = method is null ? -1 : Nodes.TypeParameters(method.ContainingType).IndexOf(typeParameter.OriginalDefinition); + return ordinal >= 0 + ? TableResolution.Slot(new TableSlot(Nodes.Id(method!), TableSlot.TypeArgumentOrdinal(ordinal), TableShape.Entity, reason)) + : TableResolution.Unresolved(reason); + } + + private static string Describe(IOperation? operation, string what) => operation switch + { + IParameterReferenceOperation parameter => $"{what} comes from parameter '{parameter.Parameter.Name}'", + IFieldReferenceOperation field => $"{what} comes from field '{field.Field.Name}'", + IPropertyReferenceOperation { Property.IsIndexer: true } indexer => $"{what} comes from {Indexer(indexer)}", + IPropertyReferenceOperation property => $"{what} comes from property '{property.Property.Name}'", + ITypeParameterObjectCreationOperation creation => $"table depends on type parameter '{creation.Type?.Name}'", + IInvocationOperation invocation => $"{what} is returned by '{invocation.TargetMethod.Name}'", + { ConstantValue: { HasValue: true, Value: null } } => $"{what} is null", + _ => $"{what} is computed at runtime", + }; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/XrmSymbols.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/XrmSymbols.cs new file mode 100644 index 00000000..8b1a590f --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Extraction/XrmSymbols.cs @@ -0,0 +1,202 @@ +using System.Collections.Concurrent; +using Microsoft.CodeAnalysis; + +namespace XrmMockup.PermissionAnalyzer.Core.Extraction; + +/// +/// The Dataverse SDK types the extractor recognises, looked up once per compilation. +/// +internal sealed class XrmSymbols +{ + // Attributes are read for every early-bound type and column used, which is the same few over and over + private readonly ConcurrentDictionary _logicalNames = new(SymbolEqualityComparer.Default); + private readonly ConcurrentDictionary _attributeNames = new(SymbolEqualityComparer.Default); + + private XrmSymbols(Compilation compilation, INamedTypeSymbol organizationService) + { + var services = new[] + { + organizationService, + compilation.GetTypeByMetadataName("Microsoft.PowerPlatform.Dataverse.Client.IOrganizationServiceAsync"), + compilation.GetTypeByMetadataName("Microsoft.PowerPlatform.Dataverse.Client.IOrganizationServiceAsync2"), + } + .Where(s => s is not null) + .Cast() + .ToList(); + + // Async2 extends Async, so a method declared on any base interface counts as a service method. + ServiceInterfaces = services.SelectMany(s => s.AllInterfaces.Prepend(s)).Distinct(SymbolEqualityComparer.Default).ToList(); + Entity = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Entity"); + EntityReference = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.EntityReference"); + EntityReferenceCollection = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.EntityReferenceCollection"); + EntityCollection = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.EntityCollection"); + QueryBase = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Query.QueryBase"); + QueryExpression = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Query.QueryExpression"); + QueryByAttribute = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Query.QueryByAttribute"); + FetchExpression = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Query.FetchExpression"); + LinkEntity = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Query.LinkEntity"); + OrganizationRequest = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.OrganizationRequest"); + EntityLogicalNameAttribute = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute"); + AttributeLogicalNameAttribute = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute"); + Plugin = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.IPlugin"); + OrganizationServiceFactory = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.IOrganizationServiceFactory"); + ExecutionContext = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.IExecutionContext"); + OrganizationServiceContext = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.Client.OrganizationServiceContext"); + Queryable = compilation.GetTypeByMetadataName("System.Linq.IQueryable`1"); + } + + /// + /// IOrganizationService and, when referenced, the Dataverse client's async service interfaces. + /// + public IReadOnlyList ServiceInterfaces { get; } + + public INamedTypeSymbol? Entity { get; } + public INamedTypeSymbol? EntityReference { get; } + public INamedTypeSymbol? EntityReferenceCollection { get; } + public INamedTypeSymbol? EntityCollection { get; } + public INamedTypeSymbol? QueryBase { get; } + public INamedTypeSymbol? QueryExpression { get; } + public INamedTypeSymbol? QueryByAttribute { get; } + public INamedTypeSymbol? FetchExpression { get; } + public INamedTypeSymbol? LinkEntity { get; } + public INamedTypeSymbol? OrganizationRequest { get; } + public INamedTypeSymbol? EntityLogicalNameAttribute { get; } + public INamedTypeSymbol? AttributeLogicalNameAttribute { get; } + public INamedTypeSymbol? Plugin { get; } + public INamedTypeSymbol? OrganizationServiceFactory { get; } + public INamedTypeSymbol? ExecutionContext { get; } + public INamedTypeSymbol? OrganizationServiceContext { get; } + public INamedTypeSymbol? Queryable { get; } + + /// + /// Returns null when the compilation doesn't reference the Dataverse SDK, so it can't make service calls. + /// + public static XrmSymbols? Create(Compilation compilation) + { + var organizationService = compilation.GetTypeByMetadataName("Microsoft.Xrm.Sdk.IOrganizationService"); + return organizationService is null ? null : new XrmSymbols(compilation, organizationService); + } + + public bool Is(ITypeSymbol? type, INamedTypeSymbol? expected) + { + if (expected is null) return false; + for (var current = type; current is not null; current = current.BaseType) + { + if (SymbolEqualityComparer.Default.Equals(current.OriginalDefinition, expected)) return true; + } + return false; + } + + /// + /// Whether is, or implements, , an interface. + /// + public static bool Implements(ITypeSymbol? type, INamedTypeSymbol? expected) => + type is not null && expected is not null + && (SymbolEqualityComparer.Default.Equals(type.OriginalDefinition, expected) + || type.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i.OriginalDefinition, expected))); + + /// + /// Whether values of are organization services, so the identity they run as is tracked. + /// + public bool IsService(ITypeSymbol? type) => + type is not null && (ServiceInterfaces.Any(s => Implements(type, s)) || IsContext(type)); + + /// + /// Whether is an OrganizationServiceContext, such as a generated context. A context + /// runs as the organization service it is created with, so it is tracked as a service. + /// + public bool IsContext(ITypeSymbol? type) => Is(type, OrganizationServiceContext); + + /// + /// The OrganizationServiceContext method is, such as CreateQuery or + /// AddObject, or null when it is another method. + /// + public string? ContextOperation(IMethodSymbol method) => + method.MethodKind == MethodKind.Ordinary + && OrganizationServiceContext is not null + && SymbolEqualityComparer.Default.Equals(method.ContainingType?.OriginalDefinition, OrganizationServiceContext) + ? method.Name + : null; + + /// + /// The record type of a query property of a context, such as Account for a generated + /// IQueryable<Account> AccountSet, or null when is another property. + /// + public ITypeSymbol? QueryElement(IPropertySymbol property) => + !property.IsStatic + && !property.IsIndexer + && IsContext(property.ContainingType) + && property.Type is INamedTypeSymbol { TypeArguments.Length: 1 } type + && SymbolEqualityComparer.Default.Equals(type.OriginalDefinition, Queryable) + ? type.TypeArguments[0] + : null; + + /// + /// The table of an early-bound type, read from [EntityLogicalName] on the type or a base type. + /// + public string? LogicalNameOf(ITypeSymbol? type) => type is null ? null : _logicalNames.GetOrAdd(type, NewLogicalName); + + private string? NewLogicalName(ISymbol type) + { + for (var current = type as ITypeSymbol; current is not null; current = current.BaseType) + { + if (NameArgument(current, EntityLogicalNameAttribute) is { } name) return name; + } + return null; + } + + /// + /// The column of an early-bound property, read from [AttributeLogicalName]. + /// + public string? AttributeNameOf(IPropertySymbol property) => + _attributeNames.GetOrAdd(property, p => NameArgument(p, AttributeLogicalNameAttribute)); + + /// + /// The name given to on , its only constructor argument. + /// + private static string? NameArgument(ISymbol symbol, INamedTypeSymbol? attributeType) => + attributeType is null + ? null + : symbol.GetAttributes() + .Where(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeType) && a.ConstructorArguments.Length == 1) + .Select(a => a.ConstructorArguments[0].Value as string) + .FirstOrDefault(name => name is not null); + + /// + /// The service operation a method performs (Create, RetrieveMultiple, …), or null when + /// the method is not an organization service method or an implementation of one. + /// + public string? ServiceOperation(IMethodSymbol method) + { + if (!IsServiceMethod(method)) return null; + + var name = method.Name; + if (name.EndsWith("Async", StringComparison.Ordinal)) name = name.Substring(0, name.Length - "Async".Length); + return name; + } + + private bool IsServiceMethod(IMethodSymbol method) + { + var type = method.ContainingType; + if (type is null) return false; + + if (ServiceInterfaces.Contains(type.OriginalDefinition, SymbolEqualityComparer.Default)) return true; + + // A class implementing the service, such as ServiceClient or a wrapper + if (!type.AllInterfaces.Any(i => ServiceInterfaces.Contains(i.OriginalDefinition, SymbolEqualityComparer.Default))) return false; + + foreach (var serviceInterface in ServiceInterfaces) + { + foreach (var member in serviceInterface.GetMembers().OfType()) + { + var implementation = type.FindImplementationForInterfaceMember(member); + if (SymbolEqualityComparer.Default.Equals(implementation, method) + || SymbolEqualityComparer.Default.Equals(implementation, method.OriginalDefinition)) + { + return true; + } + } + } + return false; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/CallGraph.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/CallGraph.cs new file mode 100644 index 00000000..0ffb17d5 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/CallGraph.cs @@ -0,0 +1,57 @@ +namespace XrmMockup.PermissionAnalyzer.Core.Graph; + +/// +/// The summaries of every compilation in the analysis, merged by id. +/// +internal sealed class CallGraph +{ + public Dictionary Nodes { get; } = new(StringComparer.Ordinal); + + public Dictionary Types { get; } = new(StringComparer.Ordinal); + + /// + /// Dependency injection registrations: implementation types by service type. + /// + public Dictionary> Registrations { get; } = new(StringComparer.Ordinal); + + /// + /// Adds the summaries of another compilation. A node or type that both have, such as code compiled for two + /// target frameworks, is merged. + /// + public void Merge(CallGraph other) + { + foreach (var node in other.Nodes.Values) + { + if (Nodes.TryGetValue(node.Id, out var existing)) existing.Merge(node); + else Nodes.Add(node.Id, node); + } + + foreach (var type in other.Types.Values) + { + if (!Types.ContainsKey(type.Id)) Types.Add(type.Id, type); + } + + foreach (var registration in other.Registrations) + { + foreach (var implementation in registration.Value) Register(registration.Key, implementation); + } + } + + public void Register(string service, string implementation) + { + if (!Registrations.TryGetValue(service, out var implementations)) + { + implementations = new SortedSet(StringComparer.Ordinal); + Registrations.Add(service, implementations); + } + implementations.Add(implementation); + } + + /// + /// Types in the solution that an object of can be at runtime, sorted. + /// + public IEnumerable ConcreteTypes(string type) => + Types.Values + .Where(t => !t.IsAbstract && (t.Id == type || t.Ancestors.Contains(type, StringComparer.Ordinal))) + .OrderBy(t => t.Id, StringComparer.Ordinal); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Cascades.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Cascades.cs new file mode 100644 index 00000000..1442a64e --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Cascades.cs @@ -0,0 +1,189 @@ +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Graph; + +/// +/// A plugin step or custom API that runs when an operation fires its message. are +/// the columns an Update step runs for, or null when it runs on every update. is +/// null for a step from the metadata whose plugin code isn't loaded. is set for a +/// step that runs asynchronously; for the code of a custom API, which no bypass parameter +/// skips. names a workflow from the metadata, which runs like a step but whose steps aren't +/// analyzed. +/// +internal sealed record CascadeStep( + string Id, + string Message, + string? Table, + string? ImpersonatingUserId, + IReadOnlyList? FilteredAttributes, + EntryCandidate? Code, + bool Asynchronous = false, + bool IsCustomApi = false, + string? Workflow = null); + +/// +/// An evaluation with the hits of every step its operations fire, and the ids of those steps, sorted. +/// +internal sealed record CascadeResult(EvaluationResult Result, IReadOnlyList Fired); + +/// +/// Expands an evaluation with the plugin steps, custom APIs and workflows its operations fire, and the steps those +/// fire in turn, as Dataverse runs them in the request pipeline. A fired step runs as the identity of the operation that +/// fired it, unless it impersonates. Each step is expanded once per identity and basis, which also stops cycles. +/// An operation on an unknown table only runs the steps without a table; the others are reported as unresolved. +/// An update runs an Update step filtered on columns when it sets one of them, and, with the basis +/// , when the columns it sets aren't all known. A request with a bypass +/// parameter doesn't run the plugin steps it bypasses. +/// +internal sealed class Cascades(CallGraph graph, IEnumerable steps, Func context) +{ + private readonly IReadOnlyList _steps = steps.OrderBy(s => s.Id, StringComparer.Ordinal).ToList(); + private readonly Dictionary<(string, RunsAs), EvaluationResult> _evaluations = []; + + /// + /// with everything it fires. Pass the step being expanded as , + /// so it doesn't fire itself again under the same identity. + /// + public CascadeResult Expand(EvaluationResult result, string? self = null, RunsAs? caller = null) + { + if (_steps.Count == 0 || result.Triggers.Count == 0) return new CascadeResult(result, []); + + var expanded = new EvaluationResult { Truncated = result.Truncated }; + Copy(result, expanded, [], RequirementBasis.Direct); + + var fired = new SortedSet(StringComparer.Ordinal); + var done = new HashSet<(string, RunsAs, RequirementBasis)>(); + if (self is not null && caller is not null) done.Add((self, caller, RequirementBasis.Direct)); + + // Breadth first, so the first path to a step is the shortest + var queue = new Queue<(EvaluationResult Result, RequirementBasis Basis)>(); + queue.Enqueue((result, RequirementBasis.Direct)); + while (queue.Count > 0) + { + var (current, currentBasis) = queue.Dequeue(); + var triggers = current.Triggers + .GroupBy(t => (Message: t.Message.ToLowerInvariant(), Table: t.Table?.ToLowerInvariant(), t.RunsAs, t.Basis, Columns: t.Columns is null ? null : string.Join(",", t.Columns), t.Bypass)) + .Select(g => g.First()); + foreach (var trigger in triggers) + { + if (trigger.Table == TriggerHit.AnyTable && Unmatched(trigger) is { Count: > 0 } unmatched) + { + expanded.Unresolved.Add(new UnresolvedHit( + trigger.Message, + [], + $"may fire any of {unmatched.Count} {trigger.Message} steps, because its table isn't known", + trigger.RunsAs, + trigger.Source)); + } + + foreach (var (step, filterBasis) in Matching(trigger)) + { + fired.Add(step.Id); + var runsAs = step.ImpersonatingUserId is { } user ? RunsAs.User(user) : trigger.RunsAs; + var basis = RequirementBases.Max(RequirementBases.Max(currentBasis, trigger.Basis), filterBasis); + if (!done.Add((step.Id, runsAs, basis))) continue; + + var table = trigger.Table is null ? trigger.Message : $"{trigger.Message} {trigger.Table}"; + var path = trigger.Source.Path.Concat([table, step.Id]).ToList(); + if (step.Code is not { } code) + { + expanded.Unresolved.Add(new UnresolvedHit( + trigger.Message, + [], + step.Workflow is { } workflow + ? RequestReasons.Workflow(workflow, !step.Asynchronous) + : $"fires plugin step {step.Id}, whose code isn't analyzed", + runsAs, + new RequirementSource(trigger.Source.Location, path))); + continue; + } + + var evaluation = Evaluate(code, runsAs); + Copy(evaluation, expanded, path, basis); + expanded.Truncated |= evaluation.Truncated; + queue.Enqueue((Prefixed(evaluation, path), basis)); + } + } + } + + return new CascadeResult(expanded, fired.ToList()); + } + + /// + /// The steps registered for the trigger's message on its table, with the basis their filter gives. A step + /// without a table runs on every table, so it is also the only step a trigger on an unknown table is known to + /// run. Steps the trigger bypasses don't run. + /// + private IEnumerable<(CascadeStep Step, RequirementBasis Basis)> Matching(TriggerHit trigger) + { + foreach (var step in _steps) + { + if (!string.Equals(step.Message, trigger.Message, StringComparison.OrdinalIgnoreCase)) continue; + if (step.Table is not null && !string.Equals(step.Table, trigger.Table, StringComparison.OrdinalIgnoreCase)) continue; + if (Bypassed(step, trigger.Bypass)) continue; + + // As in XrmMockup, a filter applies to Update only + if (step.FilteredAttributes is not { Count: > 0 } filter || !Trigger.Filters(step.Message)) + { + yield return (step, RequirementBasis.Direct); + } + else if (trigger.Columns is null) + { + yield return (step, RequirementBasis.FilterUnknown); + } + else if (trigger.Columns.Intersect(filter, StringComparer.OrdinalIgnoreCase).Any()) + { + yield return (step, RequirementBasis.Direct); + } + } + } + + /// + /// The steps of the trigger's message that run on one table, which a trigger on an unknown table may or may not + /// run. Firing them all would include the privileges of every such step in the solution, so they are reported + /// instead. + /// + private List Unmatched(TriggerHit trigger) => + _steps.Where(s => s.Table is not null && string.Equals(s.Message, trigger.Message, StringComparison.OrdinalIgnoreCase) && !Bypassed(s, trigger.Bypass)).ToList(); + + private static bool Bypassed(CascadeStep step, PluginBypass bypass) => + !step.IsCustomApi && (bypass & (step.Asynchronous ? PluginBypass.Asynchronous : PluginBypass.Synchronous)) != 0; + + private EvaluationResult Evaluate(EntryCandidate code, RunsAs runsAs) + { + if (!_evaluations.TryGetValue((code.Id, runsAs), out var result)) + { + result = new Evaluator(graph, context(code, runsAs)).Evaluate(code.Handlers); + _evaluations.Add((code.Id, runsAs), result); + } + return result; + } + + /// + /// Adds the hits of to , behind and with at + /// most as their basis. + /// + private static void Copy(EvaluationResult from, EvaluationResult to, IReadOnlyList path, RequirementBasis basis) + { + foreach (var hit in from.Requirements) to.Requirements.Add(hit with { Basis = RequirementBases.Max(hit.Basis, basis), Source = Prefix(hit.Source, path) }); + foreach (var hit in from.Unresolved) to.Unresolved.Add(hit with { Source = Prefix(hit.Source, path) }); + foreach (var hit in from.Assumptions) to.Assumptions.Add(hit with { Source = Prefix(hit.Source, path) }); + foreach (var hit in from.Globals) to.Globals.Add(hit with { Basis = RequirementBases.Max(hit.Basis, basis), Source = Prefix(hit.Source, path) }); + foreach (var hit in from.Triggers) to.Triggers.Add(hit with { Basis = RequirementBases.Max(hit.Basis, basis), Source = Prefix(hit.Source, path) }); + to.Reached.UnionWith(from.Reached); + } + + /// + /// The triggers of , behind , to expand them in turn. + /// + private static EvaluationResult Prefixed(EvaluationResult result, IReadOnlyList path) + { + var prefixed = new EvaluationResult(); + prefixed.Triggers.AddRange(result.Triggers.Select(t => t with { Source = Prefix(t.Source, path) })); + return prefixed; + } + + private static RequirementSource Prefix(RequirementSource source, IReadOnlyList path) => + path.Count == 0 ? source : source with { Path = [.. path, .. source.Path] }; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Evaluator.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Evaluator.cs new file mode 100644 index 00000000..6585a7fa --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Evaluator.cs @@ -0,0 +1,669 @@ +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Graph; + +/// +/// Who an entry point's code runs as: the caller (or the step's impersonating user), and the identity of +/// services that come from dependency injection. is the table a plugin step is +/// registered on, which the execution context's PrimaryEntityName holds. +/// +internal sealed record EntryContext(RunsAs Caller, Identity Injected, string? PrimaryTable = null); + +/// +/// A resolved identity. says why it was assumed, when it was. +/// +internal sealed record Identity(RunsAs RunsAs, string? Assumption = null) : IComparable +{ + public int CompareTo(Identity? other) + { + if (other is null) return 1; + var result = RunsAs.CompareTo(other.RunsAs); + return result != 0 ? result : string.CompareOrdinal(Assumption, other.Assumption); + } + + public override string ToString() => Assumption is null ? RunsAs.ToString() : $"{RunsAs}~{Assumption}"; +} + +internal sealed record RequirementHit(string Table, Privilege Privilege, RunsAs RunsAs, RequirementBasis Basis, RequirementSource Source); + +internal sealed record UnresolvedHit(string Operation, IReadOnlyList Privileges, string Reason, RunsAs RunsAs, RequirementSource Source); + +internal sealed record AssumptionHit(string Reason, RequirementSource Source); + +/// +/// A privilege not tied to a table, by name, that needs, such as prvBulkDelete for +/// BulkDelete. +/// +internal sealed record GlobalPrivilegeHit(string Operation, string Privilege, RunsAs RunsAs, RequirementBasis Basis, RequirementSource Source); + +/// +/// An operation that fires the plugin steps of on : null for no +/// table, for a table that isn't known. +/// +internal sealed record TriggerHit( + string Message, + string? Table, + RunsAs RunsAs, + RequirementBasis Basis, + RequirementSource Source, + IReadOnlyList? Columns = null, + PluginBypass Bypass = PluginBypass.None) +{ + public const string AnyTable = "*"; +} + +/// +/// What an entry point or method needs, in the order found. +/// +internal sealed class EvaluationResult +{ + public List Requirements { get; } = []; + public List Unresolved { get; } = []; + public List Assumptions { get; } = []; + public List Triggers { get; } = []; + public List Globals { get; } = []; + + /// + /// Every node the evaluation visited. + /// + public HashSet Reached { get; } = new(StringComparer.Ordinal); + + /// + /// Set when the evaluation stopped at , so the result may be incomplete. + /// + public bool Truncated { get; set; } +} + +/// +/// Walks the call graph from an entry point, breadth first, so the first path to an operation is the shortest. +/// Each method is evaluated per call context: the services and tables bound to its parameters and the state of +/// the current object. A method called with the same context again is not walked again. +/// +internal sealed class Evaluator(CallGraph graph, EntryContext entry) +{ + public const int MaxVisits = 10000; + + // How deep services are followed through returns and constructors + private const int MaxDepth = 16; + + // The column a record is created with to set its creation date, which needs GlobalRequirement.OverrideCreatedOnCreatedBy + private const string OverriddenCreatedOn = "overriddencreatedon"; + + private static readonly IReadOnlyDictionary<(string, int), Binding> NoBindings = new Dictionary<(string, int), Binding>(); + + private readonly Dictionary _defaultObjects = new(StringComparer.Ordinal); + private readonly List _constructing = []; + + // The lowest position in _constructing whose default object is missing a part, cut off by a cycle or the depth + // limit, so it isn't memoized + private int _cutAt = int.MaxValue; + private readonly HashSet _returning = new(StringComparer.Ordinal); + + /// + /// Everything reachable from . + /// + public EvaluationResult Evaluate(IEnumerable handlers) + { + var result = new EvaluationResult(); + var queue = new Queue(); + var visited = new HashSet(StringComparer.Ordinal); + + void Enqueue(Frame frame) + { + if (graph.Nodes.ContainsKey(frame.Node) && visited.Add(frame.Key)) queue.Enqueue(frame); + } + + foreach (var handler in handlers) + { + foreach (var start in Start(handler)) Enqueue(start); + } + + var visits = 0; + while (queue.Count > 0) + { + if (++visits > MaxVisits) + { + result.Truncated = true; + break; + } + + var frame = queue.Dequeue(); + var node = graph.Nodes[frame.Node]; + result.Reached.Add(node.Id); + + foreach (var access in node.Accesses) Record(access, frame, result); + + foreach (var lambda in node.Lambdas) + { + if (graph.Nodes.TryGetValue(lambda, out var lambdaNode)) + { + Enqueue(new Frame(lambda, frame.Object, frame.Bindings, frame.Basis, [.. frame.Path, lambdaNode.Display])); + } + } + + foreach (var call in node.Calls) + { + foreach (var (target, state, basis) in Dispatch(call, frame, 0)) + { + if (!graph.Nodes.TryGetValue(target, out var callee)) continue; + var bindings = Bind(call, frame, callee); + Enqueue(new Frame(target, state, bindings, RequirementBases.Max(basis, frame.Basis), [.. frame.Path, callee.Display])); + } + } + } + return result; + } + + /// + /// The operations written directly in , outside any call context. + /// + public EvaluationResult EvaluateAlone(NodeSummary node, string display) + { + var result = new EvaluationResult(); + var state = node.Type is { } type ? DefaultObject(type, 0) : null; + var frame = new Frame(node.Id, state, NoBindings, RequirementBasis.Direct, [display]); + foreach (var access in node.Accesses) Record(access, frame, result); + return result; + } + + private IEnumerable Start(Handler handler) + { + if (handler.ServiceType is { } service) + { + var call = new CallFact(new SourceLocation("", 0, 0), handler.Target, true, ReceiverKind.Other, service, new Dictionary()); + var frame = new Frame(handler.Target, null, NoBindings, RequirementBasis.Direct, []); + foreach (var (target, state, basis) in Dispatch(call, frame, 0)) + { + if (graph.Nodes.TryGetValue(target, out var node)) + { + yield return new Frame(target, state, NoBindings, basis, [node.Display]); + } + } + yield break; + } + + // A virtual method found on a base class, such as IPlugin.Execute implemented in a plugin base class and + // overridden in the plugin, runs the override of the object's type + var method = handler.ObjectType is { } type ? Implementation(type, handler.Target) : handler.Target; + if (!graph.Nodes.TryGetValue(method, out var start)) yield break; + var objectType = handler.ObjectType ?? start.Type; + yield return new Frame(start.Id, objectType is null ? null : DefaultObject(objectType, 0), NoBindings, RequirementBasis.Direct, [start.Display]); + } + + private void Record(AccessFact access, Frame frame, EvaluationResult result) + { + var source = new RequirementSource(access.Source, frame.Path); + var identities = Resolve(access.Service, frame, 0); + if (identities.Count == 0) identities = [Unknown("service is null")]; + + var tables = BindTables(access.Tables, frame, 0); + var privileges = access.Privileges.Distinct().OrderBy(p => p).ToList(); + foreach (var identity in identities) + { + if (identity.Assumption is { } assumption) result.Assumptions.Add(new AssumptionHit(assumption, source)); + + foreach (var table in tables.Tables) + { + foreach (var privilege in access.Privileges) + { + result.Requirements.Add(new RequirementHit(table, privilege, identity.RunsAs, frame.Basis, source)); + } + } + + // Every table a lookup can refer to, where the code doesn't say which + foreach (var table in tables.LookupTargets.Except(tables.Tables, StringComparer.Ordinal)) + { + foreach (var privilege in access.Privileges) + { + result.Requirements.Add(new RequirementHit(table, privilege, identity.RunsAs, RequirementBasis.AllLookupTargets, source)); + } + } + + foreach (var reason in tables.Reasons) + { + result.Unresolved.Add(new UnresolvedHit(access.Operation, privileges, access.ReasonPrefix + reason, identity.RunsAs, source)); + } + + foreach (var global in tables.Globals) + { + result.Globals.Add(new GlobalPrivilegeHit(global.Message, global.Privilege, identity.RunsAs, frame.Basis, source)); + } + foreach (var assumed in tables.Assumptions) result.Assumptions.Add(new AssumptionHit(assumed, source)); + + foreach (var fired in tables.Fired) + { + // The columns set, when all of them are known + var columns = fired.Value.Columns is { Reasons.Count: 0 } set ? set.Tables.ToList() : null; + var bypass = fired.Value.Bypass; + foreach (var table in fired.Value.Tables) result.Triggers.Add(new TriggerHit(fired.Key, table, identity.RunsAs, frame.Basis, source, columns, bypass)); + foreach (var table in fired.Value.LookupTargets.Except(fired.Value.Tables, StringComparer.Ordinal)) + { + result.Triggers.Add(new TriggerHit(fired.Key, table, identity.RunsAs, RequirementBasis.AllLookupTargets, source, columns, bypass)); + } + if (fired.Value.Reasons.Count > 0) result.Triggers.Add(new TriggerHit(fired.Key, TriggerHit.AnyTable, identity.RunsAs, frame.Basis, source, columns, bypass)); + if (fired.Value.Tables.Count == 0 && fired.Value.LookupTargets.Count == 0 && fired.Value.Reasons.Count == 0) result.Triggers.Add(new TriggerHit(fired.Key, null, identity.RunsAs, frame.Basis, source, columns, bypass)); + + // A record created with another creation date, whichever way the date is set + if (fired.Key.Equals(Messages.Create, StringComparison.OrdinalIgnoreCase) && fired.Value.Columns?.Tables.Contains(OverriddenCreatedOn) == true) + { + result.Globals.Add(new GlobalPrivilegeHit(fired.Key, GlobalRequirement.OverrideCreatedOnCreatedBy, identity.RunsAs, frame.Basis, source)); + } + } + } + } + + /// + /// The methods a call can run, with the object each runs on. + /// + private IEnumerable<(string Target, ObjectState? Object, RequirementBasis Basis)> Dispatch(CallFact call, Frame frame, int depth) + { + var basis = frame.Basis; + switch (call.Receiver) + { + case ReceiverKind.None: + return [(call.Target, null, basis)]; + + case ReceiverKind.This when frame.Object is { } current: + return [(call.Virtual ? Implementation(current.Type, call.Target) : call.Target, current, basis)]; + + case ReceiverKind.Created when (call.Creation ?? (IsConstructor(call.Target) ? call : null)) is { } creation: + { + var created = Construct(creation, frame, depth); + return [(call.Virtual ? Implementation(created.Type, call.Target) : call.Target, created, basis)]; + } + } + + // An object of unknown runtime type + var receiverType = call.ReceiverType; + if (!call.Virtual || receiverType is null) + { + return [(call.Target, receiverType is null ? null : DefaultObject(receiverType, depth), basis)]; + } + + if (graph.Registrations.TryGetValue(receiverType, out var registered)) + { + return registered.Select(type => (Implementation(type, call.Target), (ObjectState?)DefaultObject(type, depth), basis)).ToList(); + } + + var candidates = graph.ConcreteTypes(receiverType) + .Select(type => (Target: Implementation(type.Id, call.Target), Object: (ObjectState?)DefaultObject(type.Id, depth))) + .ToList(); + if (candidates.Count == 0) return [(call.Target, DefaultObject(receiverType, depth), basis)]; + + // A virtual method that nothing overrides runs as written + var direct = candidates.All(c => c.Target == call.Target); + return candidates.Select(c => (c.Target, c.Object, direct ? basis : RequirementBasis.AllImplementations)).ToList(); + } + + private string Implementation(string? type, string method) => + type is not null && graph.Types.TryGetValue(type, out var summary) && summary.Implementations.TryGetValue(method, out var implementation) + ? implementation + : method; + + private bool IsConstructor(string node) => graph.Nodes.TryGetValue(node, out var summary) && summary.IsConstructor; + + /// + /// What a call passes to , including the type arguments of the callee's type. A lambda + /// or local function also sees the parameters of the method around it. + /// + private IReadOnlyDictionary<(string, int), Binding> Bind(CallFact call, Frame caller, NodeSummary callee, int depth = 0) + { + var inherit = graph.Nodes.TryGetValue(caller.Node, out var callerNode) && callee.Member == callerNode.Member; + var typeArguments = TypeArguments(call, callee); + if (call.Arguments.Count == 0 && typeArguments is null) + { + return inherit ? caller.Bindings : NoBindings; + } + + var bindings = inherit + ? new Dictionary<(string, int), Binding>(caller.Bindings.ToDictionary(b => b.Key, b => b.Value)) + : new Dictionary<(string, int), Binding>(); + foreach (var argument in call.Arguments) + { + var services = argument.Value.Service is { } origins ? Resolve(origins, caller, depth) : null; + var tables = argument.Value.Tables?.ToDictionary(t => t.Key, t => BindTables(t.Value, caller, depth)); + bindings[(callee.Id, argument.Key)] = new Binding(services, tables); + } + for (var i = 0; i < (typeArguments?.Count ?? 0); i++) + { + if (typeArguments![i] is not { } typeArgument) continue; + var tables = new Dictionary { [TableShape.Entity] = BindTables(typeArgument, caller, depth) }; + bindings[(callee.Id, TableSlot.TypeArgumentOrdinal(i))] = new Binding(null, tables); + } + return bindings; + } + + /// + /// The type arguments of the type that declares : those of the call's receiver when it + /// is that type or derives from it, else those of an ancestor it was called on, such as an interface. One the + /// call doesn't provide is null, so its slot stays unresolved. + /// + private IReadOnlyList? TypeArguments(CallFact call, NodeSummary callee) + { + if (call.TypeArguments is not { } known || callee.Type is not { } type) return null; + if (known.TryGetValue(type, out var direct)) return direct; + if (!graph.Types.TryGetValue(type, out var summary) || summary.AncestorTypeArguments.Count == 0) return null; + + var count = summary.AncestorTypeArguments.Values.SelectMany(p => p).DefaultIfEmpty(-1).Max() + 1; + var result = new TableResolution?[count]; + foreach (var ancestor in summary.AncestorTypeArguments.OrderBy(a => a.Key, StringComparer.Ordinal)) + { + if (!known.TryGetValue(ancestor.Key, out var arguments)) continue; + for (var i = 0; i < ancestor.Value.Count && i < arguments.Count; i++) + { + if (ancestor.Value[i] >= 0) result[ancestor.Value[i]] ??= arguments[i]; + } + } + return result.Any(r => r is not null) ? result : null; + } + + /// + /// Fills in the parameter slots of from the call context, and the values returned by + /// calls from what each method that can run returns. + /// + private TableResolution BindTables(TableResolution tables, Frame frame, int depth) + { + if (tables.IsBound) return tables; + + var result = new List { tables.WithoutContext() }; + foreach (var slot in tables.Slots) + { + if (slot.Method == TableSlot.PrimaryEntity) result.Add(entry.PrimaryTable is { } primary ? TableResolution.Table(primary) : TableResolution.Unresolved(slot.Reason)); + else if (frame.Bindings.TryGetValue((slot.Method, slot.Ordinal), out var binding) && binding.Tables?.TryGetValue(slot.Shape, out var bound) == true) result.Add(bound!); + else if (slot.Reason.Length > 0) result.Add(TableResolution.Unresolved(slot.Reason)); + } + foreach (var returned in tables.Returns) result.Add(Returned(returned, frame, depth + 1)); + foreach (var fired in tables.Fired) + { + var columns = fired.Value.Columns is { } set ? BindTables(set, frame, depth) : null; + result.Add(TableResolution.Fires(fired.Key, BindTables(fired.Value, frame, depth), columns, fired.Value.Bypass)); + } + return TableResolution.Union(result); + } + + private TableResolution Returned(ReturnedTables returned, Frame frame, int depth) + { + if (depth > MaxDepth) + { + CutOff(); + return returned.Reason.Length > 0 ? TableResolution.Unresolved($"{returned.Reason}, through too many calls") : TableResolution.Empty; + } + + var results = new List(); + var cyclic = false; + var found = false; + foreach (var (target, state, _) in Dispatch(returned.Call, frame, depth)) + { + if (!graph.Nodes.TryGetValue(target, out var callee) || !callee.ReturnTables.TryGetValue(returned.Shape, out var tables)) continue; + found = true; + + // A method that returns its own result, directly or through others, adds nothing the other returns don't + var key = target + "\n" + returned.Shape; + if (!_returning.Add(key)) + { + cyclic = true; + continue; + } + try + { + var calleeFrame = new Frame(target, state, Bind(returned.Call, frame, callee, depth), frame.Basis, frame.Path, frame.Injected); + results.Add(BindTables(tables, calleeFrame, depth)); + } + finally + { + _returning.Remove(key); + } + } + var result = TableResolution.Union(results); + + // Requests that need nothing resolve to nothing, so for them only a method that returns none is unknown + if (cyclic || returned.Reason.Length == 0) return result; + if (RequestShapes.IsRequest(returned.Shape)) return found ? result : TableResolution.Unresolved(returned.Reason); + return result.OrUnresolved(returned.Reason); + } + + private IReadOnlyList Resolve(IEnumerable origins, Frame frame, int depth) + { + var result = new SortedSet(); + foreach (var origin in origins) result.UnionWith(Resolve(origin, frame, depth)); + return result.ToList(); + } + + private IEnumerable Resolve(ServiceOrigin origin, Frame frame, int depth) + { + if (depth > MaxDepth) + { + CutOff(); + return [Unknown("service is passed through too many calls")]; + } + + switch (origin) + { + case FixedOrigin { RunsAs.Kind: RunsAsKind.Caller, Initiating: false }: + return [new Identity(entry.Caller)]; + + case FixedOrigin @fixed: + return [new Identity(@fixed.RunsAs)]; + + case ParameterOrigin parameter: + if (frame.Bindings.TryGetValue((parameter.Method, parameter.Ordinal), out var binding) && binding.Services is { } services) return services; + return frame.Injected ? [entry.Injected] : [Unknown($"service comes from parameter '{parameter.Name}'")]; + + case FieldOrigin field: + return Field(field, frame, depth) ?? [Unknown($"service comes from field '{ShortName(field.Field)}'")]; + + case InjectedOrigin: + return [entry.Injected]; + + case ReturnedOrigin returned: + { + var result = new List(); + foreach (var (target, state, _) in Dispatch(returned.Call, frame, depth + 1)) + { + if (!graph.Nodes.TryGetValue(target, out var callee)) continue; + var calleeFrame = new Frame(target, state, Bind(returned.Call, frame, callee, depth + 1), frame.Basis, frame.Path, frame.Injected); + foreach (var value in callee.Returns) result.AddRange(Resolve(value, calleeFrame, depth + 1)); + } + return result.Count > 0 ? result : [Unknown($"service is returned by '{ShortName(returned.Call.Target)}'")]; + } + + case UnknownOrigin unknown: + return [Unknown(unknown.Reason)]; + + default: + return [Unknown("service is computed at runtime")]; + } + } + + private IReadOnlyList? Field(FieldOrigin field, Frame frame, int depth) + { + if (field.OnThis && frame.Object is { } current) + { + if (current.Fields.TryGetValue(field.Field, out var value)) return value; + if (current.Type is { } type && type != field.Type && DefaultObject(type, depth + 1).Fields.TryGetValue(field.Field, out var inherited)) return inherited; + } + return DefaultObject(field.Type, depth + 1).Fields.TryGetValue(field.Field, out var fallback) ? fallback : null; + } + + /// + /// The object a constructor call creates, with the services its constructors store. + /// + private ObjectState Construct(CallFact constructor, Frame caller, int depth) + { + var state = new ObjectState(constructor.ReceiverType); + if (depth > MaxDepth) CutOff(); + else if (graph.Nodes.TryGetValue(constructor.Target, out var node)) + { + RunConstructor(node, Bind(constructor, caller, node, depth), state, caller.Injected, depth + 1); + } + return state.Freeze(); + } + + /// + /// An object made by the host or a dependency injection container: every constructor, with injected + /// parameters. Memoized per type, unless a part of it was cut off. + /// + private ObjectState DefaultObject(string type, int depth) + { + if (_defaultObjects.TryGetValue(type, out var known)) return known; + if (depth > MaxDepth) + { + CutOff(); + return new ObjectState(type).Freeze(); + } + + // An object that needs itself gets an empty one; that is the whole of it for the outer one, but not for the + // objects in between, which only saw the empty one + var cycle = _constructing.IndexOf(type); + if (cycle >= 0) + { + _cutAt = Math.Min(_cutAt, cycle + 1); + return new ObjectState(type).Freeze(); + } + + var level = _constructing.Count; + _constructing.Add(type); + try + { + var state = new ObjectState(type); + var constructors = graph.Types.TryGetValue(type, out var summary) ? summary.Constructors.ToList() : []; + if (constructors.Count == 0) + { + Initialize(type, new Frame("", state, NoBindings, RequirementBasis.Direct, [], true), state, depth + 1); + } + + foreach (var constructor in constructors) + { + if (!graph.Nodes.TryGetValue(constructor, out var node)) continue; + var single = new ObjectState(type); + RunConstructor(node, NoBindings, single, injected: true, depth + 1); + state.Merge(single); + } + + var result = state.Freeze(); + if (_cutAt > level) _defaultObjects[type] = result; + return result; + } + finally + { + _constructing.RemoveAt(level); + if (_cutAt >= level) _cutAt = int.MaxValue; + } + } + + /// + /// Something was left out at the depth limit, so no default object being made is complete. + /// + private void CutOff() + { + if (_constructing.Count > 0) _cutAt = 0; + } + + private void RunConstructor(NodeSummary constructor, IReadOnlyDictionary<(string, int), Binding> bindings, ObjectState state, bool injected, int depth) + { + if (depth > MaxDepth) + { + CutOff(); + return; + } + var frame = new Frame(constructor.Id, state, bindings, RequirementBasis.Direct, [], injected); + + if (constructor.Type is { } type) Initialize(type, frame, state, depth); + + // : base(…) and : this(…) + foreach (var call in constructor.Calls.Where(c => c.Receiver == ReceiverKind.This && IsConstructor(c.Target))) + { + if (graph.Nodes.TryGetValue(call.Target, out var chained) && chained.Id != constructor.Id) + { + RunConstructor(chained, Bind(call, frame, chained, depth), state, injected, depth + 1); + } + } + + foreach (var write in constructor.FieldWrites) + { + state.Fields[write.Field] = Resolve(write.Value, frame, depth + 1); + } + } + + private void Initialize(string type, Frame frame, ObjectState state, int depth) + { + if (!graph.Types.TryGetValue(type, out var summary)) return; + foreach (var write in summary.Initializers) + { + state.Fields[write.Field] = Resolve(write.Value, frame, depth + 1); + } + } + + private Identity Unknown(string reason) => new(entry.Caller with { Assumed = true }, reason); + + private static string ShortName(string id) + { + var end = id.IndexOf('('); + var name = end < 0 ? id : id.Substring(0, end); + return name.Substring(name.LastIndexOf('.') + 1); + } + + /// + /// The services and tables passed to one parameter. + /// + private sealed record Binding(IReadOnlyList? Services, IReadOnlyDictionary? Tables) + { + public override string ToString() => + string.Join(",", Services ?? []) + "|" + string.Join(",", (Tables ?? new Dictionary()).OrderBy(t => t.Key).Select(t => $"{t.Key}={t.Value}")); + } + + /// + /// The services stored in an object's fields. + /// + private sealed class ObjectState(string? type) + { + private string? _key; + + public string? Type { get; } = type; + + public Dictionary> Fields { get; } = new(StringComparer.Ordinal); + + public string Key => _key ?? throw new InvalidOperationException("Object state is not complete"); + + public void Merge(ObjectState other) + { + foreach (var field in other.Fields) + { + Fields[field.Key] = Fields.TryGetValue(field.Key, out var existing) + ? existing.Concat(field.Value).Distinct().OrderBy(i => i).ToList() + : field.Value; + } + } + + public ObjectState Freeze() + { + _key = Type + "{" + string.Join(";", Fields.OrderBy(f => f.Key, StringComparer.Ordinal).Select(f => f.Key + "=" + string.Join(",", f.Value))) + "}"; + return this; + } + } + + /// + /// A node in a call context. is set while building an object for a container, where + /// unbound constructor parameters are injected. + /// + private sealed class Frame( + string node, + ObjectState? state, + IReadOnlyDictionary<(string, int), Binding> bindings, + RequirementBasis basis, + IReadOnlyList path, + bool injected = false) + { + public string Node { get; } = node; + public ObjectState? Object { get; } = state; + public IReadOnlyDictionary<(string, int), Binding> Bindings { get; } = bindings; + public RequirementBasis Basis { get; } = basis; + public IReadOnlyList Path { get; } = path; + public bool Injected { get; } = injected; + + public string Key => + Node + "\n" + Basis + "\n" + Object?.Key + "\n" + + string.Join("\n", Bindings.OrderBy(b => b.Key.Item1, StringComparer.Ordinal).ThenBy(b => b.Key.Item2).Select(b => $"{b.Key.Item1}#{b.Key.Item2}:{b.Value}")); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Summaries.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Summaries.cs new file mode 100644 index 00000000..ccba99c4 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/Summaries.cs @@ -0,0 +1,274 @@ +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Graph; + +// The call graph is built from these summaries. They hold ids and source locations only, no Roslyn objects, +// so summaries of several compilations (projects, target frameworks) merge into one graph by id. + +/// +/// Where an organization service comes from. Origins that depend on the caller (parameters, fields) are +/// resolved per call path. +/// +internal abstract record ServiceOrigin; + +/// +/// A known identity. means the caller of the entry point, which a plugin step's +/// impersonating user replaces. +/// marks the user who started the operation (InitiatingUserId), whom impersonation +/// doesn't replace. +/// +internal sealed record FixedOrigin(RunsAs RunsAs, bool Initiating = false) : ServiceOrigin; + +internal sealed record ParameterOrigin(string Method, int Ordinal, string Name) : ServiceOrigin; + +/// +/// A field or auto-property of . is set when it is read from the current +/// object, so the object's constructor arguments decide its value. +/// +internal sealed record FieldOrigin(string Type, string Field, bool OnThis) : ServiceOrigin; + +/// +/// Provided by dependency injection or a service provider. Who it runs as depends on the host. +/// +internal sealed record InjectedOrigin : ServiceOrigin; + +/// +/// Returned by a method in the solution. +/// +internal sealed record ReturnedOrigin(CallFact Call) : ServiceOrigin; + +internal sealed record UnknownOrigin(string Reason) : ServiceOrigin; + +/// +/// One service call: the tables it touches and the service it is made on. +/// +internal sealed record AccessFact( + string Operation, + SourceLocation Source, + IReadOnlyList Privileges, + TableResolution Tables, + string ReasonPrefix, + IReadOnlyList Service); + +internal enum ReceiverKind +{ + /// + /// A static method. + /// + None, + + /// + /// The current object, including base.M(), constructor initializers and local functions. + /// + This, + + /// + /// An object created at the call site, or in a local that holds only that object. + /// + Created, + + /// + /// Any other object, of unknown concrete type. + /// + Other, +} + +/// +/// A call to a method that may be in the solution. is set when the method that runs depends +/// on the receiver's runtime type. is the constructor call that made the receiver, for +/// ; a constructor call is its own creation and leaves it null. +/// holds, per generic type the receiver is or derives from, the tables of its type +/// arguments, which the method that runs binds when it is declared in that type. +/// +internal sealed record CallFact( + SourceLocation Source, + string Target, + bool Virtual, + ReceiverKind Receiver, + string? ReceiverType, + IReadOnlyDictionary Arguments, + CallFact? Creation = null, + IReadOnlyDictionary>? TypeArguments = null); + +/// +/// What an argument contributes to the callee: its service origins and its tables per shape. +/// +internal sealed record ArgumentFact(IReadOnlyList? Service, IReadOnlyDictionary? Tables) +{ + /// + /// The ordinal under which a call on an OrganizationServiceContext passes the service of the context, which + /// code in the context runs as. + /// + public const int ReceiverOrdinal = int.MinValue; +} + +internal sealed record FieldWrite(string Field, IReadOnlyList Value); + +/// +/// A call graph node: a member, lambda or local function, with the facts found in its body. +/// +internal sealed class NodeSummary(string id, string member, string display, string? type, bool isConstructor, SourceLocation? declaration, SourceLocation? memberDeclaration) +{ + public string Id { get; } = id; + + public bool IsConstructor { get; } = isConstructor; + + /// + /// The id of the member that contains this node; the node's own id unless it's a lambda or local function. + /// + public string Member { get; } = member; + + public string Display { get; } = display; + + /// + /// Id of the containing type. + /// + public string? Type { get; } = type; + + public SourceLocation? Declaration { get; } = declaration; + + public SourceLocation? MemberDeclaration { get; } = memberDeclaration; + + public List Accesses { get; } = []; + + public List Calls { get; } = []; + + /// + /// Lambdas declared directly in this node. They count as reachable from it. + /// + public SortedSet Lambdas { get; } = new(StringComparer.Ordinal); + + /// + /// The services this method returns, when it returns one. + /// + public List> Returns { get; } = []; + + /// + /// The tables this method returns per shape, when it returns an entity, query or string. + /// + public Dictionary ReturnTables { get; } = []; + + /// + /// Services stored in fields of the current object. + /// + public List FieldWrites { get; } = []; + + /// + /// Adds the facts of the same node from another compilation, such as another target framework. Facts at the + /// same source location may resolve differently, including call arguments, returned values and services + /// stored in fields. Keep every distinct resolved fact, without duplicating identical compilations. + /// + public void Merge(NodeSummary other) + { + MergeBySource(Accesses, other.Accesses, a => (a.Source, SummaryKeys.Access(a))); + MergeBySource(Calls, other.Calls, c => (c.Source, SummaryKeys.Call(c))); + Lambdas.UnionWith(other.Lambdas); + var returnedServices = new HashSet(Returns.Select(SummaryKeys.Services), StringComparer.Ordinal); + Returns.AddRange(other.Returns.Where(r => returnedServices.Add(SummaryKeys.Services(r)))); + foreach (var returned in other.ReturnTables) + { + ReturnTables[returned.Key] = ReturnTables.TryGetValue(returned.Key, out var known) + ? known.Union(returned.Value) : returned.Value; + } + // Constructor evaluation uses the last write to each field. Merge those effective values rather than + // appending another write, which would make whichever compilation arrived last overwrite the others. + foreach (var writes in other.FieldWrites.GroupBy(w => w.Field, StringComparer.Ordinal)) + { + var incoming = writes.Last(); + var index = FieldWrites.FindLastIndex(w => w.Field == incoming.Field); + if (index < 0) FieldWrites.Add(incoming); + else + { + var services = FieldWrites[index].Value.Concat(incoming.Value) + .GroupBy(SummaryKeys.Service, StringComparer.Ordinal) + .OrderBy(g => g.Key, StringComparer.Ordinal).Select(g => g.First()).ToList(); + FieldWrites[index] = new FieldWrite(incoming.Field, services); + } + } + } + + private static void MergeBySource(List target, List source, Func key) + { + var known = new HashSet<(SourceLocation, string)>(target.Select(key)); + target.AddRange(source.Where(f => known.Add(key(f)))); + } +} + +/// +/// A type in the solution, for virtual dispatch and object construction. +/// +internal sealed class TypeSummary(string id, bool isAbstract, bool isInterface, IReadOnlyList ancestors) +{ + public string Id { get; } = id; + + /// + /// Abstract classes and interfaces, which are never the runtime type of an object. + /// + public bool IsAbstract { get; } = isAbstract; + + public bool IsInterface { get; } = isInterface; + + /// + /// Base classes and every implemented interface. + /// + public IReadOnlyList Ancestors { get; } = ancestors; + + /// + /// For each method of the type or its ancestors, the method in the solution that runs for an object of this type. + /// + public Dictionary Implementations { get; } = new(StringComparer.Ordinal); + + /// + /// For each generic ancestor, which of this type's type parameters (see Nodes.TypeParameters) each of + /// its type arguments is, or -1 when it is another type. A call on an ancestor binds them for this type. + /// + public Dictionary> AncestorTypeArguments { get; } = new(StringComparer.Ordinal); + + /// + /// Instance constructors in the solution. + /// + public SortedSet Constructors { get; } = new(StringComparer.Ordinal); + + /// + /// Services stored by field and property initializers. + /// + public List Initializers { get; } = []; +} + +/// +/// A dependency injection registration: AddScoped<IFoo, Foo>() maps IFoo to Foo. +/// +internal sealed record Registration(string Service, string Implementation); + +/// +/// Where an entry point starts. is the runtime type of the current object, when known; +/// otherwise the handler is dispatched like an interface call on . +/// +internal sealed record Handler(string Target, string? ObjectType, string? ServiceType = null); + +/// +/// The execute privilege a custom API's registration in code sets: a privilege name, or a table privilege. All +/// null when it is set but can't be read. +/// +internal sealed record ExecutePrivilege(string? Name, string? Table = null, Privilege? Privilege = null); + +/// +/// An entry point found in code, before its requirements are worked out. is the +/// privilege a custom API's registration sets, if any. +/// +internal sealed record EntryCandidate( + string Id, + EntryPointKind Kind, + string Type, + string? Assembly, + Trigger? Trigger, + string? ImpersonatingUserId, + SourceLocation? Declaration, + IReadOnlyList Handlers, + ExecutePrivilege? ExecutePrivilege = null); + +/// +/// A class implementing IPlugin, for matching the steps in the plugin metadata. +/// +internal sealed record PluginClass(string Type, string? Assembly, SourceLocation? Declaration, string TypeId, string? Execute, bool HasCodeSteps); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/SummaryExtractor.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/SummaryExtractor.cs new file mode 100644 index 00000000..657d492c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/SummaryExtractor.cs @@ -0,0 +1,976 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Operations; +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Model; +using static XrmMockup.PermissionAnalyzer.Core.Extraction.Operations; + +namespace XrmMockup.PermissionAnalyzer.Core.Graph; + +/// +/// Summarizes every method body of a compilation: its service calls, the methods it calls with what it passes +/// them, and where its organization services come from. +/// +internal sealed class SummaryExtractor(Compilation compilation, XrmSymbols symbols, SourcePaths paths, RequestRules rules, LookupColumns lookups) +{ + // How far constants are followed through fields and locals, such as a user id in a static field. + private const int MaxConstantDepth = 8; + + private const string NoEntityTable = "entity has no table name"; + + private static readonly HashSet RegistrationMethods = new(StringComparer.Ordinal) + { + "AddScoped", "AddTransient", "AddSingleton", + "TryAddScoped", "TryAddTransient", "TryAddSingleton", + "AddKeyedScoped", "AddKeyedTransient", "AddKeyedSingleton", + }; + + private readonly CallGraph _graph = new(); + private readonly HashSet _visiting = new(SymbolEqualityComparer.Default); + private readonly Dictionary _resolvers = new(SymbolEqualityComparer.Default); + + /// + /// Whether a body or initializer has code the compiler couldn't bind, such as a call to a method or on a type it + /// didn't find. Its calls are missing from the graph. Set by . + /// + public bool HasUnboundCode { get; private set; } + + public CallGraph Extract(CancellationToken cancellationToken = default) + { + // Binding the bodies is most of the work and a semantic model is thread-safe, so declarations are bound in + // parallel, even within one large generated file, while the graph is built from them in source order + var declarations = compilation.SyntaxTrees + .Select(tree => compilation.GetSemanticModel(tree)) + .SelectMany(model => model.SyntaxTree.GetRoot(cancellationToken).DescendantNodesAndSelf().Select(syntax => (Model: model, Syntax: syntax))) + .AsParallel().AsOrdered().WithCancellation(cancellationToken) + .Select(node => Bind(node.Model, node.Syntax)) + .OfType(); + foreach (var declaration in declarations) Visit(declaration); + return _graph; + } + + private enum DeclarationKind { Body, Type, Initializer } + + /// A declaration with its symbol and bound operation, ready to be summarized. + private sealed record Declaration(DeclarationKind Kind, SemanticModel Model, SyntaxNode Syntax, ISymbol? Symbol, IOperation? Operation = null); + + private static Declaration? Bind(SemanticModel model, SyntaxNode syntax) => syntax switch + { + CompilationUnitSyntax unit when unit.Members.OfType().Any() + => new(DeclarationKind.Body, model, unit, model.GetDeclaredSymbol(unit), model.GetOperation(unit)), + + BaseMethodDeclarationSyntax method when method.Body is not null || method.ExpressionBody is not null + => new(DeclarationKind.Body, model, method, model.GetDeclaredSymbol(method), model.GetOperation(method)), + + AccessorDeclarationSyntax accessor when accessor.Body is not null || accessor.ExpressionBody is not null + => new(DeclarationKind.Body, model, accessor, model.GetDeclaredSymbol(accessor), model.GetOperation(accessor)), + + PropertyDeclarationSyntax { ExpressionBody: { } body } property + => new(DeclarationKind.Body, model, property, (model.GetDeclaredSymbol(property) as IPropertySymbol)?.GetMethod, model.GetOperation(body)), + + IndexerDeclarationSyntax { ExpressionBody: { } body } indexer + => new(DeclarationKind.Body, model, indexer, (model.GetDeclaredSymbol(indexer) as IPropertySymbol)?.GetMethod, model.GetOperation(body)), + + BaseTypeDeclarationSyntax declaration when model.GetDeclaredSymbol(declaration) is INamedTypeSymbol type + => new(DeclarationKind.Type, model, declaration, type), + + EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax { Parent.Parent: FieldDeclarationSyntax } declarator } initializer + => new(DeclarationKind.Initializer, model, initializer, model.GetDeclaredSymbol(declarator), model.GetOperation(initializer)), + + EqualsValueClauseSyntax { Parent: PropertyDeclarationSyntax property } initializer + => new(DeclarationKind.Initializer, model, initializer, model.GetDeclaredSymbol(property), model.GetOperation(initializer)), + + _ => null, + }; + + private void Visit(Declaration declaration) + { + HasUnboundCode = HasUnboundCode || declaration.Operation is { } bound && bound.DescendantsAndSelf().Any(IsUnbound); + + switch (declaration.Kind) + { + case DeclarationKind.Body: + Body(declaration.Symbol as IMethodSymbol, declaration.Operation); + break; + + case DeclarationKind.Type: + var type = (INamedTypeSymbol)declaration.Symbol!; + AddType(type); + if (declaration.Syntax is TypeDeclarationSyntax { ParameterList: not null } primary) PrimaryConstructor(declaration.Model, primary, type); + break; + + case DeclarationKind.Initializer: + Initializer(declaration.Symbol, declaration.Operation); + break; + } + } + + private static bool IsUnbound(IOperation operation) => + operation.Kind == OperationKind.Invalid || operation.Type is { TypeKind: TypeKind.Error }; + + private void Body(IMethodSymbol? symbol, IOperation? body) + { + if (symbol is null || body is null) return; + + // A context's query property, such as a generated AccountSet, is read where it is used + if (symbol is { MethodKind: MethodKind.PropertyGet, AssociatedSymbol: IPropertySymbol getterOf } && symbols.QueryElement(getterOf) is not null) return; + + Node(symbol); + + foreach (var operation in body.DescendantsAndSelf()) + { + switch (operation) + { + case IAnonymousFunctionOperation lambda: + Node(Owner(lambda.Parent, symbol)).Lambdas.Add(Nodes.Id(lambda.Symbol)); + Node(lambda.Symbol); + break; + + case ILocalFunctionOperation local: + Node(local.Symbol); + break; + + case IInvocationOperation invocation: + Invocation(invocation, symbol); + break; + + case IObjectCreationOperation creation when Construction(creation, symbol) is { } call: + Node(Owner(creation, symbol)).Calls.Add(call); + break; + + case IMethodReferenceOperation reference + when Call(reference.Method, reference.Instance, reference.IsVirtual, [], reference.Syntax.GetLocation(), symbol) is { } call: + Node(Owner(reference, symbol)).Calls.Add(call); + break; + + case IPropertyReferenceOperation property when symbols.QueryElement(property.Property) is { } element: + Node(Owner(property, symbol)).Accesses.Add(Query( + new Site(property.Property.Name, paths.Of(NameLocation(property.Syntax)), ServiceOf(property.Instance, symbol)), + Resolver(symbol).TypeArgument(element), + property)); + break; + + case IPropertyReferenceOperation property when Accessor(property, symbol) is { } call: + Node(Owner(property, symbol)).Calls.Add(call); + break; + + case IReturnOperation { ReturnedValue: { } value } when symbols.IsService(value.Type): + Node(Owner(operation, symbol)).Returns.Add(ServiceOf(value, symbol)); + break; + + case IReturnOperation { ReturnedValue: { } value }: + ReturnedTables(Owner(operation, symbol), value, symbol); + break; + + case ISimpleAssignmentOperation assignment when FieldOf(assignment.Target) is { } field && symbols.IsService(assignment.Target.Type): + Node(Owner(operation, symbol)).FieldWrites.Add(new FieldWrite(field, ServiceOf(assignment.Value, symbol))); + break; + } + } + } + + /// + /// The tables a method returns, for every way a caller might read them, such as a query built by a helper. + /// + private void ReturnedTables(IMethodSymbol owner, IOperation value, IMethodSymbol root) + { + var resolver = Resolver(root); + var shapes = resolver.ShapesOf(owner.ReturnType); + if (shapes.Count == 0) return; + + var returns = Node(owner).ReturnTables; + foreach (var shape in shapes) + { + var tables = resolver.Resolve(value, shape); + returns[shape] = returns.TryGetValue(shape, out var known) ? known.Union(tables) : tables; + } + } + + /// + /// The table resolver for code in , which follows calls to methods in the solution. It is + /// shared, so a local passed to the call it is assigned from, as in x = Prepare(x), is resolved once. + /// + private TableResolver Resolver(IMethodSymbol root) + { + if (!_resolvers.TryGetValue(root, out var resolver)) + { + _resolvers[root] = resolver = new TableResolver(symbols, rules, invocation => + IsInSource(invocation.TargetMethod) + ? Call(invocation.TargetMethod, invocation.Instance, invocation.IsVirtual, invocation.Arguments, NameLocation(invocation.Syntax), root) + : null, lookups, root); + } + return resolver; + } + + private void Invocation(IInvocationOperation invocation, IMethodSymbol root) + { + var owner = Node(Owner(invocation, root)); + if (symbols.ServiceOperation(invocation.TargetMethod) is { } operation) + { + owner.Accesses.AddRange(Accesses(invocation, operation, root)); + return; + } + + if (symbols.ContextOperation(invocation.TargetMethod) is { } contextOperation) + { + owner.Accesses.AddRange(ContextAccesses(invocation, contextOperation, root)); + return; + } + + Registration(invocation); + + if (Call(invocation.TargetMethod, invocation.Instance, invocation.IsVirtual, invocation.Arguments, NameLocation(invocation.Syntax), root) is { } call) + { + owner.Calls.Add(call); + } + } + + private IEnumerable Accesses(IInvocationOperation invocation, string operation, IMethodSymbol root) + { + var resolver = Resolver(root); + var first = Argument(invocation, 0); + var site = new Site(operation, paths.Of(NameLocation(invocation.Syntax)), ServiceOf(invocation.Instance, root)); + + switch (operation) + { + case Messages.Create: + return Write(site, resolver, Messages.Create, first, Privilege.Create); + case "CreateAndReturn": + return Write(site, resolver, Messages.Create, first, Privilege.Create, Privilege.Read); + case Messages.Update: + return Write(site, resolver, Messages.Update, first, Privilege.Write); + case Messages.Retrieve: + return [site.Access(Fires(Messages.Retrieve, resolver.Name(first)), Privilege.Read)]; + case Messages.Delete: + return [site.Access(Fires(Messages.Delete, resolver.Name(first)), Privilege.Delete)]; + case Messages.RetrieveMultiple: + return + [ + site.Access( + resolver.Query(first).OrUnresolved("query has no table name") + .Union(TableResolution.Fires(Messages.RetrieveMultiple, resolver.Query(first, includeLinks: false).OrUnresolved("query has no table name"))), + Privilege.Read), + ]; + case Messages.Associate: + case Messages.Disassociate: + var related = invocation.Arguments.FirstOrDefault(a => symbols.Is(a.Parameter?.Type, symbols.EntityReferenceCollection)); + return + [ + site.Access(Fires(operation, resolver.Name(first)), Privilege.Read, Privilege.AppendTo), + site.Access(resolver.EntityReferences(related).OrUnresolved("no related records are added"), "related records: ", Privilege.Read, Privilege.Append), + ]; + case Messages.Execute: + // One access per privilege the request can need, and one for what it can't be tied to a privilege + return + [ + .. Enum.GetValues(typeof(Privilege)).Cast().Select(p => site.Access(resolver.Requests(first, RequestShapes.For(p)), p)), + site.Access(resolver.Requests(first, TableShape.RequestOther)), + ]; + default: + return []; + } + } + + /// + /// The accesses of an OrganizationServiceContext method. Changes are sent by SaveChanges, but + /// are reported where they are made, which names the record. + /// + private IEnumerable ContextAccesses(IInvocationOperation invocation, string method, IMethodSymbol root) + { + var resolver = Resolver(root); + var first = Argument(invocation, 0); + var target = Argument(invocation, 2); + var site = new Site(method, paths.Of(NameLocation(invocation.Syntax)), ServiceOf(invocation.Instance, root)); + + switch (method) + { + case "CreateQuery": + var tables = invocation.TargetMethod.IsGenericMethod ? resolver.TypeArgument(invocation.TargetMethod.TypeArguments[0]) : resolver.Name(first); + return [Query(site, tables, invocation)]; + case "AddObject": + return Write(site, resolver, Messages.Create, first, Privilege.Create); + case "UpdateObject": + return Write(site, resolver, Messages.Update, first, Privilege.Write); + case "DeleteObject": + return [site.Access(Fires(Messages.Delete, resolver.Entity(first).OrUnresolved(NoEntityTable)), Privilege.Delete)]; + case "AddLink": + case "DeleteLink": + return Link(site, method == "AddLink" ? Messages.Associate : Messages.Disassociate, resolver, first, target); + case "AddRelatedObject": + return [.. Write(site, resolver, Messages.Create, target, Privilege.Create), .. Link(site, Messages.Associate, resolver, first, target)]; + case "LoadProperty": + return [site.Access(TableResolution.Unresolved("related records are read through a relationship, whose table isn't known"), Privilege.Read)]; + case Messages.Execute: + return Accesses(invocation, Messages.Execute, root); + default: + return []; + } + } + + /// + /// Read on the tables a query reads. It fires the plugin steps of RetrieveMultiple unless it is joined to + /// another query, whose table it is linked to. + /// + private static AccessFact Query(Site site, TableResolution tables, IOperation query) => + site.Access(IsJoined(query) ? tables : Fires(Messages.RetrieveMultiple, tables), Privilege.Read); + + /// + /// Writing a record: the privileges on its table, firing with the columns it sets, and + /// Append and AppendTo for its lookups. + /// + private static AccessFact[] Write(Site site, TableResolver resolver, string message, IOperation? entity, params Privilege[] privileges) => + [ + site.Access(Fires(message, resolver.Entity(entity).OrUnresolved(NoEntityTable), resolver.Columns(entity)), privileges), + .. Lookups(site, resolver, entity), + ]; + + private static AccessFact[] Link(Site site, string message, TableResolver resolver, IOperation? source, IOperation? target) => + [ + site.Access(Fires(message, resolver.Entity(source)), Privilege.Read, Privilege.AppendTo), + site.Access(resolver.Entity(target), "related records: ", Privilege.Read, Privilege.Append), + ]; + + /// + /// Whether is the inner query of a LINQ join. + /// + private static bool IsJoined(IOperation query) + { + var parent = query.Parent; + while (parent is IConversionOperation) parent = parent.Parent; + return parent is IArgumentOperation { Parameter.Name: "inner", Parent: IInvocationOperation { TargetMethod.Name: "Join" or "GroupJoin" } }; + } + + /// + /// The service a context is created with: its first argument that is a service. + /// + private IReadOnlyList ContextServiceOf(IEnumerable arguments, IMethodSymbol root) => + arguments.FirstOrDefault(a => symbols.IsService(a.Parameter?.Type)) is { } service + ? ServiceOf(service.Value, root) + : [new UnknownOrigin("context is created without a service")]; + + /// + /// , on which the call also fires the plugin steps of , + /// setting . + /// + private static TableResolution Fires(string message, TableResolution tables, TableResolution? columns = null) => + tables.Union(TableResolution.Fires(message, tables, columns)); + + /// + /// Append on an entity that gets a lookup, and AppendTo on the tables its lookups refer to. + /// + private static AccessFact[] Lookups(Site site, TableResolver resolver, IOperation? entity) => + [ + site.Access(resolver.Lookups(entity, TableShape.LookupHolder), Privilege.Append), + site.Access(resolver.Lookups(entity, TableShape.LookupTarget), "lookup value: ", Privilege.AppendTo), + ]; + + /// + /// A call to a method that is in the solution or may be implemented by it. Calls into the framework are left + /// out, so the graph only holds calls that can lead to code in the solution. + /// + private CallFact? Call(IMethodSymbol target, IOperation? instance, bool isVirtual, IReadOnlyList arguments, Location location, IMethodSymbol root) + { + if (!IsInSource(target) && (!isVirtual || IsFrameworkType(target.ContainingType))) return null; + + var created = Creation(instance); + var unwrapped = Unwrap(instance); + var receiver = target.IsStatic ? ReceiverKind.None + : target.MethodKind == MethodKind.LocalFunction || IsThis(instance) ? ReceiverKind.This + : created is not null ? ReceiverKind.Created + : ReceiverKind.Other; + + var creation = receiver == ReceiverKind.Created ? Construction(created!, root) : null; + var receiverType = receiver switch + { + ReceiverKind.Created => creation?.ReceiverType, + ReceiverKind.Other when unwrapped?.Type is { } type => Nodes.TypeId(type), + _ => Nodes.TypeId(target.ContainingType), + }; + + var argumentFacts = Arguments(target, arguments, isVirtual, root); + if (receiver != ReceiverKind.None && target.MethodKind != MethodKind.Constructor && symbols.IsContext(target.ContainingType)) + { + argumentFacts[ArgumentFact.ReceiverOrdinal] = new ArgumentFact(ServiceOf(instance, root), null); + } + + return new CallFact( + paths.Of(location), + Nodes.Id(target), + isVirtual, + receiver, + receiverType, + argumentFacts, + creation, + TypeArguments(created?.Type ?? unwrapped?.Type, target, root)); + } + + /// + /// The call to the constructor of a created object, so the services it stores can be followed. + /// + private CallFact? Construction(IObjectCreationOperation creation, IMethodSymbol root) + { + if (creation.Constructor is not { } constructor || !IsInSource(constructor)) return null; + return new CallFact( + paths.Of(creation.Syntax.GetLocation()), + Nodes.Id(constructor), + false, + ReceiverKind.Created, + Nodes.TypeId(constructor.ContainingType), + Arguments(constructor, creation.Arguments, false, root), + TypeArguments: TypeArguments(creation.Type, constructor, root)); + } + + /// + /// The tables of the type arguments of each generic type is or derives from, and of + /// the type that declares , so a method declared in one of them can read its type + /// parameters. + /// + private IReadOnlyDictionary>? TypeArguments(ITypeSymbol? receiver, IMethodSymbol target, IMethodSymbol root) + { + Dictionary>? result = null; + var resolver = Resolver(root); + IEnumerable types = receiver is null ? [target.ContainingType] : [target.ContainingType, receiver, .. BaseTypes(receiver)]; + foreach (var type in types.OfType()) + { + var arguments = Nodes.TypeArguments(type); + if (arguments.Count == 0 || !IsInSource(type)) continue; + + result ??= new Dictionary>(StringComparer.Ordinal); + result[Nodes.TypeId(type)] = arguments.Select(resolver.TypeArgument).ToList(); + } + return result; + } + + /// + /// A property with a getter or setter body, which runs as a method. + /// + private CallFact? Accessor(IPropertyReferenceOperation property, IMethodSymbol root) + { + var isWrite = property.Parent is IAssignmentOperation assignment && assignment.Target == property; + var accessor = isWrite ? property.Property.SetMethod : property.Property.GetMethod; + if (accessor is null || IsAutoProperty(property.Property)) return null; + + var isVirtual = (property.Property.IsVirtual || property.Property.IsAbstract || property.Property.IsOverride + || property.Property.ContainingType.TypeKind == TypeKind.Interface) + && Unwrap(property.Instance) is not IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ContainingTypeInstance, Syntax: BaseExpressionSyntax }; + return Call(accessor, property.Instance, isVirtual, property.Arguments, property.Syntax.GetLocation(), root); + } + + /// + /// What each argument passes on: its services, and its tables for every way the callee might read them. The + /// type arguments of a generic method are passed as tables too, under . + /// + private SortedDictionary Arguments(IMethodSymbol target, IReadOnlyList arguments, bool isVirtual, IMethodSymbol root) + { + var result = new SortedDictionary(); + var tablesMatter = isVirtual || IsInSource(target); + var resolver = Resolver(root); + foreach (var argument in arguments) + { + if (argument.Parameter is not { } parameter || argument.ArgumentKind == ArgumentKind.ParamArray) continue; + + var service = symbols.IsService(parameter.Type) ? ServiceOf(argument.Value, root) : null; + + Dictionary? tables = null; + if (tablesMatter) + { + foreach (var shape in resolver.ShapesOf(parameter.Type)) + { + tables ??= new Dictionary(); + tables[shape] = resolver.Resolve(argument.Value, shape); + } + } + + if (service is not null || tables is not null) result[parameter.Ordinal] = new ArgumentFact(service, tables); + } + + if (tablesMatter && target.IsGenericMethod) + { + var typeArguments = (target.GetConstructedReducedFrom() ?? target).TypeArguments; + for (var i = 0; i < typeArguments.Length; i++) + { + result[TableSlot.TypeParameterOrdinal(i)] = new ArgumentFact(null, new Dictionary + { + [TableShape.Entity] = resolver.TypeArgument(typeArguments[i]), + }); + } + } + return result; + } + + /// + /// Where the organization service in comes from. + /// + private IReadOnlyList ServiceOf(IOperation? operation, IMethodSymbol root) + { + var op = Unwrap(operation); + switch (op) + { + case null: + return [new UnknownOrigin("service is missing")]; + + case { ConstantValue: { HasValue: true, Value: null } }: + return []; + + case IParameterReferenceOperation parameter: + return [Parameter(parameter.Parameter, root)]; + + case ILocalReferenceOperation local: + return Local(local, root); + + case IFieldReferenceOperation field when IsInSource(field.Field): + return [new FieldOrigin(Nodes.TypeId(field.Field.ContainingType), Nodes.Id(field.Field), !field.Field.IsStatic && IsThis(field.Instance))]; + + case IFieldReferenceOperation field: + return [new UnknownOrigin($"service comes from field '{field.Field.Name}'")]; + + case IPropertyReferenceOperation property: + return Property(property, root); + + case IInvocationOperation invocation: + return ServiceFromInvocation(invocation, root); + + case IObjectCreationOperation creation when symbols.IsContext(creation.Type): + return ContextServiceOf(creation.Arguments, root); + + // Code in a context runs as the service of the context it is called on + case IInstanceReferenceOperation { Type: { } type } when symbols.IsContext(type): + return [new ParameterOrigin(Nodes.Id(root), ArgumentFact.ReceiverOrdinal, "this")]; + + case IObjectCreationOperation creation when !IsInSource(creation.Type): + // ServiceClient, CrmServiceClient: connects as the application user + return [new FixedOrigin(RunsAs.ApplicationUser)]; + + case IConditionalOperation { WhenFalse: { } whenFalse } conditional: + return [.. ServiceOf(conditional.WhenTrue, root), .. ServiceOf(whenFalse, root)]; + + case ICoalesceOperation coalesce: + return [.. ServiceOf(coalesce.Value, root), .. ServiceOf(coalesce.WhenNull, root)]; + + case ICoalesceAssignmentOperation coalesce: + return [.. ServiceOf(coalesce.Target, root), .. ServiceOf(coalesce.Value, root)]; + + case ISimpleAssignmentOperation assignment: + return ServiceOf(assignment.Value, root); + + default: + return [new UnknownOrigin("service is computed at runtime")]; + } + } + + private ServiceOrigin Parameter(IParameterSymbol parameter, IMethodSymbol root) + { + // A primary constructor parameter used outside the constructor is a field of the object + if (parameter.ContainingSymbol is IMethodSymbol { MethodKind: MethodKind.Constructor } constructor + && IsPrimaryConstructor(constructor) + && !SymbolEqualityComparer.Default.Equals(Nodes.Member(root), constructor)) + { + var type = Nodes.TypeId(constructor.ContainingType); + return new FieldOrigin(type, $"{type}.{parameter.Name}", true); + } + return new ParameterOrigin(Nodes.Id(parameter.ContainingSymbol), parameter.Ordinal, parameter.Name); + } + + private IReadOnlyList Local(ILocalReferenceOperation reference, IMethodSymbol root) + { + var local = reference.Local; + if (!_visiting.Add(local)) return []; + try + { + var body = Root(reference); + + // App code acting for a user: client.CallerId = userId + var impersonates = body.DescendantsAndSelf().Any(node => + node is ISimpleAssignmentOperation { Target: IPropertyReferenceOperation { Property.Name: SdkNames.CallerId or SdkNames.CallerAADObjectId } property } + && IsLocal(property.Instance, local)); + if (impersonates) return [new FixedOrigin(RunsAs.ImpersonatedCaller)]; + + var result = new List(); + var values = LocalValues(local, body, out var failure); + foreach (var value in values) + { + result.AddRange(ServiceOf(value, root)); + } + if (failure is not null) result.Add(new UnknownOrigin(failure)); + return result; + } + finally + { + _visiting.Remove(local); + } + } + + private IReadOnlyList Property(IPropertyReferenceOperation property, IMethodSymbol root) + { + var symbol = property.Property; + if (IsAutoProperty(symbol)) + { + return [new FieldOrigin(Nodes.TypeId(symbol.ContainingType), Nodes.Id(symbol), !symbol.IsStatic && IsThis(property.Instance))]; + } + + if (IsInSource(symbol)) + { + return Accessor(property, root) is { } call + ? [new ReturnedOrigin(call)] + : [new UnknownOrigin($"service comes from property '{symbol.Name}'")]; + } + + // The plugin context of XrmPluginCore and similar base classes + return symbol.Name switch + { + "OrganizationService" => [new FixedOrigin(RunsAs.Caller)], + "OrganizationAdminService" => [new FixedOrigin(RunsAs.System)], + _ => [new UnknownOrigin($"service comes from property '{symbol.Name}'")], + }; + } + + private IReadOnlyList ServiceFromInvocation(IInvocationOperation invocation, IMethodSymbol root) + { + var method = invocation.TargetMethod; + if (method.Name == SdkNames.CreateOrganizationService && XrmSymbols.Implements(method.ContainingType, symbols.OrganizationServiceFactory)) + { + return UserArgument(Argument(invocation, 0), root, 0); + } + + if (method.Name is "GetService" or "GetRequiredService") + { + return [new InjectedOrigin()]; + } + + if (IsInSource(method) && Call(method, invocation.Instance, invocation.IsVirtual, invocation.Arguments, NameLocation(invocation.Syntax), root) is { } call) + { + return [new ReturnedOrigin(call)]; + } + + return [new UnknownOrigin($"service is returned by '{method.Name}'")]; + } + + /// + /// Who a service from CreateOrganizationService(userId) runs as. + /// + private IReadOnlyList UserArgument(IOperation? argument, IMethodSymbol root, int depth) + { + var op = Unwrap(argument); + switch (op) + { + case null: + case { ConstantValue: { HasValue: true, Value: null } }: + case IDefaultValueOperation: + return [new FixedOrigin(RunsAs.System)]; + + case IPropertyReferenceOperation { Property.Name: SdkNames.UserId or SdkNames.InitiatingUserId } property + when XrmSymbols.Implements(property.Property.ContainingType, symbols.ExecutionContext): + return [new FixedOrigin(RunsAs.Caller, property.Property.Name == SdkNames.InitiatingUserId)]; + + case IConditionalOperation { WhenFalse: { } whenFalse } conditional when depth < MaxConstantDepth: + return [.. UserArgument(conditional.WhenTrue, root, depth + 1), .. UserArgument(whenFalse, root, depth + 1)]; + + case ILocalReferenceOperation local when depth < MaxConstantDepth && _visiting.Add(local.Local): + try + { + var values = LocalValues(local.Local, Root(local), out var failure); + var result = values.SelectMany(v => UserArgument(v, root, depth + 1)).ToList(); + if (failure is not null) result.Add(new UnknownOrigin(failure)); + return result; + } + finally + { + _visiting.Remove(local.Local); + } + + case IFieldReferenceOperation field when depth < MaxConstantDepth && FieldInitializer(field.Field) is { } initializer: + return UserArgument(initializer, root, depth + 1); + } + + if (GuidConstant(op) is { } userId) return [new FixedOrigin(RunsAs.User(userId))]; + + return op is IParameterReferenceOperation parameter + ? [new UnknownOrigin($"user id comes from parameter '{parameter.Parameter.Name}'")] + : [new UnknownOrigin("user id is computed at runtime")]; + } + + /// + /// The value of a readonly or constant field set by its declaration, such as a user id. + /// + private IOperation? FieldInitializer(IFieldSymbol field) + { + if (!field.IsReadOnly && !field.IsConst) return null; + foreach (var reference in field.DeclaringSyntaxReferences) + { + if (reference.GetSyntax() is VariableDeclaratorSyntax { Initializer: { } initializer } + && compilation.ContainsSyntaxTree(initializer.SyntaxTree) + && compilation.GetSemanticModel(initializer.SyntaxTree).GetOperation(initializer) is IFieldInitializerOperation operation) + { + return operation.Value; + } + } + return null; + } + + private void Initializer(ISymbol? member, IOperation? initializer) + { + if (member?.ContainingType is not { } type || initializer is not ISymbolInitializerOperation { Value: { } value }) return; + if (!symbols.IsService(value.Type) && !symbols.IsService((member as IFieldSymbol)?.Type ?? (member as IPropertySymbol)?.Type)) return; + + AddType(type); + var constructor = type.InstanceConstructors.FirstOrDefault(IsPrimaryConstructor) ?? type.InstanceConstructors.FirstOrDefault(); + if (constructor is null) return; + _graph.Types[Nodes.TypeId(type)].Initializers.Add(new FieldWrite(Nodes.Id(member), ServiceOf(value, constructor))); + } + + /// + /// A primary constructor stores its service parameters, which the type's members read as fields. + /// + private void PrimaryConstructor(SemanticModel model, TypeDeclarationSyntax declaration, INamedTypeSymbol type) + { + var constructor = type.InstanceConstructors.FirstOrDefault(c => c.DeclaringSyntaxReferences.Any(r => r.GetSyntax() == declaration)); + if (constructor is null) return; + + var node = Node(constructor); + var typeId = Nodes.TypeId(type); + foreach (var parameter in constructor.Parameters.Where(p => symbols.IsService(p.Type))) + { + node.FieldWrites.Add(new FieldWrite($"{typeId}.{parameter.Name}", [new ParameterOrigin(node.Id, parameter.Ordinal, parameter.Name)])); + } + + if (declaration.BaseList?.Types.FirstOrDefault() is PrimaryConstructorBaseTypeSyntax baseType + && model.GetOperation(baseType) is { } operation) + { + foreach (var invocation in operation.DescendantsAndSelf().OfType()) + { + Invocation(invocation, constructor); + } + } + } + + private static IEnumerable BaseTypes(ITypeSymbol type) + { + for (var current = type.BaseType; current is not null; current = current.BaseType) yield return current; + } + + private void AddType(INamedTypeSymbol type) + { + var id = Nodes.TypeId(type); + if (_graph.Types.ContainsKey(id) || type.TypeKind is not (TypeKind.Class or TypeKind.Struct or TypeKind.Interface)) return; + + var ancestors = new SortedSet(StringComparer.Ordinal); + foreach (var current in BaseTypes(type).Where(t => t.SpecialType != SpecialType.System_Object)) ancestors.Add(Nodes.TypeId(current)); + foreach (var @interface in type.AllInterfaces) ancestors.Add(Nodes.TypeId(@interface)); + + var summary = new TypeSummary(id, type.IsAbstract || type.IsStatic || type.TypeKind == TypeKind.Interface, type.TypeKind == TypeKind.Interface, ancestors.ToList()); + + var typeParameters = Nodes.TypeParameters(type); + if (typeParameters.Count > 0) + { + foreach (var ancestor in type.AllInterfaces.Concat(BaseTypes(type))) + { + var arguments = Nodes.TypeArguments(ancestor); + if (arguments.Count == 0 || !IsInSource(ancestor)) continue; + summary.AncestorTypeArguments[Nodes.TypeId(ancestor)] = arguments.Select(a => a is ITypeParameterSymbol p ? typeParameters.IndexOf(p) : -1).ToList(); + } + } + + // Most derived first, so an override replaces the method it overrides + foreach (var current in BaseTypes(type).Prepend(type)) + { + foreach (var method in current.GetMembers().OfType()) + { + if (method.IsStatic || method.IsAbstract || method.MethodKind == MethodKind.Constructor || !IsInSource(method)) continue; + var implementation = Nodes.Id(method); + for (var overridden = method; overridden is not null; overridden = overridden.OverriddenMethod) + { + var key = Nodes.Id(overridden); + if (!summary.Implementations.ContainsKey(key)) summary.Implementations.Add(key, implementation); + } + } + } + + if (type.TypeKind != TypeKind.Interface) + { + foreach (var @interface in type.AllInterfaces) + { + foreach (var member in @interface.GetMembers().OfType()) + { + if (type.FindImplementationForInterfaceMember(member) is IMethodSymbol implementation && IsInSource(implementation)) + { + var key = Nodes.Id(member); + if (!summary.Implementations.ContainsKey(key)) summary.Implementations.Add(key, Nodes.Id(implementation)); + } + } + } + } + + foreach (var constructor in type.InstanceConstructors.Where(IsInSource)) + { + summary.Constructors.Add(Nodes.Id(constructor)); + } + + _graph.Types.Add(id, summary); + } + + /// + /// Records services.AddScoped<IFoo, Foo>() and the other IServiceCollection registrations. + /// + private void Registration(IInvocationOperation invocation) + { + var method = invocation.TargetMethod; + if (!RegistrationMethods.Contains(method.Name) + || method.ContainingNamespace?.ToDisplayString().StartsWith("Microsoft.Extensions.DependencyInjection", StringComparison.Ordinal) != true) + { + return; + } + + var typeArguments = method.TypeArguments; + if (typeArguments.Length == 2) + { + Register(typeArguments[0], typeArguments[1]); + } + else if (typeArguments.Length == 1) + { + var implementations = invocation.Arguments.SelectMany(a => CreatedTypes(a.Value)).ToList(); + if (implementations.Count == 0) implementations.Add(typeArguments[0]); + foreach (var implementation in implementations) Register(typeArguments[0], implementation); + } + else + { + var types = invocation.Arguments.Select(a => Unwrap(a.Value)).OfType().Select(t => t.TypeOperand).ToList(); + if (types.Count > 0) Register(types[0], types.Count > 1 ? types[1] : types[0]); + } + } + + /// + /// The types a registration creates: new Foo(…) returned by a factory lambda, or an instance. + /// + private static IEnumerable CreatedTypes(IOperation value) + { + var op = Unwrap(value); + if (op is IDelegateCreationOperation { Target: IAnonymousFunctionOperation lambda }) + { + return lambda.Body.DescendantsAndSelf() + .OfType() + .Select(r => Unwrap(r.ReturnedValue)) + .OfType() + .Select(c => c.Type) + .OfType(); + } + return op is IObjectCreationOperation { Type: { } type } ? [type] : []; + } + + private void Register(ITypeSymbol service, ITypeSymbol implementation) + { + if (service is INamedTypeSymbol && implementation is INamedTypeSymbol) + { + _graph.Register(Nodes.TypeId(service), Nodes.TypeId(implementation)); + } + } + + private NodeSummary Node(IMethodSymbol symbol) + { + var id = Nodes.Id(symbol); + if (_graph.Nodes.TryGetValue(id, out var node)) return node; + + var member = Nodes.Member(symbol) ?? symbol; + node = new NodeSummary( + id, + Nodes.Id(member), + Nodes.Display(symbol), + member.ContainingType is { } type ? Nodes.TypeId(type) : null, + symbol.MethodKind == MethodKind.Constructor, + paths.Declaration(symbol), + paths.Declaration(member)); + _graph.Nodes.Add(id, node); + return node; + } + + /// + /// The node an operation belongs to: the innermost lambda or local function around it, or the member. + /// + private static IMethodSymbol Owner(IOperation? operation, IMethodSymbol root) + { + for (var current = operation; current is not null; current = current.Parent) + { + switch (current) + { + case IAnonymousFunctionOperation lambda: return lambda.Symbol; + case ILocalFunctionOperation local: return local.Symbol; + } + } + return root; + } + + /// + /// The field a service is stored in, when it is a field or auto-property of the current object. + /// + private static string? FieldOf(IOperation target) => target switch + { + IFieldReferenceOperation field when IsInSource(field.Field) && (field.Field.IsStatic || IsThis(field.Instance)) => Nodes.Id(field.Field), + IPropertyReferenceOperation property when IsAutoProperty(property.Property) && (property.Property.IsStatic || IsThis(property.Instance)) => Nodes.Id(property.Property), + _ => null, + }; + + /// + /// Every value assigned to in its method. says why some + /// assignment can't be followed. + /// + private static List LocalValues(ILocalSymbol local, IOperation root, out string? failure) + { + string? failed = null; + var values = Operations.LocalValues(local, root, reason => failed = reason); + if (values.Any(v => v.IsLoopCollection)) failed = LoopVariable(local); + failure = failed; + return values.Where(v => !v.IsLoopCollection).Select(v => v.Operation).ToList(); + } + + /// + /// The object creation a receiver holds: new Foo().M(), or a local assigned only that object. + /// + private static IObjectCreationOperation? Creation(IOperation? instance) + { + switch (Unwrap(instance)) + { + case IObjectCreationOperation creation: + return creation; + case ILocalReferenceOperation local: + var values = LocalValues(local.Local, Root(local), out var failure); + return failure is null && values.Count == 1 ? Unwrap(values[0]) as IObjectCreationOperation : null; + default: + return null; + } + } + + private static bool IsThis(IOperation? instance) => + instance is null || Unwrap(instance) is IInstanceReferenceOperation { ReferenceKind: InstanceReferenceKind.ContainingTypeInstance }; + + private static bool IsPrimaryConstructor(IMethodSymbol constructor) => + constructor.DeclaringSyntaxReferences.Any(r => r.GetSyntax() is TypeDeclarationSyntax); + + /// + /// A property without accessor bodies, which stores its value like a field. + /// + private static bool IsAutoProperty(IPropertySymbol property) => + IsInSource(property) + && property.DeclaringSyntaxReferences.All(r => r.GetSyntax() is PropertyDeclarationSyntax + { + ExpressionBody: null, + AccessorList: var accessors, + } && (accessors is null || accessors.Accessors.All(a => a.Body is null && a.ExpressionBody is null))) + && !property.IsAbstract; + + private static Location NameLocation(SyntaxNode syntax) => syntax switch + { + InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax access } => access.Name.GetLocation(), + InvocationExpressionSyntax { Expression: MemberBindingExpressionSyntax binding } => binding.Name.GetLocation(), + MemberAccessExpressionSyntax access => access.Name.GetLocation(), + MemberBindingExpressionSyntax binding => binding.Name.GetLocation(), + _ => syntax.GetLocation(), + }; + + private sealed record Site(string Operation, SourceLocation Source, IReadOnlyList Service) + { + public AccessFact Access(TableResolution tables, params Privilege[] privileges) => Access(tables, "", privileges); + + public AccessFact Access(TableResolution tables, string reasonPrefix, params Privilege[] privileges) => + new(Operation, Source, privileges, tables, reasonPrefix, Service); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/SummaryKeys.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/SummaryKeys.cs new file mode 100644 index 00000000..734af74f --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/SummaryKeys.cs @@ -0,0 +1,55 @@ +using System.Globalization; +using XrmMockup.PermissionAnalyzer.Core.Extraction; + +namespace XrmMockup.PermissionAnalyzer.Core.Graph; + +/// +/// Structural, ordinal keys for SDK-free facts. Collection record equality and their default ToString methods +/// use collection objects rather than their contents, so neither identifies facts across compilations. +/// +internal static class SummaryKeys +{ + public static string Call(CallFact call) => Parts( + Parts(call.Source.File, Number(call.Source.Line), Number(call.Source.Column)), call.Target, call.Virtual.ToString(), call.Receiver.ToString(), call.ReceiverType, + Parts(call.Arguments.OrderBy(a => a.Key).Select(a => Parts(Number(a.Key), Argument(a.Value)))), + call.Creation is null ? null : Call(call.Creation), + call.TypeArguments is null ? null : Parts(call.TypeArguments.OrderBy(a => a.Key, StringComparer.Ordinal) + .Select(a => Parts(a.Key, Parts(a.Value.Select(Tables)))))); + + public static string Access(AccessFact access) => Parts(access.Operation, access.ReasonPrefix, + Parts(access.Privileges.Select(p => p.ToString())), Tables(access.Tables), Services(access.Service)); + + public static string Services(IEnumerable services) => + Parts(services.Select(Service).Distinct(StringComparer.Ordinal).OrderBy(s => s, StringComparer.Ordinal)); + + public static string Tables(TableResolution tables) => Parts( + Parts(tables.Tables), Parts(tables.Reasons), Parts(tables.LookupTargets), + Parts(tables.Slots.Select(s => Parts(s.Method, Number(s.Ordinal), s.Shape.ToString(), s.Reason))), + Parts(tables.Returns.Select(r => Parts(Call(r.Call), r.Shape.ToString(), r.Reason))), + Parts(tables.Fired.OrderBy(f => f.Key, StringComparer.Ordinal).Select(f => Parts(f.Key, Tables(f.Value)))), + tables.Columns is null ? null : Tables(tables.Columns), tables.Bypass.ToString(), + Parts(tables.Globals.Select(g => Parts(g.Privilege, g.Message))), Parts(tables.Assumptions)); + + private static string Argument(ArgumentFact argument) => Parts( + argument.Service is null ? null : Services(argument.Service), + argument.Tables is null ? null : Parts(argument.Tables.OrderBy(t => t.Key).Select(t => Parts(t.Key.ToString(), Tables(t.Value))))); + + public static string Service(ServiceOrigin service) => service switch + { + FixedOrigin fixedOrigin => Parts(nameof(FixedOrigin), fixedOrigin.RunsAs.Kind.ToString(), fixedOrigin.RunsAs.UserId, fixedOrigin.RunsAs.Assumed.ToString(), fixedOrigin.Initiating.ToString()), + ParameterOrigin parameter => Parts(nameof(ParameterOrigin), parameter.Method, Number(parameter.Ordinal), parameter.Name), + FieldOrigin field => Parts(nameof(FieldOrigin), field.Type, field.Field, field.OnThis.ToString()), + InjectedOrigin => nameof(InjectedOrigin), + ReturnedOrigin returned => Parts(nameof(ReturnedOrigin), Call(returned.Call)), + UnknownOrigin unknown => Parts(nameof(UnknownOrigin), unknown.Reason), + _ => throw new ArgumentOutOfRangeException(nameof(service)), + }; + + private static string Number(int value) => value.ToString(CultureInfo.InvariantCulture); + + // Length prefixes prevent a delimiter in a path, reason or other value from making two keys identical. + private static string Parts(params string?[] parts) => Parts((IEnumerable)parts); + + private static string Parts(IEnumerable parts) => + string.Concat(parts.Select(part => part is null ? "-1:" : Number(part.Length) + ":" + part)); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/UserOperation.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/UserOperation.cs new file mode 100644 index 00000000..c7126185 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Graph/UserOperation.cs @@ -0,0 +1,92 @@ +using XrmMockup.PermissionAnalyzer.Core.Extraction; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Core.Graph; + +/// +/// An operation a user makes outside the solution's code, such as updating a record in an app, given with +/// --operation. It needs the privileges of its request rule on its table as the caller, and fires the plugin +/// steps of the rule's messages, setting when they are given. +/// +internal sealed record UserOperation(string Message, string Table, IReadOnlyList? Columns) +{ + /// + /// Where the requirements of a user operation are reported, as there is no code for it. + /// + public static readonly SourceLocation Location = new("--operation", 0, 0); + + public string Display => $"{Message} {Table}"; + + /// + /// A call graph node with the operation's accesses, to evaluate on its own. + /// + public NodeSummary Node(string id, RequestRules rules, LookupColumns lookups) + { + var node = new NodeSummary(id, id, Display, null, false, null, null); + if (rules.Find(Message) is not { } rule) + { + // A message without a rule, such as a custom API, may fire steps on the table + node.Accesses.Add(Access(TableResolution.Unresolved(RequestReasons.NoRule(Message)).Union(TableResolution.Fires(Message, TableResolution.Table(Table), ColumnSet())))); + return node; + } + + var members = new OperationMembers(this, RuleApplication.PrimaryMember(rule), lookups); + foreach (var shape in RequestShapes.All) + { + var tables = RuleApplication.Apply(Message, rule, members, shape); + node.Accesses.Add(RequestShapes.PrivilegeOf(shape) is { } privilege ? Access(tables, privilege) : Access(tables)); + } + return node; + } + + private TableResolution? ColumnSet() => Columns is null ? null : TableResolution.Union(Columns.Select(TableResolution.Table)); + + private AccessFact Access(TableResolution tables, params Privilege[] privileges) => new(Message, Location, privileges, tables, "", Service); + + private static IReadOnlyList Service { get; } = [new FixedOrigin(RunsAs.Caller)]; + + /// + /// The members of a user operation. Its table and columns are those of the member its steps fire on, usually + /// Target; the values of the other members aren't known. + /// + private sealed class OperationMembers(UserOperation operation, string? primary, LookupColumns lookups) : IRequestMembers + { + public TableResolution Tables(string message, string member) => + member == primary ? TableResolution.Table(operation.Table) : TableResolution.Unresolved($"{member} of the {message} request isn't known"); + + public TableResolution? Columns(string member) => member == primary ? operation.ColumnSet() : null; + + // The choices a user makes, such as whether qualifying a lead creates an account, aren't known, so each applies + public bool MayBeSet(string member) => true; + + public IReadOnlyList Rights(string path, out TableResolution reasons) + { + reasons = TableResolution.Unresolved($"the rights granted in {path} aren't known"); + return []; + } + + /// + /// The table when a column set is a lookup, and the tables the lookups refer to: the table when there's + /// one, every target as a lookup target when there are several. + /// + public TableResolution Lookups(string member, TableShape shape) + { + if (member != primary || operation.Columns is null) return TableResolution.Empty; + + var targets = operation.Columns.Select(c => lookups.TargetsOf(operation.Table, c)).Where(t => t.Count > 0).ToList(); + if (targets.Count == 0) return TableResolution.Empty; + if (shape == TableShape.LookupHolder) return TableResolution.Table(operation.Table); + + return TableResolution.Union(targets.SelectMany(target => target.Select(name => target.Count == 1 ? TableResolution.Table(name) : TableResolution.LookupTarget(name)))); + } + + public TableResolution Requests(string member, TableShape shape) => + RequestShapes.Other(shape, $"the requests in {member} of the {operation.Message} request aren't known"); + + public TableResolution Bypass(string message, out PluginBypass bypass) + { + bypass = PluginBypass.None; + return TableResolution.Empty; + } + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/PermissionAnalyzer.Core.csproj b/src/PermissionAnalyzer/PermissionAnalyzer.Core/PermissionAnalyzer.Core.csproj new file mode 100644 index 00000000..e1ec5306 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/PermissionAnalyzer.Core.csproj @@ -0,0 +1,18 @@ + + + + netstandard2.0 + XrmMockup.PermissionAnalyzer.Core + XrmMockup.PermissionAnalyzer.Core + + false + Reusable static Dataverse privilege analysis engine for the CLI and SDK. + + + + + + + + + diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Core/Polyfills/IsExternalInit.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Polyfills/IsExternalInit.cs new file mode 100644 index 00000000..5b331890 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Core/Polyfills/IsExternalInit.cs @@ -0,0 +1,6 @@ +// Enables init-only setters and records when targeting netstandard2.0. +namespace System.Runtime.CompilerServices; + +internal static class IsExternalInit +{ +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/Analyze.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/Analyze.cs new file mode 100644 index 00000000..70f1af8e --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/Analyze.cs @@ -0,0 +1,212 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.PowerPlatform.Dataverse.Client; +using Microsoft.Xrm.Sdk; +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Compiles source in memory against the real Dataverse SDK and analyzes it. +/// +internal static class Analyze +{ + public const string Root = "/src"; + + /// + /// Usings and an early-bound Account and Contact every snippet can use. + /// + private const string Prelude = """ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using Microsoft.Xrm.Sdk; + using Microsoft.Xrm.Sdk.Client; + using Microsoft.Xrm.Sdk.Query; + using Microsoft.Xrm.Sdk.Messages; using Microsoft.Crm.Sdk.Messages; + using Microsoft.Extensions.DependencyInjection; + using XrmPluginCore; + using XrmPluginCore.Enums; + + [EntityLogicalName("account")] + public class Account : Entity { public const string EntityLogicalName = "account"; public Account() : base("account") { } } + + [EntityLogicalName("contact")] + public class Contact : Entity { public const string EntityLogicalName = "contact"; public Contact() : base("contact") { } } + + """; + + /// + /// Look-alikes of the plugin, workflow and Azure Functions APIs, compiled into their own assembly so they are + /// external to the analyzed code, as the real packages are. + /// + private const string Stubs = """ + using System; + using Microsoft.Xrm.Sdk; + using Microsoft.Extensions.DependencyInjection; + + namespace XrmPluginCore.Enums + { + public enum EventOperation { Create, Update, Delete, Retrieve } + public enum ExecutionStage { PreValidation = 10, PreOperation = 20, PostOperation = 40 } + public enum Privilege { Create, Read, Write, Delete, Append, AppendTo, Assign, Share } + public enum ExecutionMode { Synchronous, Asynchronous } + } + + namespace XrmPluginCore.Plugins + { + public class PluginStepConfigBuilder + { + public PluginStepConfigBuilder SetUserContext(Guid userId) => this; + public PluginStepConfigBuilder SetName(string name) => this; + public PluginStepConfigBuilder SetExecutionMode(XrmPluginCore.Enums.ExecutionMode mode) => this; + public PluginStepConfigBuilder AddFilteredAttributes(params System.Linq.Expressions.Expression>[] lambdas) => this; + public PluginStepConfigBuilder AddFilteredAttributes(params string[] attributes) => this; + } + + public class CustomApiConfigBuilder + { + public CustomApiConfigBuilder WithExecutePrivilegeName(string name) => this; + public CustomApiConfigBuilder WithExecutePrivilege(XrmPluginCore.Enums.Privilege privilege) where T : Entity => this; + public CustomApiConfigBuilder WithExecutePrivilege(string schemaName, XrmPluginCore.Enums.Privilege privilege) => this; + } + } + + namespace XrmPluginCore + { + using XrmPluginCore.Enums; + using XrmPluginCore.Plugins; + + public interface IExtendedServiceProvider : IServiceProvider { } + + public class LocalPluginContext + { + public LocalPluginContext(IExtendedServiceProvider serviceProvider) { } + public IOrganizationService OrganizationService => null!; + public IOrganizationService OrganizationAdminService => null!; + public IPluginExecutionContext PluginExecutionContext => null!; + } + + public abstract class Plugin : IPlugin + { + public void Execute(IServiceProvider serviceProvider) { } + protected virtual IServiceCollection OnBeforeBuildServiceProvider(IServiceCollection services) => services; + protected PluginStepConfigBuilder RegisterPluginStep(EventOperation operation, ExecutionStage stage, Action action) where T : Entity => new(); + protected PluginStepConfigBuilder RegisterPluginStep(string operation, ExecutionStage stage, Action action) where T : Entity => new(); + protected PluginStepConfigBuilder RegisterStep(EventOperation operation, ExecutionStage stage, Action action) where TEntity : Entity => new(); + protected PluginStepConfigBuilder RegisterStep(EventOperation operation, ExecutionStage stage, string handlerMethod) where TEntity : Entity => new(); + protected PluginStepConfigBuilder RegisterStep(EventOperation operation, ExecutionStage stage, Action action) where T : Entity => new(); + protected CustomApiConfigBuilder RegisterCustomAPI(string name, Action action) => new(); + protected CustomApiConfigBuilder RegisterAPI(string name, Action action) => new(); + } + } + + namespace System.Activities + { + public class CodeActivityContext { public T GetExtension() where T : class => null!; } + public abstract class CodeActivity { protected abstract void Execute(CodeActivityContext context); } + } + + namespace Microsoft.Azure.Functions.Worker + { + [AttributeUsage(AttributeTargets.Method)] + public sealed class FunctionAttribute(string name) : Attribute { public string Name { get; } = name; } + + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class HttpTriggerAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class TimerTriggerAttribute(string schedule) : Attribute { } + } + """; + + private static readonly Lazy> References = new(() => + { + var platform = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator); + var references = platform + .Append(typeof(Entity).Assembly.Location) + .Append(typeof(IOrganizationServiceAsync2).Assembly.Location) + .Distinct(StringComparer.Ordinal) + .Select(path => (MetadataReference)MetadataReference.CreateFromFile(path)) + .ToList(); + + var stubs = CSharpCompilation.Create( + "Stubs", + [CSharpSyntaxTree.ParseText(Stubs)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + using var image = new MemoryStream(); + var emitted = stubs.Emit(image); + Assert.True(emitted.Success, string.Join("\n", emitted.Diagnostics)); + references.Add(MetadataReference.CreateFromImage(image.ToArray())); + return references; + }); + + /// + /// Compiles as , relative to . + /// + public static CSharpCompilation Compile(string source, string assemblyName = "Test", string file = "Code.cs", params CSharpCompilation[] references) + { + var tree = CSharpSyntaxTree.ParseText(Prelude + source, path: Path.Combine(Root, file)); + var compilation = CSharpCompilation.Create( + assemblyName, + [tree], + References.Value.Concat(references.Select(r => r.ToMetadataReference())), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + + var errors = compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToList(); + Assert.True(errors.Count == 0, string.Join("\n", errors)); + return compilation; + } + + public static Manifest Code( + string source, + IEnumerable? roleGovernedTables = null, + EntryPointSelector? scope = null, + Action? setup = null, + IEnumerable? rules = null, + IEnumerable? lookups = null) + { + var builder = new ManifestBuilder(Root, rules, lookups); + setup?.Invoke(builder); + Assert.True(builder.Add(Compile(source))); + return builder.Build(roleGovernedTables, scope); + } + + /// + /// The single method that performs data operations, which no entry point reaches. + /// + public static MethodManifest Method(string source) + { + var manifest = Code(source); + Assert.Empty(manifest.EntryPoints); + return Assert.Single(manifest.Unreached); + } + + /// + /// The entry point with this id. + /// + public static EntryPoint Entry(this Manifest manifest, string id) => + manifest.EntryPoints.SingleOrDefault(e => e.Id == id) + ?? throw new Xunit.Sdk.XunitException($"No entry point {id}; found: {string.Join(", ", manifest.EntryPoints.Select(e => e.Id))}"); + + /// + /// Requirements as table:Privilege, in manifest order. + /// + public static IReadOnlyList Requirements(this MethodManifest method) => + method.Requirements.Select(r => $"{r.Table}:{r.Privilege}").ToList(); + + /// + /// Requirements as table:Privilege, in manifest order. + /// + public static IReadOnlyList Requirements(this EntryPoint entryPoint) => + entryPoint.Requirements.Select(r => $"{r.Table}:{r.Privilege}").Distinct().ToList(); + + /// + /// Requirements as table:Privilege as RunsAs, in manifest order. + /// + public static IReadOnlyList RequirementsWithIdentity(this EntryPoint entryPoint) => + entryPoint.Requirements.Select(r => $"{r.Table}:{r.Privilege} as {r.RunsAs}").ToList(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/BypassTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/BypassTests.cs new file mode 100644 index 00000000..46be85bb --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/BypassTests.cs @@ -0,0 +1,143 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Requests that bypass custom plugin steps: they need a privilege to, and don't run the steps they bypass. +/// +public class BypassTests +{ + private const string Importer = "method:Contoso.Importer.Run(IOrganizationService)"; + + /// + /// A synchronous account Create step that deletes a lead, an asynchronous one that deletes a task, and an importer + /// that creates an account with a request that sets up. + /// + private static EntryPoint Run(string parameters, Action? setup = null) => + Analyze.Code($$""" + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() + { + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)); + RegisterPluginStep(EventOperation.Create, ExecutionStage.PreOperation, c => c.OrganizationService.Delete("task", Guid.Empty)) + .SetExecutionMode(ExecutionMode.Asynchronous); + } + } + + public class Importer + { + public void Run(IOrganizationService service) + { + var request = new CreateRequest { Target = new Account() }; + {{parameters}} + service.Execute(request); + } + } + } + """, + setup: builder => + { + setup?.Invoke(builder); + builder.AddEntryMethods(["Contoso.Importer.Run"]); + }).Entry(Importer); + + private static IReadOnlyList Globals(EntryPoint entryPoint) => entryPoint.GlobalRequirements.Select(r => r.Privilege).ToList(); + + [Fact] + public void RequestWithoutBypassRunsEveryStep() + { + var run = Run(""); + + Assert.Equal(["account:Create", "lead:Delete", "task:Delete"], run.Requirements()); + Assert.Empty(run.GlobalRequirements); + } + + [Fact] + public void BypassCustomPluginExecutionSkipsSynchronousSteps() + { + var run = Run("""request.Parameters["BypassCustomPluginExecution"] = true;"""); + + Assert.Equal(["account:Create", "task:Delete"], run.Requirements()); + Assert.Equal(["prvBypassCustomPlugins"], Globals(run)); + } + + [Theory] + [InlineData("CustomSync", new[] { "account:Create", "task:Delete" })] + [InlineData("CustomAsync", new[] { "account:Create", "lead:Delete" })] + [InlineData("CustomSync,CustomAsync", new[] { "account:Create" })] + public void BypassBusinessLogicExecutionSkipsTheStepsItNames(string value, string[] requirements) + { + var run = Run($$"""request.Parameters.Add("BypassBusinessLogicExecution", "{{value}}");"""); + + Assert.Equal(requirements, run.Requirements()); + Assert.Equal(["prvBypassCustomBusinessLogic"], Globals(run)); + } + + [Theory] + [InlineData("""request.Parameters["BypassCustomPluginExecution"] = Environment.UserName == "admin";""", "prvBypassCustomPlugins")] + [InlineData("""request.Parameters["BypassBusinessLogicExecution"] = Environment.GetEnvironmentVariable("BYPASS");""", "prvBypassCustomBusinessLogic")] + [InlineData("""request.Parameters["BypassBusinessLogicExecutionStepIds"] = "7d1c4f3a-0000-4000-8000-000000000001";""", "prvBypassCustomBusinessLogic")] + public void BypassThatIsntKnownNeedsThePrivilegeButSkipsNoStep(string parameters, string privilege) + { + var run = Run(parameters); + + Assert.Equal(["account:Create", "lead:Delete", "task:Delete"], run.Requirements()); + Assert.Equal([privilege], Globals(run)); + } + + [Fact] + public void BypassSetToFalseNeedsNothing() + { + var run = Run("""request.Parameters["BypassCustomPluginExecution"] = false;"""); + + Assert.Equal(["account:Create", "lead:Delete", "task:Delete"], run.Requirements()); + Assert.Empty(run.GlobalRequirements); + } + + [Fact] + public void ModeOfAStepFromTheMetadataIsUsed() + { + var run = Run( + """request.Parameters["BypassBusinessLogicExecution"] = "CustomAsync";""", + builder => builder.AddPluginSteps( + [ + new PluginStepRegistration("Contoso.AccountPlugin", "Test", "Create", "account", 40, null, Asynchronous: true), + new PluginStepRegistration("Other.ContactPlugin", "Other", "Create", "account", 40, null, Asynchronous: true), + ])); + + Assert.Equal(["account:Create"], run.Requirements()); + Assert.Empty(run.Unresolved); + } + + [Fact] + public void CustomApiCodeRunsWhateverIsBypassed() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Api : Plugin + { + public Api() => RegisterCustomAPI("ctx_Recalculate", c => c.OrganizationService.Update(new Account())); + } + + public class Importer + { + public void Run(IOrganizationService service) + { + var request = new OrganizationRequest("ctx_Recalculate"); + request.Parameters["BypassBusinessLogicExecution"] = "CustomSync,CustomAsync"; + service.Execute(request); + } + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + var run = manifest.Entry(Importer); + + Assert.Equal(["account:Write"], run.Requirements()); + Assert.Equal(["prvBypassCustomBusinessLogic"], Globals(run)); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/CascadeTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/CascadeTests.cs new file mode 100644 index 00000000..d0680a82 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/CascadeTests.cs @@ -0,0 +1,433 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// The plugin steps and custom APIs that an entry point's operations fire, which run in the same request and need +/// their privileges too. +/// +public class CascadeTests +{ + private const string UserId = "6f1c2a9e-0000-4000-8000-000000000001"; + + /// + /// A contact Create step that updates an account, and an account Update step that deletes a lead. + /// + private const string Plugins = """ + namespace Contoso + { + public class ContactPlugin : Plugin + { + public ContactPlugin() + { + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Update(new Account())); + RegisterPluginStep(EventOperation.Delete, ExecutionStage.PreOperation, c => c.OrganizationService.Delete("task", Guid.Empty)); + } + } + + public class AccountPlugin : Plugin + { + public AccountPlugin() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)); + } + } + """; + + [Fact] + public void FunctionFiresStepsAsItsApplicationUser() + { + var manifest = Analyze.Code(""" + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("ProcessOrder")] + public void Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.Create(new Contact()); + } + } + """ + Plugins); + var function = manifest.Entry("function:Test/ProcessOrder"); + + Assert.Equal( + ["account:Write as ApplicationUser", "contact:Create as ApplicationUser", "lead:Delete as ApplicationUser"], + function.RequirementsWithIdentity()); + Assert.Equal( + ["plugin:Contoso.AccountPlugin:Update:account:PostOperation", "plugin:Contoso.ContactPlugin:Create:contact:PostOperation"], + function.Triggers); + Assert.All(function.Requirements, r => Assert.Equal(RequirementBasis.Direct, r.Basis)); + + var lead = Assert.Single(function.Requirements, r => r.Table == "lead"); + Assert.Equal( + [ + "Functions.Run", + "Create contact", + "plugin:Contoso.ContactPlugin:Create:contact:PostOperation", + "ContactPlugin.ctor (lambda, line 32)", + "Update account", + "plugin:Contoso.AccountPlugin:Update:account:PostOperation", + "AccountPlugin.ctor (lambda, line 39)", + ], + Assert.Single(lead.Sources).Path); + } + + [Fact] + public void StepsFiredForAnotherUserRunAsThatUser() + { + var manifest = Analyze.Code(""" + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("ActForUser")] + public static void ActForUser([Microsoft.Azure.Functions.Worker.TimerTrigger("0 * * * *")] object timer, Guid userId) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.CallerId = userId; + client.Delete("contact", Guid.Empty); + } + } + """ + Plugins); + + Assert.Equal( + ["contact:Delete as ImpersonatedCaller", "task:Delete as ImpersonatedCaller"], + manifest.Entry("function:Test/ActForUser").RequirementsWithIdentity()); + } + + [Fact] + public void ImpersonatingStepRunsAsItsUser() + { + var manifest = Analyze.Code( + """ + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Entity("lead"))); + } + + public class Importer + { + public void Run(IOrganizationService service) => service.Update(new Account()); + } + } + """, + setup: builder => + { + builder.AddPluginSteps([new PluginStepRegistration("Contoso.AccountPlugin", "Test", "Update", "account", 40, UserId)]); + builder.AddEntryMethods(["Contoso.Importer.Run"]); + }); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService)"); + Assert.Equal(["account:Write as ApplicationUser (assumed)", $"lead:Create as User {UserId}"], run.RequirementsWithIdentity()); + } + + [Fact] + public void RequestFiresTheStepsOfEachOfItsMessages() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() + { + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)); + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("task", Guid.Empty)); + RegisterPluginStep("Upsert", ExecutionStage.PostOperation, c => c.OrganizationService.Delete("email", Guid.Empty)); + RegisterPluginStep(EventOperation.Delete, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("fax", Guid.Empty)); + } + } + + public class Importer + { + public void Run(IOrganizationService service) => Save(service, new UpsertRequest { Target = new Account() }); + + static void Save(IOrganizationService service, OrganizationRequest request) => service.Execute(request); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService)"); + Assert.Equal(["account:Create", "account:Write", "email:Delete", "lead:Delete", "task:Delete"], run.Requirements()); + Assert.Equal(3, run.Triggers.Count); + } + + [Fact] + public void WinningAnOpportunityFiresWinStepsOnTheOpportunity() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class OpportunityPlugin : Plugin + { + public OpportunityPlugin() + { + RegisterPluginStep("Win", ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)); + } + } + + [EntityLogicalName("opportunity")] + public class Opportunity : Entity { public Opportunity() : base("opportunity") { } } + + public class Closer + { + public void Run(IOrganizationService service, Guid id) => + service.Execute(new WinOpportunityRequest { OpportunityClose = new Entity("opportunityclose") { ["opportunityid"] = new EntityReference("opportunity", id) }, Status = new OptionSetValue(3) }); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Closer.Run"])); + + var run = manifest.Entry("method:Contoso.Closer.Run(IOrganizationService, Guid)"); + Assert.Equal(["plugin:Contoso.OpportunityPlugin:Win:opportunity:PostOperation"], run.Triggers); + Assert.Equal(["lead:Delete", "opportunity:AppendTo", "opportunity:Write", "opportunityclose:Append", "opportunityclose:Create"], run.Requirements().Order(StringComparer.Ordinal)); + } + + [Fact] + public void StepsThatFireEachOtherAreExpandedOnce() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => + { + c.OrganizationService.Update(new Account()); + c.OrganizationService.Update(new Contact()); + }); + } + + public class ContactPlugin : Plugin + { + public ContactPlugin() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Update(new Account())); + } + } + """); + + var account = manifest.Entry("plugin:Contoso.AccountPlugin:Update:account:PostOperation"); + Assert.Equal(["account:Write", "contact:Write"], account.Requirements()); + Assert.Equal( + ["plugin:Contoso.AccountPlugin:Update:account:PostOperation", "plugin:Contoso.ContactPlugin:Update:contact:PostOperation"], + account.Triggers); + } + + [Fact] + public void OperationOnAnUnknownTableIsReportedAsAPossibleCascade() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Importer + { + public void Run(IOrganizationService service, Entity entity) => service.Delete(entity.LogicalName, entity.Id); + } + } + """ + Plugins, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService, Entity)"); + Assert.Empty(run.Requirements); + Assert.Empty(run.Triggers); + Assert.Equal(2, run.Unresolved.Count(u => u.Operation == "Delete")); + Assert.Single(run.Unresolved, u => u.Reason == "may fire any of 1 Delete steps, because its table isn't known"); + } + + [Fact] + public void OperationOnAnUnknownTableFiresStepsWithoutATable() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class AuditPlugin : Plugin + { + public AuditPlugin() => RegisterPluginStep(EventOperation.Delete, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Entity("task"))); + } + + public class Importer + { + public void Run(IOrganizationService service, Entity entity) => service.Delete(entity.LogicalName, entity.Id); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService, Entity)"); + Assert.Equal(["task:Create"], run.Requirements()); + Assert.Single(run.Triggers); + Assert.DoesNotContain(run.Unresolved, u => u.Reason.StartsWith("may fire", StringComparison.Ordinal)); + } + + [Fact] + public void PrimaryEntityNameIsTheTableOfTheStep() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => Sync(c.OrganizationService, c.PluginExecutionContext)); + + static void Sync(IOrganizationService service, IPluginExecutionContext context) + { + var record = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet()); + service.Update(new Entity(record.LogicalName, record.Id)); + } + } + + public class Importer + { + public void Run(IOrganizationService service, IPluginExecutionContext context) => + service.Delete(context.PrimaryEntityName, Guid.Empty); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + + var step = manifest.Entry("plugin:Contoso.AccountPlugin:Update:account:PostOperation"); + Assert.Equal(["account:Read", "account:Write"], step.Requirements()); + Assert.Empty(step.Unresolved); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService, IPluginExecutionContext)"); + Assert.Contains(run.Unresolved, u => u.Reason == "table name comes from property 'PrimaryEntityName'"); + } + + [Fact] + public void OperationOnALookupFiresTheStepsOfItsTargets() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Importer + { + public void Run(IOrganizationService service, Order order) => + service.Update(new Entity { LogicalName = order.CustomerId!.LogicalName, Id = order.CustomerId.Id }); + } + + [EntityLogicalName("ctx_order")] + public class Order : Entity + { + public Order() : base("ctx_order") { } + + [AttributeLogicalName("ctx_customerid")] + public EntityReference? CustomerId { get => GetAttributeValue("ctx_customerid"); set => this["ctx_customerid"] = value; } + } + } + """ + Plugins, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"]), + lookups: [new LookupColumn("ctx_order", "ctx_customerid", ["account", "contact"])]); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService, Order)"); + Assert.Equal(["plugin:Contoso.AccountPlugin:Update:account:PostOperation"], run.Triggers); + var lead = Assert.Single(run.Requirements, r => r.Table == "lead"); + Assert.Equal(RequirementBasis.AllLookupTargets, lead.Basis); + Assert.Empty(run.Unresolved); + } + + [Fact] + public void MetadataStepWithoutCodeIsAFinding() + { + var manifest = Analyze.Code( + """ + namespace Contoso + { + public class Importer + { + public void Run(IOrganizationService service) => service.Create(new Account()); + } + } + """, + setup: builder => + { + builder.AddPluginSteps( + [ + new PluginStepRegistration("Other.AccountPlugin", "Other", "Create", "account", 20, null), + new PluginStepRegistration("Other.ContactPlugin", "Other", "Create", "contact", 20, null), + ]); + builder.AddEntryMethods(["Contoso.Importer.Run"]); + }); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService)"); + Assert.Equal(["account:Create"], run.Requirements()); + Assert.Equal(["plugin:Other.AccountPlugin:Create:account:PreOperation"], run.Triggers); + var unresolved = Assert.Single(run.Unresolved); + Assert.Equal("fires plugin step plugin:Other.AccountPlugin:Create:account:PreOperation, whose code isn't analyzed", unresolved.Reason); + Assert.Empty(unresolved.Privileges); + } + + [Fact] + public void CustomApiCallRunsItsCode() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Api : Plugin + { + public Api() => RegisterCustomAPI("ctx_Recalculate", c => c.OrganizationService.Update(new Account())); + } + + public class Importer + { + public void Run(IOrganizationService service) => service.Execute(new OrganizationRequest("ctx_Recalculate")); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService)"); + Assert.Equal(["account:Write"], run.Requirements()); + Assert.Single(run.Triggers); + Assert.StartsWith("custom-api:", run.Triggers[0]); + Assert.Empty(run.Unresolved); + } + + [Fact] + public void CustomApiNamedWithRequestSuffixRunsItsCode() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Api : Plugin + { + public Api() => RegisterCustomAPI("ctx_SubmitRequest", c => c.OrganizationService.Update(new Account())); + } + + public class Importer + { + public void Run(IOrganizationService service) => service.Execute(new OrganizationRequest("ctx_SubmitRequest")); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService)"); + Assert.Equal(["account:Write"], run.Requirements()); + Assert.StartsWith("custom-api:", Assert.Single(run.Triggers)); + Assert.Empty(run.Unresolved); + } + + [Fact] + public void CustomApiNamedWithRequestSuffixAndARuleRunsItsCode() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Api : Plugin + { + public Api() => RegisterCustomAPI("ctx_SubmitRequest", c => c.OrganizationService.Update(new Account())); + } + + public class Importer + { + public void Run(IOrganizationService service, Guid id) => + service.Execute(new OrganizationRequest("ctx_SubmitRequest") { ["Target"] = new EntityReference("contact", id) }); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"]), + rules: [new RequestRule("ctx_SubmitRequest") { Checks = [new RuleCheck([Privilege.Read]) { Member = "Target" }] }]); + + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService, Guid)"); + Assert.Equal(["account:Write", "contact:Read"], run.Requirements()); + Assert.StartsWith("custom-api:", Assert.Single(run.Triggers)); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ContextTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ContextTests.cs new file mode 100644 index 00000000..5c12b43c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ContextTests.cs @@ -0,0 +1,176 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// OrganizationServiceContext: LINQ queries, query properties of generated contexts, and changes saved +/// through the context. +/// +public class ContextTests +{ + /// + /// A context like a generated one, with a query property per table. + /// + private const string Context = """ + public class Xrm : OrganizationServiceContext + { + public Xrm(IOrganizationService service) : base(service) { } + + public IQueryable AccountSet => CreateQuery(); + + public IQueryable ContactSet { get { return CreateQuery(); } } + } + """; + + [Fact] + public void QueryPropertyNeedsReadWhereItIsUsed() + { + var method = Analyze.Method(Context + """ + class C + { + List M(IOrganizationService service, Guid id) => + new Xrm(service).AccountSet.Where(a => a.Id == id).ToList(); + } + """); + + Assert.Equal("C.M(IOrganizationService, Guid)", method.Id); + Assert.Equal(["account:Read"], method.Requirements()); + var location = Assert.Single(method.Requirements[0].Sources).Location; + Assert.Equal((28, 26), (location.Line, location.Column)); + } + + [Fact] + public void CreateQueryNeedsRead() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var context = new OrganizationServiceContext(service); + var contacts = context.CreateQuery().ToList(); + var leads = (from l in context.CreateQuery("lead") select l).ToList(); + } + } + """); + + Assert.Equal(["contact:Read", "lead:Read"], method.Requirements()); + } + + [Fact] + public void JoinedQueriesNeedReadAndOnlyTheOuterOneFiresRetrieveMultiple() + { + var manifest = Analyze.Code(Context + """ + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("Contacts")] + public void Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request) + { + var xrm = new Xrm(new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret")); + var names = (from a in xrm.AccountSet + join c in xrm.ContactSet on a.Id equals c.Id + select c.Id).ToList(); + } + } + """, + setup: builder => builder.AddPluginSteps( + [ + new PluginStepRegistration("Contoso.AccountQuery", "Contoso", "RetrieveMultiple", "account", 20, null), + new PluginStepRegistration("Contoso.ContactQuery", "Contoso", "RetrieveMultiple", "contact", 20, null), + ])); + + var function = manifest.Entry("function:Test/Contacts"); + Assert.Equal(["account:Read as ApplicationUser", "contact:Read as ApplicationUser"], function.RequirementsWithIdentity()); + Assert.Equal(["plugin:Contoso.AccountQuery:RetrieveMultiple:account:PreOperation"], function.Triggers); + } + + [Fact] + public void ChangesNeedThePrivilegesOfTheirMessage() + { + var method = Analyze.Method(Context + """ + class C + { + void M(Xrm xrm) + { + xrm.AddObject(new Account()); + var contact = xrm.ContactSet.First(); + xrm.UpdateObject(contact); + xrm.DeleteObject(new Entity("lead")); + xrm.SaveChanges(); + } + } + """); + + Assert.Equal(["account:Create", "contact:Read", "contact:Write", "lead:Delete"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void LinksNeedAppendAndAppendTo() + { + var method = Analyze.Method(Context + """ + class C + { + void M(Xrm xrm, Account account) + { + xrm.AddLink(account, new Relationship("account_contacts"), new Contact()); + xrm.AddRelatedObject(account, new Relationship("account_tasks"), new Entity("task")); + } + } + """); + + Assert.Equal( + ["account:Read", "account:AppendTo", "contact:Read", "contact:Append", "task:Create", "task:Read", "task:Append"], + method.Requirements()); + } + + [Fact] + public void LoadPropertyIsUnresolved() + { + var method = Analyze.Method(Context + """ + class C + { + void M(Xrm xrm, Account account) => xrm.LoadProperty(account, new Relationship("account_contacts")); + } + """); + + Assert.Equal("related records are read through a relationship, whose table isn't known", Assert.Single(method.Unresolved).Reason); + } + + [Fact] + public void ContextRunsAsTheServiceItIsCreatedWith() + { + var manifest = Analyze.Code(Context + """ + namespace Contoso + { + public class ContactPlugin : Plugin + { + public ContactPlugin() => + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => new Archiver(new ArchiveContext(c.OrganizationService)).Run()); + } + + public class ArchiveContext : Xrm + { + public ArchiveContext(IOrganizationService service) : base(service) { } + + public void Archive(Contact contact) => DeleteObject(contact); + } + + public class Archiver + { + private readonly ArchiveContext _xrm; + + public Archiver(ArchiveContext xrm) { _xrm = xrm; } + + public void Run() => _xrm.Archive(_xrm.ContactSet.First()); + } + } + """); + + var step = Assert.Single(manifest.EntryPoints); + Assert.Equal(["contact:Read as Caller", "contact:Delete as Caller"], step.RequirementsWithIdentity()); + Assert.Empty(step.Assumptions); + Assert.Empty(manifest.Unreached); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/CoverageTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/CoverageTests.cs new file mode 100644 index 00000000..6438c562 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/CoverageTests.cs @@ -0,0 +1,620 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool; +using XrmMockup.PermissionAnalyzer.Tool.Commands; +using XrmMockup.PermissionAnalyzer.Tool.Options; +using XrmMockup.PermissionAnalyzer.Tool.Output; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class CoverageTests +{ + private const string UserId = "6a1e5c4d-2b3f-4a5e-8c7d-9e0f1a2b3c4d"; + + private static readonly RoleDefinition Salesperson = Role("Salesperson", + ("account", Privilege.Read, PrivilegeDepth.User), + ("account", Privilege.Write, PrivilegeDepth.User), + ("contact", Privilege.Read, PrivilegeDepth.BusinessUnit)); + + private static readonly RoleDefinition Manager = Role("Sales Manager", + ("account", Privilege.Read, PrivilegeDepth.Organization), + ("contact", Privilege.Create, PrivilegeDepth.User)); + + private static readonly RoleDefinition Integration = Role("Integration App", + ("account", Privilege.Create, PrivilegeDepth.Organization), + ("contact", Privilege.Delete, PrivilegeDepth.Organization)); + + private static readonly string[] Governed = ["account", "contact"]; + + private const string PluginSource = """ + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + + private void Execute(LocalPluginContext context) + { + context.OrganizationService.Retrieve("account", Guid.Empty, new ColumnSet()); + context.OrganizationService.Create(new Contact()); + context.OrganizationAdminService.Delete("contact", Guid.Empty); + } + } + """; + + private const string FunctionSource = """ + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("ProcessOrder")] + public void Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.Create(new Account()); + } + + [Microsoft.Azure.Functions.Worker.Function("ActForUser")] + public static void ActForUser([Microsoft.Azure.Functions.Worker.TimerTrigger("0 * * * *")] object timer, Guid userId) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.CallerId = userId; + client.Delete("contact", Guid.Empty); + } + } + """; + + [Fact] + public void CombinedRolesGrantTheUnionWithTheHighestDepth() + { + var roles = RoleSet.Combine([Salesperson, Manager], "--role"); + + Assert.Equal(["Sales Manager", "Salesperson"], roles.Names); + Assert.Equal(PrivilegeDepth.Organization, roles.Depth("account", Privilege.Read)); + Assert.Equal(PrivilegeDepth.User, roles.Depth("account", Privilege.Write)); + Assert.Equal(PrivilegeDepth.User, roles.Depth("contact", Privilege.Create)); + Assert.Null(roles.Depth("contact", Privilege.Delete)); + Assert.Null(roles.Depth("lead", Privilege.Read)); + } + + [Fact] + public void CallerRequirementsAreCheckedAgainstTheRoles() + { + var manifest = Analyze.Code(PluginSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal( + ["account:Read as Caller: Granted User", "contact:Create as Caller: Missing", "contact:Delete as System: System"], + Results(report, entry)); + Assert.Equal(new CoverageSummary(1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0), report.Summary); + Assert.False(report.Summary.Passed(strict: false)); + + var identity = Assert.Single(report.For(entry).Identities); + Assert.Equal(RunsAs.Caller, identity.RunsAs); + Assert.Equal("Salesperson (--role)", identity.Roles?.ToString()); + } + + [Fact] + public void AnyDepthCountsAndCombinedRolesCover() + { + var manifest = Analyze.Code(PluginSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson, Manager], "--role") }); + + Assert.Equal( + ["account:Read as Caller: Granted Organization", "contact:Create as Caller: Granted User", "contact:Delete as System: System"], + Results(report, manifest.Entry("plugin:P:Update:account:PostOperation"))); + Assert.True(report.Summary.Passed(strict: true)); + } + + [Fact] + public void ApplicationUserRolesComeFromPrincipalsWithTheFunctionWinning() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var options = new CoverageOptions + { + Principals = new Dictionary + { + ["test"] = RoleSet.Combine([Salesperson], "Principals: Test"), + ["Test/ProcessOrder"] = RoleSet.Combine([Integration], "Principals: Test/ProcessOrder"), + }, + }; + var report = CoverageEvaluator.Evaluate(manifest, options); + + var process = manifest.Entry("function:Test/ProcessOrder"); + Assert.Equal(["account:Create as ApplicationUser: Granted Organization"], Results(report, process)); + Assert.Equal("Integration App (Principals: Test/ProcessOrder)", Assert.Single(report.For(process).Identities).Roles?.ToString()); + Assert.True(report.UsesConfiguredRoles); + } + + [Fact] + public void RoleOptionReplacesPrincipals() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var options = new CoverageOptions + { + Roles = RoleSet.Combine([Salesperson], "--role"), + Principals = new Dictionary { ["Test"] = RoleSet.Combine([Integration], "Principals: Test") }, + }; + var report = CoverageEvaluator.Evaluate(manifest, options); + + Assert.Equal(["account:Create as ApplicationUser: Missing"], Results(report, manifest.Entry("function:Test/ProcessOrder"))); + Assert.False(report.UsesConfiguredRoles); + Assert.Empty(report.UnusedPrincipals); + } + + [Fact] + public void ReportListsSettingsThatMatchNothingAnalyzed() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Principals = new Dictionary + { + ["Test/ProcessOrder"] = RoleSet.Combine([Integration], "Principals: Test/ProcessOrder"), + ["Test/Gone"] = RoleSet.Combine([Integration], "Principals: Test/Gone"), + ["Other"] = RoleSet.Combine([Integration], "Principals: Other"), + }, + Users = new Dictionary { [UserId] = RoleSet.Combine([Manager], "Users: svc-plugins") }, + }); + + Assert.Equal(["Other", "Test/Gone"], report.UnusedPrincipals); + Assert.Equal([UserId], report.UnusedUsers); + } + + [Fact] + public void UserIdsInConfigurationAreNormalized() + { + Assert.Equal(UserId, CoverageSetup.UserId("{" + UserId.ToUpperInvariant() + "}")); + var error = Assert.Throws(() => CoverageSetup.UserId("svc-plugins")); + Assert.StartsWith("XrmMockup:Permissions:Users:svc-plugins isn't a user id", error.Message); + } + + [Fact] + public void ApplicationUserWithoutRolesIsNotChecked() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { CallerRoles = RoleSet.Combine([Integration], "--caller-role") }); + + var process = manifest.Entry("function:Test/ProcessOrder"); + Assert.Equal(["account:Create as ApplicationUser: NotChecked"], Results(report, process)); + Assert.Equal("not checked: pass --role, or map Test in XrmMockup:Permissions:Principals", Assert.Single(report.For(process).Identities).Note); + Assert.True(report.Summary.Passed(strict: false)); + Assert.False(report.Summary.Passed(strict: true)); + } + + [Fact] + public void ImpersonatedCallsUseCallerRolesAndNeedActOnBehalfOfAnotherUser() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var withoutCallerRoles = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Integration], "--role") }); + var actForUser = manifest.Entry("function:Test/ActForUser"); + + Assert.Equal(["contact:Delete as ImpersonatedCaller: NotChecked"], Results(withoutCallerRoles, actForUser)); + Assert.StartsWith("not checked: acts for the user in CallerId", withoutCallerRoles.For(actForUser).Identities.Single(i => i.RunsAs.Kind == RunsAsKind.ImpersonatedCaller).Note); + + // The application user's roles don't count: the call runs with the impersonated user's privileges + var withCallerRoles = CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Roles = RoleSet.Combine([Integration], "--role"), + CallerRoles = RoleSet.Combine([Salesperson], "--caller-role"), + }); + Assert.Equal(["contact:Delete as ImpersonatedCaller: Missing"], Results(withCallerRoles, actForUser)); + + // The roles come from metadata without global privileges, so the privilege to impersonate can't be checked + Assert.Equal(["prvActOnBehalfOfAnotherUser as ApplicationUser: Unverifiable"], GlobalResults(withCallerRoles, actForUser)); + Assert.Empty(manifest.Entry("function:Test/ProcessOrder").GlobalRequirements); + Assert.Equal(1, withCallerRoles.Summary.Unverifiable); + } + + [Fact] + public void ImpersonationIsCheckedAgainstGlobalPrivileges() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var actForUser = manifest.Entry("function:Test/ActForUser"); + + var missing = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([WithGlobal(Integration)], "--role") }); + Assert.Equal(["prvActOnBehalfOfAnotherUser as ApplicationUser: Missing"], GlobalResults(missing, actForUser)); + var global = Assert.Single(missing.MissingGlobal); + Assert.Equal((GlobalRequirement.ActOnBehalfOfAnotherUser, RunsAs.ApplicationUser), (global.Privilege, global.RunsAs)); + Assert.Equal(["function:Test/ActForUser"], global.In); + Assert.Equal(0, missing.Summary.Unverifiable); + Assert.False(missing.Summary.Passed(strict: false)); + + var granted = CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Roles = RoleSet.Combine([WithGlobal(Integration, ("prvactonbehalfofanotheruser", PrivilegeDepth.Organization))], "--role"), + }); + Assert.Equal(["prvActOnBehalfOfAnotherUser as ApplicationUser: Granted Organization"], GlobalResults(granted, actForUser)); + } + + [Fact] + public void GlobalPrivilegeCanBeSuppressedByName() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Roles = RoleSet.Combine([WithGlobal(Integration)], "--role"), + Suppress = [CoverageSetup.Suppression(new SuppressionConfiguration { Privilege = "prvActOnBehalfOfAnotherUser", Reason = "set up by hand" }, 0)], + }); + + Assert.Equal(["prvActOnBehalfOfAnotherUser as ApplicationUser: Suppressed"], GlobalResults(report, manifest.Entry("function:Test/ActForUser"))); + Assert.Empty(report.MissingGlobal); + } + + [Fact] + public void SuppressionWithoutTableNeedsAGlobalPrivilegeName() + { + var exception = Assert.Throws(() => CoverageSetup.Suppression(new SuppressionConfiguration { Privilege = "Create" }, 2)); + + Assert.StartsWith("XrmMockup:Permissions:Suppress:2 has no Table", exception.Message); + } + + [Fact] + public void RolesFromOlderMetadataDontKnowGlobalPrivileges() + { + Assert.False(RoleSet.Combine([Integration, WithGlobal(Salesperson)], "--role").KnowsGlobalPrivileges); + Assert.True(RoleSet.Combine([WithGlobal(Integration), WithGlobal(Salesperson)], "--role").KnowsGlobalPrivileges); + } + + [Fact] + public void UnverifiableImpersonationOnlyFailsWhenStrict() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Roles = RoleSet.Combine([Integration], "--role"), + CallerRoles = RoleSet.Combine([Integration], "--caller-role"), + }); + + Assert.True(report.Summary.Passed(strict: false)); + Assert.False(report.Summary.Passed(strict: true)); + } + + [Fact] + public void ImpersonatingUserOfAStepUsesTheUsersMapping() + { + var source = $$""" + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Contact())) + .SetUserContext(new Guid("{{UserId}}")); + } + } + """; + var manifest = Analyze.Code(source, Governed); + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + + // --role is for the caller, not for a specific user + var unmapped = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Manager], "--role") }); + Assert.Equal([$"contact:Create as User {UserId}: NotChecked"], Results(unmapped, entry)); + Assert.Equal($"not checked: runs as user {UserId}; map it in XrmMockup:Permissions:Users", Assert.Single(unmapped.For(entry).Identities).Note); + + var mapped = CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Users = new Dictionary { [UserId.ToUpperInvariant()] = RoleSet.Combine([Manager], "Users: svc-plugins") }, + }); + Assert.Equal([$"contact:Create as User {UserId}: Granted User"], Results(mapped, entry)); + Assert.True(mapped.UsesConfiguredRoles); + } + + [Fact] + public void AssumedIdentitiesAreChecked() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Importer + { + public void Run(IOrganizationService service) => service.Delete("contact", Guid.Empty); + } + } + """, Governed, setup: b => b.AddEntryMethods(["Contoso.Importer.Run"])); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + + Assert.Equal(["contact:Delete as ApplicationUser (assumed): Missing"], Results(report, Assert.Single(manifest.EntryPoints))); + Assert.Equal(1, report.Summary.Missing); + } + + [Fact] + public void TablesNoRoleGovernsAreCovered() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Entity("ctx_log"))); + } + """, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + + Assert.Equal(["ctx_log:Create as Caller: NotGoverned"], Results(report, Assert.Single(manifest.EntryPoints))); + Assert.True(report.Summary.Passed(strict: true)); + } + + [Fact] + public void TablesNoRoleGovernsAreCoveredForIdentitiesWithoutRoles() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Entity("ctx_log"))); + } + """, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions()); + + Assert.Equal(["ctx_log:Create as Caller: NotGoverned"], Results(report, Assert.Single(manifest.EntryPoints))); + Assert.Equal(0, report.Summary.NotChecked); + } + + [Fact] + public void SuppressedPrivilegesDontFail() + { + var manifest = Analyze.Code(PluginSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Roles = RoleSet.Combine([Salesperson], "--role"), + Suppress = [new Suppression("contact", Privilege.Create, "Created by a flow"), new Suppression("account", null, "Not used")], + }); + + var entry = Assert.Single(manifest.EntryPoints); + Assert.Equal( + ["account:Read as Caller: Granted User", "contact:Create as Caller: Suppressed", "contact:Delete as System: System"], + Results(report, entry)); + Assert.Equal("Created by a flow", report.For(entry).For(entry.Requirements[1]).Reason); + Assert.True(report.Summary.Passed(strict: true)); + } + + [Fact] + public void RoleCatalogFindsNamesIgnoringCaseAndSuggestsClosest() + { + var catalog = new RoleCatalog([Integration, Manager, Salesperson]); + + Assert.Same(Salesperson, Assert.Single(catalog.Find("salesperson"))); + Assert.Empty(catalog.Find("Sales")); + Assert.Equal("Salesperson", catalog.Suggest("Salesperon")[0]); + // Both contain the name, so the closer one comes first + Assert.Equal(["Salesperson", "Sales Manager"], catalog.Suggest("sales").Take(2)); + Assert.Empty(catalog.Suggest("Marketing")); + } + + [Fact] + public void UnknownRoleIsAnErrorWithSuggestions() + { + var error = Assert.Throws(() => + CoverageSetup.Create([Integration, Manager, Salesperson], ["Salesperon"], [], new PermissionsConfiguration(), requireRoles: true)); + + Assert.Contains("Unknown security role 'Salesperon' in --role. Did you mean 'Salesperson'", error.Message); + } + + [Fact] + public void UnknownRoleInConfigurationNamesTheSetting() + { + var configuration = new PermissionsConfiguration + { + Principals = new() { ["Contoso.Functions"] = new PrincipalConfiguration { Roles = ["Integration"] } }, + }; + var error = Assert.Throws(() => CoverageSetup.Create([Integration], [], [], configuration, requireRoles: true)); + + Assert.Contains("in XrmMockup:Permissions:Principals:Contoso.Functions. Did you mean 'Integration App'?", error.Message); + } + + [Fact] + public void RoleOptionReplacesPrincipalsWithoutLookingThemUp() + { + var configuration = new PermissionsConfiguration + { + Principals = new() { ["Contoso.Functions"] = new PrincipalConfiguration { Roles = ["Integration"] } }, + }; + var options = CoverageSetup.Create([Integration], ["Integration App"], [], configuration, requireRoles: true); + + Assert.NotNull(options!.Roles); + Assert.Empty(options.Principals); + } + + [Fact] + public void FailingNeedsRolesAndAPlainRunDoesnt() + { + Assert.Null(CoverageSetup.Create([Salesperson], [], [], new PermissionsConfiguration(), requireRoles: false)); + var error = Assert.Throws(() => CoverageSetup.Create([Salesperson], [], [], new PermissionsConfiguration(), requireRoles: true)); + Assert.StartsWith("No roles to check against", error.Message); + } + + [Fact] + public void ConfiguredRolesApplyWithoutFailing() + { + var configuration = new PermissionsConfiguration + { + Principals = new() { ["Contoso.Functions"] = new PrincipalConfiguration { Roles = ["Integration App"] } }, + }; + + Assert.NotNull(CoverageSetup.Create([Integration], [], [], configuration, requireRoles: false)); + // Without roles to look them up in, a plain run only lists what the code needs + Assert.Null(CoverageSetup.Create(null, [], [], configuration, requireRoles: false)); + Assert.Throws(() => CoverageSetup.Create(null, [], [], configuration, requireRoles: true)); + } + + [Fact] + public void SuppressionWithUnknownPrivilegeIsAnError() + { + var configuration = new PermissionsConfiguration { Suppress = [new SuppressionConfiguration { Table = "account", Privilege = "Update" }] }; + var error = Assert.Throws(() => CoverageSetup.Create([Salesperson], ["Salesperson"], [], configuration, requireRoles: true)); + + Assert.StartsWith("XrmMockup:Permissions:Suppress:0 has an unknown Privilege 'Update'", error.Message); + } + + [Fact] + public void MissingPrivilegesAreMergedAcrossEntryPoints() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Contact())); + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Contact())); + RegisterPluginStep(EventOperation.Delete, ExecutionStage.PreOperation, c => c.OrganizationService.Delete("account", Guid.Empty)); + } + } + """, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + + Assert.Equal( + [ + "account:Delete as Caller (Salesperson (--role)) in plugin:P:Delete:account:PreOperation", + "contact:Create as Caller (Salesperson (--role)) in plugin:P:Create:account:PostOperation, plugin:P:Update:account:PostOperation", + ], + report.Missing.Select(m => $"{m.Table}:{m.Privilege} as {m.RunsAs} ({m.Roles}) in {string.Join(", ", m.In)}")); + Assert.Equal(3, report.Summary.Missing); + } + + [Fact] + public void TextOutputMarksEachRequirement() + { + var manifest = Analyze.Code(PluginSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + using var output = new StringWriter(); + new TextManifestWriter(new ReportOptions(Detail.Detailed)).Write(manifest, report, output); + var lines = output.ToString().Split('\n'); + + Assert.Contains(" roles for Caller: Salesperson (--role)", lines); + Assert.Contains(lines, l => l.StartsWith(" ✔ account Read Caller User ", StringComparison.Ordinal)); + Assert.Contains(lines, l => l.StartsWith(" ✘ contact Create Caller missing ", StringComparison.Ordinal)); + Assert.Contains(lines, l => l.StartsWith(" · contact Delete System SYSTEM ", StringComparison.Ordinal)); + Assert.Contains("Result: 1 granted, 1 missing, 1 as SYSTEM", lines); + Assert.Contains("Missing privileges:", lines); + Assert.Contains(" ✘ contact Create Caller Salesperson (--role) in plugin:P:Update:account:PostOperation", lines); + Assert.DoesNotContain(lines, l => l.StartsWith("Not checked: ", StringComparison.Ordinal)); + Assert.Contains(lines, l => l.StartsWith("1 entry point, 0 unreached methods, 2 tables, 3 table privileges (3 requirements counted per entry point and method)", StringComparison.Ordinal)); + } + + [Fact] + public void TextOutputListsWhatWasNotChecked() + { + var summary = new CoverageSummary(Granted: 2, NotGoverned: 0, Missing: 0, Suppressed: 0, NotChecked: 1, System: 0, Unresolved: 3, UnresolvedNoRule: 1, UnresolvedCustomApi: 1, UnresolvedWorkflow: 0, Unverifiable: 1); + Assert.True(summary.Incomplete); + Assert.True(summary.Passed(strict: false)); + Assert.False(summary.Passed(strict: true)); + + var manifest = Analyze.Code(FunctionSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Integration], "--role") }); + using var output = new StringWriter(); + new TextManifestWriter().Write(manifest, report, output); + var line = Assert.Single(output.ToString().Split('\n'), l => l.StartsWith("Not checked: ", StringComparison.Ordinal)); + + Assert.EndsWith("1 privilege not tied to a table (the role metadata predates them; regenerate it)", line); + } + + [Fact] + public void TruncatedAnalysisOnlyFailsWhenStrict() + { + var summary = new CoverageSummary(Granted: 2, NotGoverned: 0, Missing: 0, Suppressed: 0, NotChecked: 0, System: 0, Unresolved: 0, UnresolvedNoRule: 0, UnresolvedCustomApi: 0, UnresolvedWorkflow: 0, Unverifiable: 0, Truncated: 2); + + Assert.True(summary.Incomplete); + Assert.True(summary.Passed(strict: false)); + Assert.False(summary.Passed(strict: true)); + Assert.Equal("Not checked: 2 entry points or methods whose analysis stopped at the call limit", ReportText.NotChecked(summary)); + } + + [Fact] + public void TextOutputCountsRequestsWithoutRuleAndCustomApiCalls() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => + { + c.OrganizationService.Execute(new AddMembersTeamRequest()); + c.OrganizationService.Execute(new OrganizationRequest("ctx_Recalculate")); + c.OrganizationService.Execute(new OrganizationRequest(c.PluginExecutionContext.MessageName)); + }); + } + """, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + using var output = new StringWriter(); + new TextManifestWriter().Write(manifest, report, output); + var line = Assert.Single(output.ToString().Split('\n'), l => l.StartsWith("Not checked: ", StringComparison.Ordinal)); + + Assert.StartsWith("Not checked: 3 unresolved operations (1 request without a rule, 1 custom API call, 1 with an unknown table or request)", line); + } + + [Fact] + public void TextOutputShowsTheImpersonationPrivilege() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Integration], "--role") }); + using var output = new StringWriter(); + new TextManifestWriter(new ReportOptions(Detail.Detailed)).Write(manifest, report, output); + var text = output.ToString(); + + Assert.Matches(@"\n · prvActOnBehalfOfAnotherUser +global +ApplicationUser +unverifiable +", text); + Assert.Contains(" roles for ImpersonatedCaller: not checked: acts for the user in CallerId", text); + Assert.Contains("Privileges not tied to a table: prvActOnBehalfOfAnotherUser\n", text); + Assert.Contains("1 privilege not tied to a table (the role metadata predates them; regenerate it)", text); + } + + [Fact] + public void JsonOutputHasCoverageOnlyWithRoles() + { + var manifest = Analyze.Code(PluginSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + + using var plain = new StringWriter(); + new JsonManifestWriter().Write(manifest, null, plain); + Assert.DoesNotContain("coverage", plain.ToString()); + Assert.DoesNotContain("\"result\"", plain.ToString()); + Assert.DoesNotContain("\"missing\"", plain.ToString()); + + using var covered = new StringWriter(); + new JsonManifestWriter().Write(manifest, report, covered); + var json = covered.ToString(); + Assert.Contains("\"status\": \"granted\"", json); + Assert.Contains("\"depth\": \"User\"", json); + Assert.Contains("\"status\": \"missing\"", json); + Assert.Contains("\"origin\": \"--role\"", json); + Assert.Contains("\"missing\": 1", json); + Assert.Contains("\"unresolvedNoRule\": 0", json); + Assert.Contains("\"unresolvedCustomApi\": 0", json); + Assert.Contains("\"in\": [\n \"plugin:P:Update:account:PostOperation\"\n ]", json); + Assert.Contains("\"incomplete\": false", json); + } + + [Fact] + public void JsonOutputWritesGlobalRequirementsWithoutATable() + { + var manifest = Analyze.Code(FunctionSource, Governed); + var report = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([WithGlobal(Integration)], "--role") }); + using var output = new StringWriter(); + new JsonManifestWriter().Write(manifest, report, output); + var json = output.ToString(); + + Assert.Contains("\"privilege\": \"prvActOnBehalfOfAnotherUser\",\n \"runsAs\": \"ApplicationUser\"", json); + Assert.Contains("\"privilege\": \"Delete\"", json); + Assert.DoesNotContain("impersonation", json); + Assert.Contains("\"missing\": [\n {\n \"privilege\": \"prvActOnBehalfOfAnotherUser\"", json); + } + + private static IReadOnlyList Results(CoverageReport report, EntryPoint entryPoint) => + entryPoint.Requirements.Select(r => + { + var coverage = report.For(entryPoint).For(r); + var depth = coverage.Depth is { } d ? $" {d}" : ""; + return $"{r.Table}:{r.Privilege} as {r.RunsAs}: {coverage.Status}{depth}"; + }).ToList(); + + private static IReadOnlyList GlobalResults(CoverageReport report, EntryPoint entryPoint) => + entryPoint.GlobalRequirements.Select(r => + { + var coverage = report.For(entryPoint).For(r); + var depth = coverage.Depth is { } d ? $" {d}" : ""; + return $"{r.Privilege} as {r.RunsAs}: {coverage.Status}{depth}"; + }).ToList(); + + /// + /// The role as downloaded by a metadata generator that has global privileges. + /// + private static RoleDefinition WithGlobal(RoleDefinition role, params (string Name, PrivilegeDepth Depth)[] globalPrivileges) => + new(role.Name, role.Privileges, globalPrivileges.ToDictionary(p => p.Name, p => p.Depth, StringComparer.OrdinalIgnoreCase)); + + private static RoleDefinition Role(string name, params (string Table, Privilege Privilege, PrivilegeDepth Depth)[] privileges) => + new(name, privileges + .GroupBy(p => p.Table) + .ToDictionary(g => g.Key, g => (IReadOnlyDictionary)g.ToDictionary(p => p.Privilege, p => p.Depth))); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/DeterminismTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/DeterminismTests.cs new file mode 100644 index 00000000..6c313a6d --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/DeterminismTests.cs @@ -0,0 +1,149 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Tool.Output; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class DeterminismTests +{ + private const string Source = """ + namespace Contoso + { + class B { void Z(IOrganizationService s) { s.Delete("contact", Guid.Empty); s.Create(new Account()); } } + class A { void Y(IOrganizationService s, Entity e) { s.Update(e); s.Retrieve("account", Guid.Empty, new ColumnSet()); } } + + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => new B2().Run(c.OrganizationService)); + RegisterPluginStep(EventOperation.Create, ExecutionStage.PreOperation, c => new B2().Run(c.OrganizationAdminService)); + } + } + + public interface IStore { void Save(IOrganizationService s); } + public class S1 : IStore { public void Save(IOrganizationService s) => s.Create(new Contact()); } + public class S2 : IStore { public void Save(IOrganizationService s) => s.Create(new Account()); } + class B2 { public IStore? Store; public void Run(IOrganizationService s) { Store!.Save(s); s.Delete("contact", Guid.Empty); } } + } + """; + + [Fact] + public void SameCompilationAddedTwiceMergesAndOutputIsStable() + { + // A multi-targeted project is analyzed once per target framework + var once = new ManifestBuilder(Analyze.Root); + once.Add(Analyze.Compile(Source)); + + var twice = new ManifestBuilder(Analyze.Root); + twice.Add(Analyze.Compile(Source)); + twice.Add(Analyze.Compile(Source)); + + foreach (var writer in new IManifestWriter[] { new TextManifestWriter(), new TextManifestWriter(new ReportOptions(Detail.Compact)), new TextManifestWriter(new ReportOptions(Detail.Normal)), new TextManifestWriter(new ReportOptions(Detail.Full)), new JsonManifestWriter(), new MarkdownManifestWriter(), new SarifManifestWriter() }) + { + Assert.Equal(Write(writer, once), Write(writer, twice)); + } + } + + [Fact] + public void ACallThatResolvesDifferentlyPerTargetFrameworkKeepsBoth() + { + // The call is at the same place in both compilations, but its constant differs, as with #if per framework + const string Call = """ + namespace Contoso + { + class Cleanup { void Run(IOrganizationService s) => s.Delete(Names.Table, Guid.Empty); } + } + """; + var builder = new ManifestBuilder(Analyze.Root); + builder.Add(Analyze.Compile(Call + """static class Names { public const string Table = "account"; }""")); + builder.Add(Analyze.Compile(Call + """static class Names { public const string Table = "contact"; }""")); + + Assert.Equal(["account:Delete", "contact:Delete"], Assert.Single(builder.Build().Unreached).Requirements()); + } + + [Fact] + public void OutputDoesNotDependOnCompilationOrder() + { + var forward = new ManifestBuilder(Analyze.Root); + forward.Add(Analyze.Compile(Source, "Contoso.A")); + forward.Add(Analyze.Compile(Source, "Contoso.B")); + + var backward = new ManifestBuilder(Analyze.Root); + backward.Add(Analyze.Compile(Source, "Contoso.B")); + backward.Add(Analyze.Compile(Source, "Contoso.A")); + + foreach (var writer in new IManifestWriter[] { new TextManifestWriter(), new TextManifestWriter(new ReportOptions(Detail.Compact)), new TextManifestWriter(new ReportOptions(Detail.Normal)), new TextManifestWriter(new ReportOptions(Detail.Full)), new JsonManifestWriter(), new MarkdownManifestWriter(), new SarifManifestWriter() }) + { + Assert.Equal(Write(writer, forward), Write(writer, backward)); + } + } + + [Fact] + public void UnreachedMethodsAreSortedOrdinally() + { + var manifest = Analyze.Code(Source); + Assert.Equal(["Contoso.A.Y(IOrganizationService, Entity)", "Contoso.B.Z(IOrganizationService)"], manifest.Unreached.Select(m => m.Id)); + } + + [Fact] + public void OverloadsThatOnlyDifferInGenericsOrNamespacesHaveTheirOwnIds() + { + const string Source = """ + namespace Contoso.A { class Record { } } + namespace Contoso.B { class Record { } } + namespace Contoso + { + class Sync + { + void Run(IOrganizationService s) { s.Delete("account", Guid.Empty); } + void Run(IOrganizationService s) { s.Delete("contact", Guid.Empty); } + void Save(IOrganizationService s, A.Record r) { s.Delete("lead", Guid.Empty); } + void Save(IOrganizationService s, B.Record r) { s.Delete("task", Guid.Empty); } + } + } + """; + var manifest = Analyze.Code(Source); + + Assert.Equal( + [ + "Contoso.Sync.Run(IOrganizationService): account:Delete", + "Contoso.Sync.Run(IOrganizationService): contact:Delete", + "Contoso.Sync.Save(Microsoft.Xrm.Sdk.IOrganizationService, Contoso.A.Record): lead:Delete", + "Contoso.Sync.Save(Microsoft.Xrm.Sdk.IOrganizationService, Contoso.B.Record): task:Delete", + ], + manifest.Unreached.Select(m => m.Id + ": " + string.Join(", ", m.Requirements()))); + + // A method name matches its generic overloads too + var entries = Analyze.Code(Source, setup: builder => builder.AddEntryMethods(["Contoso.Sync.Run"])); + Assert.Equal(["method:Contoso.Sync.Run(IOrganizationService)", "method:Contoso.Sync.Run(IOrganizationService)"], entries.EntryPoints.Select(e => e.Id)); + } + + [Fact] + public void OutputUsesLineFeeds() + { + var builder = new ManifestBuilder(Analyze.Root); + builder.Add(Analyze.Compile(Source)); + var text = Write(new JsonManifestWriter(), builder) + Write(new TextManifestWriter(), builder) + Write(new MarkdownManifestWriter(), builder) + Write(new SarifManifestWriter(), builder); + Assert.DoesNotContain('\r', text); + } + + [Fact] + public void JsonListsEntryPointsWithIdentities() + { + var builder = new ManifestBuilder(Analyze.Root); + builder.Add(Analyze.Compile(Source)); + var json = Write(new JsonManifestWriter(), builder); + + Assert.Contains("\"id\": \"plugin:Contoso.P:Update:contact:PostOperation\"", json); + Assert.Contains("\"runsAs\": \"System\"", json); + Assert.Contains("\"basis\": \"all-implementations\"", json); + Assert.Contains("\"unreached\": [", json); + } + + private static string Write(IManifestWriter writer, ManifestBuilder builder) + { + using var output = new StringWriter(); + writer.Write(builder.Build(["account"]), null, output); + return output.ToString(); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/EntryPointTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/EntryPointTests.cs new file mode 100644 index 00000000..4962fd2b --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/EntryPointTests.cs @@ -0,0 +1,548 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class EntryPointTests +{ + private const string UserId = "6a1e5c4d-2b3f-4a5e-8c7d-9e0f1a2b3c4d"; + + [Fact] + public void PluginCoreStepRunsAsCaller() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, context => + context.OrganizationService.Create(new Contact())); + } + } + } + """); + + var entry = manifest.Entry("plugin:Contoso.AccountPlugin:Update:account:PostOperation"); + Assert.Equal(EntryPointKind.PluginStep, entry.Kind); + Assert.Equal("Contoso.AccountPlugin", entry.Type); + Assert.Equal(new Trigger("Update", "account", "PostOperation"), entry.Trigger); + Assert.Equal(["contact:Create as Caller"], entry.RequirementsWithIdentity()); + Assert.Empty(manifest.Unreached); + } + + [Fact] + public void AdminServiceRunsAsSystem() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep("Create", ExecutionStage.PreOperation, Execute); + + private void Execute(LocalPluginContext context) + { + context.OrganizationAdminService.Delete("contact", Guid.Empty); + context.OrganizationService.Retrieve("account", Guid.Empty, new ColumnSet()); + } + } + """); + + var entry = manifest.Entry("plugin:P:Create:account:PreOperation"); + Assert.Equal(["account:Read as Caller", "contact:Delete as System"], entry.RequirementsWithIdentity()); + } + + [Fact] + public void SetUserContextRunsAsThatUser() + { + var manifest = Analyze.Code($$""" + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Contact())) + .SetUserContext(new Guid("{{UserId}}")); + } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(UserId, entry.ImpersonatingUserId); + Assert.Equal([$"contact:Create as User {UserId}"], entry.RequirementsWithIdentity()); + } + + [Fact] + public void CallsAreFollowedWithServiceAndTableArguments() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + + private void Execute(LocalPluginContext context) => new Helper().Touch(context.OrganizationService, "contact"); + } + + public class Helper + { + public void Touch(IOrganizationService service, string table) => service.Delete(table, Guid.Empty); + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + var requirement = Assert.Single(entry.Requirements); + Assert.Equal(("contact", Privilege.Delete, RunsAs.Caller), (requirement.Table, requirement.Privilege, requirement.RunsAs)); + Assert.Equal(2, Assert.Single(requirement.Sources).Path.Count); + Assert.Empty(entry.Unresolved); + Assert.Empty(manifest.Unreached); + } + + [Fact] + public void ServiceReturnedThroughRecursiveCallsEndsAtTheDepthLimit() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + + private void Execute(LocalPluginContext context) => Services.Get(context.OrganizationService, 3).Create(new Contact()); + } + + public static class Services + { + public static IOrganizationService Get(IOrganizationService service, int n) => n == 0 ? service : Get(Get(service, n - 1), n - 1); + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Contains("contact:Create as Caller", entry.RequirementsWithIdentity()); + } + + [Fact] + public void ServiceFromAnOutArgumentIsAssumed() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + + private void Execute(LocalPluginContext context) + { + if (TryGet(context, out var service)) service.Create(new Contact()); + } + + private static bool TryGet(LocalPluginContext context, out IOrganizationService service) + { + service = context.OrganizationService; + return true; + } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal("local 'service' is passed by ref or out", Assert.Single(entry.Assumptions).Reason); + } + + [Fact] + public void ServiceAssignedByDeconstructionIsAssumed() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + + private void Execute(LocalPluginContext context) + { + IOrganizationService service; + int retries; + (service, retries) = (context.OrganizationService, 3); + service.Create(new Contact()); + } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal("local 'service' is assigned by deconstruction", Assert.Single(entry.Assumptions).Reason); + } + + [Fact] + public void ServiceAssignedWithCoalesceIsFollowed() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + + private void Execute(LocalPluginContext context) + { + IOrganizationService? service = null; + service ??= context.OrganizationAdminService; + service.Create(new Contact()); + } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Contains("contact:Create as System", entry.RequirementsWithIdentity()); + } + + [Fact] + public void InjectedServiceUsesRegisteredImplementation() + { + var manifest = Analyze.Code(""" + public interface IAccountService { void HandleCreate(); void HandleUpdate(); } + + public class AccountService(IOrganizationServiceFactory factory, IPluginExecutionContext context) : IAccountService + { + private readonly IOrganizationService service = factory.CreateOrganizationService(context.UserId); + public void HandleCreate() => service.Create(new Contact()); + public void HandleUpdate() => service.Update(new Account()); + } + + public class OtherAccountService : IAccountService + { + public void HandleCreate() { } + public void HandleUpdate() { } + } + + public class P : Plugin + { + public P() + { + RegisterStep(EventOperation.Create, ExecutionStage.PostOperation, s => s.HandleCreate()); + RegisterStep(EventOperation.Update, ExecutionStage.PostOperation, nameof(IAccountService.HandleUpdate)); + } + + protected override IServiceCollection OnBeforeBuildServiceProvider(IServiceCollection services) => + services.AddScoped(); + } + """); + + var create = manifest.Entry("plugin:P:Create:account:PostOperation"); + Assert.Equal(["contact:Create as Caller"], create.RequirementsWithIdentity()); + Assert.Equal(RequirementBasis.Direct, create.Requirements[0].Basis); + + var update = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["account:Write as Caller"], update.RequirementsWithIdentity()); + } + + [Fact] + public void UnregisteredInterfaceCallReachesAllImplementations() + { + var manifest = Analyze.Code(""" + public interface IStore { void Save(IOrganizationService service); } + public class AccountStore : IStore { public void Save(IOrganizationService service) => service.Create(new Account()); } + public class ContactStore : IStore { public void Save(IOrganizationService service) => service.Create(new Contact()); } + + public class P : Plugin + { + private readonly IStore store; + public P(IStore store) + { + this.store = store; + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => this.store.Save(c.OrganizationService)); + } + } + """); + + var entry = manifest.Entry("plugin:P:Create:account:PostOperation"); + Assert.Equal(["account:Create as Caller", "contact:Create as Caller"], entry.RequirementsWithIdentity()); + Assert.All(entry.Requirements, r => Assert.Equal(RequirementBasis.AllImplementations, r.Basis)); + } + + [Fact] + public void CustomApiIsAnEntryPoint() + { + var manifest = Analyze.Code(""" + public class DoThing : Plugin + { + public DoThing() => RegisterCustomAPI("ctx_DoThing", c => c.OrganizationService.Create(new Account())); + } + """); + + var entry = manifest.Entry("custom-api:ctx_DoThing"); + Assert.Equal(EntryPointKind.CustomApi, entry.Kind); + Assert.Equal(["account:Create as Caller"], entry.RequirementsWithIdentity()); + } + + [Fact] + public void CodeActivityRunsAsCaller() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class Activity : System.Activities.CodeActivity + { + protected override void Execute(System.Activities.CodeActivityContext context) + { + var execution = context.GetExtension(); + var factory = context.GetExtension(); + var service = factory.CreateOrganizationService(execution.UserId) as IOrganizationService; + service.Create(new Contact()); + } + } + } + """); + + var entry = manifest.Entry("activity:Contoso.Activity"); + Assert.Equal(EntryPointKind.CodeActivity, entry.Kind); + Assert.Equal(["contact:Create as Caller"], entry.RequirementsWithIdentity()); + } + + [Fact] + public void AzureFunctionRunsAsApplicationUser() + { + var manifest = Analyze.Code(""" + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("ProcessOrder")] + public void Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.Create(new Account()); + } + + [Microsoft.Azure.Functions.Worker.Function("ActForUser")] + public static void ActForUser([Microsoft.Azure.Functions.Worker.TimerTrigger("0 * * * *")] object timer, Guid userId) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.CallerId = userId; + client.Delete("contact", Guid.Empty); + } + } + """); + + var process = manifest.Entry("function:Test/ProcessOrder"); + Assert.Equal(EntryPointKind.Function, process.Kind); + Assert.Equal("HttpTrigger", process.Trigger?.Binding); + Assert.Equal(["account:Create as ApplicationUser"], process.RequirementsWithIdentity()); + + var actForUser = manifest.Entry("function:Test/ActForUser"); + Assert.Equal("TimerTrigger", actForUser.Trigger?.Binding); + Assert.Equal(["contact:Delete as ImpersonatedCaller"], actForUser.RequirementsWithIdentity()); + } + + [Fact] + public void FunctionsOfTheSameNameInTwoAppsAreSelectedByTheirAssembly() + { + const string Source = """ + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("ProcessOrder")] + public void Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.Create(new Account()); + } + } + """; + Manifest Select(string function) + { + var builder = new ManifestBuilder(Analyze.Root); + builder.Add(Analyze.Compile(Source, "Contoso.Orders")); + builder.Add(Analyze.Compile(Source, "Contoso.Returns")); + return builder.Build(scope: EntryPointSelector.Function(function)); + } + + Assert.Equal(["function:Contoso.Orders/ProcessOrder", "function:Contoso.Returns/ProcessOrder"], Select("processorder").EntryPoints.Select(e => e.Id)); + Assert.Equal(["function:Contoso.Returns/ProcessOrder"], Select("Contoso.Returns/ProcessOrder").EntryPoints.Select(e => e.Id)); + } + + [Fact] + public void FunctionReachesServicesInReferencedProject() + { + // A function app whose Dataverse calls are all in a shared library, registered with DI + var library = Analyze.Compile(""" + namespace Contoso.Logic + { + public interface ITemplateService { void Delete(Guid id); } + public class TemplateService(IOrganizationService service) : ITemplateService + { + public void Delete(Guid id) => service.Update(new Account { Id = id }); + } + public static class Handler + { + public static async Task HandleAsync(Func> action) => await action(); + } + public static class Registration + { + public static IServiceCollection AddLogic(this IServiceCollection services) => services.AddScoped(); + } + } + """, "Contoso.Logic"); + var functions = Analyze.Compile(""" + namespace Contoso.Functions + { + public class DeleteTemplate(Contoso.Logic.ITemplateService templates) + { + [Microsoft.Azure.Functions.Worker.Function("DeleteTemplate")] + public Task Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request, Guid id) => + Contoso.Logic.Handler.HandleAsync(async () => { templates.Delete(id); return id; }); + } + } + """, "Contoso.Functions", references: library); + + var builder = new ManifestBuilder(Analyze.Root); + Assert.True(builder.Add(library)); + Assert.True(builder.Add(functions)); + var manifest = builder.Build(["account"]); + + Assert.Equal(["account:Write as ApplicationUser (assumed)"], manifest.Entry("function:Contoso.Functions/DeleteTemplate").RequirementsWithIdentity()); + Assert.Empty(manifest.Unreached); + } + + [Fact] + public void MethodsNoEntryPointReachesAreUnreached() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => Used(c.OrganizationService)); + private static void Used(IOrganizationService s) => s.Create(new Contact()); + } + + public class Unused + { + public void M(IOrganizationService s) => s.Delete("account", Guid.Empty); + } + """); + + Assert.Single(manifest.EntryPoints); + var unreached = Assert.Single(manifest.Unreached); + Assert.Equal("Unused.M(IOrganizationService)", unreached.Id); + Assert.Equal(["account:Delete"], unreached.Requirements()); + } + + [Fact] + public void PlainPluginGetsOneEntryPointPerMetadataStep() + { + const string source = """ + namespace Contoso + { + public class LegacyPlugin : IPlugin + { + public void Execute(IServiceProvider serviceProvider) + { + var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext))!; + var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))!; + var service = factory.CreateOrganizationService(context.UserId); + service.Create(new Contact()); + } + } + } + """; + + var withoutSteps = Analyze.Code(source); + var plugin = withoutSteps.Entry("plugin:Contoso.LegacyPlugin"); + Assert.Equal(EntryPointKind.Plugin, plugin.Kind); + Assert.Equal(["contact:Create as Caller"], plugin.RequirementsWithIdentity()); + + var withSteps = Analyze.Code(source, setup: builder => builder.AddPluginSteps( + [ + new PluginStepRegistration("Contoso.LegacyPlugin", "Test", "Update", "account", 40, UserId.ToUpperInvariant()), + new PluginStepRegistration("Contoso.LegacyPlugin", "Other", "Create", "contact", 20, null), + ])); + + Assert.Equal( + ["plugin:Contoso.LegacyPlugin:Create:contact:PreOperation", "plugin:Contoso.LegacyPlugin:Update:account:PostOperation"], + withSteps.EntryPoints.Select(e => e.Id)); + var impersonated = withSteps.Entry("plugin:Contoso.LegacyPlugin:Update:account:PostOperation"); + Assert.Equal(UserId, impersonated.ImpersonatingUserId); + Assert.Equal([$"contact:Create as User {UserId}"], impersonated.RequirementsWithIdentity()); + } + + [Fact] + public void MetadataStepAddsImpersonationToCodeStep() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Contact())); + } + """, + setup: builder => builder.AddPluginSteps([new PluginStepRegistration("P", "Test", "update", "account", 40, UserId)])); + + var entry = Assert.Single(manifest.EntryPoints); + Assert.Equal("plugin:P:Update:account:PostOperation", entry.Id); + Assert.Equal([$"contact:Create as User {UserId}"], entry.RequirementsWithIdentity()); + } + + [Fact] + public void ScopeSelectsEntryPoints() + { + const string source = """ + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Contact())); + RegisterPluginStep(EventOperation.Create, ExecutionStage.PreOperation, c => c.OrganizationService.Delete("contact", Guid.Empty)); + } + } + + public class Importer + { + public void Run(IOrganizationService service) => service.Update(new Account()); + public void Run(IOrganizationService service, string table) => service.Delete(table, Guid.Empty); + } + } + """; + + var plugin = Analyze.Code(source, scope: EntryPointSelector.Plugin("accountplugin:Update")); + Assert.Equal(["plugin:Contoso.AccountPlugin:Update:account:PostOperation"], plugin.EntryPoints.Select(e => e.Id)); + Assert.Empty(plugin.Unreached); + + var stage = Analyze.Code(source, scope: EntryPointSelector.Plugin("Contoso.AccountPlugin:Create:PreOperation")); + Assert.Equal(["plugin:Contoso.AccountPlugin:Create:account:PreOperation"], stage.EntryPoints.Select(e => e.Id)); + + var methods = Analyze.Code( + source, + scope: EntryPointSelector.Methods(["Contoso.Importer.Run"]), + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + Assert.Equal( + ["method:Contoso.Importer.Run(IOrganizationService)", "method:Contoso.Importer.Run(IOrganizationService, string)"], + methods.EntryPoints.Select(e => e.Id)); + // The update fires the account plugin's Update step, which runs as the same identity + Assert.Equal(["account:Write as ApplicationUser (assumed)", "contact:Create as ApplicationUser (assumed)"], methods.EntryPoints[0].RequirementsWithIdentity()); + Assert.Equal(["plugin:Contoso.AccountPlugin:Update:account:PostOperation"], methods.EntryPoints[0].Triggers); + + var none = Analyze.Code(source, scope: EntryPointSelector.Function("Missing")); + Assert.Empty(none.EntryPoints); + } + + [Fact] + public void PluginOverridingBaseExecuteRunsTheOverride() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public abstract class PluginBase : IPlugin + { + public virtual void Execute(IServiceProvider serviceProvider) { } + } + + public class DaxifBase : IPlugin + { + public void Execute(IServiceProvider serviceProvider) { } + } + + public class Derived : DaxifBase { } + + public class ContactPlugin : PluginBase + { + public override void Execute(IServiceProvider serviceProvider) + { + var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))!; + factory.CreateOrganizationService(null).Create(new Contact()); + } + } + } + """); + + // DaxifBase is only a base class, so it gets no entry point of its own + Assert.Equal(["plugin:Contoso.ContactPlugin", "plugin:Contoso.Derived"], manifest.EntryPoints.Select(e => e.Id)); + Assert.Equal(["contact:Create as System"], manifest.Entry("plugin:Contoso.ContactPlugin").RequirementsWithIdentity()); + Assert.Empty(manifest.Unreached); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExecutePrivilegeTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExecutePrivilegeTests.cs new file mode 100644 index 00000000..bb79ddd1 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExecutePrivilegeTests.cs @@ -0,0 +1,162 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class ExecutePrivilegeTests +{ + private const string Importer = "method:Contoso.Importer.Run(IOrganizationService)"; + + private static readonly PrivilegeDefinition ReadOrder = new("prvReadctx_Order", Privilege.Read, ["ctx_order"]); + private static readonly PrivilegeDefinition ActOnBehalf = new("prvActOnBehalfOfAnotherUser", null, []); + private static readonly PrivilegeDefinition PublishCustomization = new("prvPublishCustomization", null, ["solution"]); + + /// + /// A custom API registered with and a method that calls it. + /// + private static Manifest Run(string configuration, Action? setup = null) => + Analyze.Code($$""" + namespace Contoso + { + public class Api : Plugin + { + public Api() => RegisterCustomAPI("ctx_Recalculate", c => c.OrganizationService.Update(new Account())){{configuration}}; + } + + public class Importer + { + public void Run(IOrganizationService service) => service.Execute(new OrganizationRequest("ctx_Recalculate")); + } + } + """, + setup: builder => + { + setup?.Invoke(builder); + builder.AddEntryMethods(["Contoso.Importer.Run"]); + }); + + [Fact] + public void ExecutePrivilegeOnAnEarlyBoundTableIsRequired() + { + var manifest = Run(".WithExecutePrivilege(XrmPluginCore.Enums.Privilege.Read)"); + var run = manifest.Entry(Importer); + + Assert.Equal(["account:Read", "account:Write"], run.Requirements()); + Assert.Equal(RequirementBasis.ExecutePrivilege, run.Requirements.Single(r => r.Privilege == Privilege.Read).Basis); + Assert.Empty(run.Unresolved); + } + + [Fact] + public void ExecutePrivilegeOnASchemaNameIsRequiredOnTheLogicalName() + { + var run = Run(""".WithExecutePrivilege("ctx_Order", XrmPluginCore.Enums.Privilege.Write)""").Entry(Importer); + + Assert.Equal(["account:Write", "ctx_order:Write"], run.Requirements()); + } + + [Fact] + public void CustomApiEntryPointNeedsItsExecutePrivilegeForTheCaller() + { + var api = Assert.Single(Run(".WithExecutePrivilege(XrmPluginCore.Enums.Privilege.Read)").EntryPoints, e => e.Kind == EntryPointKind.CustomApi); + + var requirement = Assert.Single(api.Requirements, r => r.Privilege == Privilege.Read); + Assert.Equal(RunsAs.Caller, requirement.RunsAs); + Assert.Empty(Assert.Single(requirement.Sources).Path); + } + + [Fact] + public void ExecutePrivilegeNameNeedsThePrivilegeCatalog() + { + var run = Run(""".WithExecutePrivilegeName("prvReadctx_Order")""").Entry(Importer); + + var unresolved = Assert.Single(run.Unresolved); + Assert.Equal("ctx_Recalculate", unresolved.Operation); + Assert.Equal( + "custom API 'ctx_Recalculate' needs execute privilege 'prvReadctx_Order', which needs a privilege catalog (PrivilegeCatalog.xml) to look up", + unresolved.Reason); + Assert.Equal(["account:Write"], run.Requirements()); + } + + [Fact] + public void ExecutePrivilegeNameIsLookedUpInThePrivilegeCatalog() + { + var run = Run(""".WithExecutePrivilegeName("PRVREADCTX_ORDER")""", b => b.AddPrivilegeCatalog([ReadOrder], [])).Entry(Importer); + + Assert.Equal(["account:Write", "ctx_order:Read"], run.Requirements()); + Assert.Empty(run.Unresolved); + } + + [Fact] + public void ExecutePrivilegeNotTiedToATableIsAGlobalRequirement() + { + var run = Run(""".WithExecutePrivilegeName("prvActOnBehalfOfAnotherUser")""", b => b.AddPrivilegeCatalog([ActOnBehalf], [])).Entry(Importer); + + var global = Assert.Single(run.GlobalRequirements); + Assert.Equal(("prvActOnBehalfOfAnotherUser", RequirementBasis.ExecutePrivilege), (global.Privilege, global.Basis)); + Assert.Equal(["account:Write"], run.Requirements()); + } + + [Theory] + [InlineData(""" + .WithExecutePrivilegeName("prvUnknown") + """, "custom API 'ctx_Recalculate' needs execute privilege 'prvUnknown', which isn't in the privilege catalog")] + [InlineData(""" + .WithExecutePrivilegeName("prvPublishCustomization") + """, "custom API 'ctx_Recalculate' needs execute privilege 'prvPublishCustomization', whose access right isn't a table privilege")] + [InlineData(""" + .WithExecutePrivilegeName(System.Environment.GetEnvironmentVariable("PRIVILEGE")) + """, "custom API 'ctx_Recalculate' needs an execute privilege set at runtime")] + public void ExecutePrivilegeThatCantBeLookedUpIsUnresolved(string configuration, string reason) + { + var run = Run(configuration, b => b.AddPrivilegeCatalog([ActOnBehalf, PublishCustomization], [])).Entry(Importer); + + Assert.Equal(reason, Assert.Single(run.Unresolved).Reason); + } + + [Fact] + public void CustomApiOnlyInTheCatalogNeedsItsExecutePrivilege() + { + var manifest = Analyze.Code(""" + class C + { + void M(IOrganizationService service) + { + service.Execute(new OrganizationRequest("ctx_Export")); + service.Execute(new OrganizationRequest("ctx_Ping")); + } + } + """, + setup: b => b.AddPrivilegeCatalog([ReadOrder], [new CustomApiDefinition("ctx_Export", "prvReadctx_Order"), new CustomApiDefinition("ctx_Ping", null)])); + var method = Assert.Single(manifest.Unreached); + + Assert.Equal(["ctx_order:Read"], method.Requirements()); + Assert.Equal( + ["custom API 'ctx_Export' is called; its code isn't analyzed", "custom API 'ctx_Ping' is called; its code isn't analyzed"], + method.Unresolved.Select(u => u.Reason)); + } + + [Fact] + public void ImpersonationNeedsActOnBehalfOfAnotherUserOnTheImpersonator() + { + var manifest = Analyze.Code(""" + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("ActForUser")] + public static void ActForUser([Microsoft.Azure.Functions.Worker.TimerTrigger("0 * * * *")] object timer, Guid userId) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.CallerId = userId; + client.Delete("contact", Guid.Empty); + client.Create(new Account()); + } + } + """); + var actForUser = manifest.Entry("function:Test/ActForUser"); + + var global = Assert.Single(actForUser.GlobalRequirements); + Assert.Equal( + (GlobalRequirement.ActOnBehalfOfAnotherUser, RunsAs.ApplicationUser, RequirementBasis.Direct), + (global.Privilege, global.RunsAs, global.Basis)); + Assert.Equal(2, global.Sources.Count); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExecuteRuleTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExecuteRuleTests.cs new file mode 100644 index 00000000..53be7fd4 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExecuteRuleTests.cs @@ -0,0 +1,477 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool; +using XrmMockup.PermissionAnalyzer.Tool.Commands; +using XrmMockup.PermissionAnalyzer.Tool.Options; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Requests passed to Execute, read through the rule for their message. +/// +public class ExecuteRuleTests +{ + [Fact] + public void TypedRequestUsesItsRule() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) + { + service.Execute(new CreateRequest { Target = new Account() }); + service.Execute(new AssignRequest { Target = new EntityReference("contact", id) }); + } + } + """); + + Assert.Equal(["account:Create", "contact:Write", "contact:Assign"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void UpsertNeedsCreateAndWrite() + { + var method = Analyze.Method(""" + class C { void M(IOrganizationService service) => service.Execute(new UpsertRequest { Target = new Contact() }); } + """); + + Assert.Equal(["contact:Create", "contact:Write"], method.Requirements()); + } + + [Fact] + public void RequestNeedingNoPrivilegeIsNotReported() + { + var manifest = Analyze.Code(""" + class C + { + void M(IOrganizationService service) + { + service.Execute(new WhoAmIRequest()); + service.Execute(new OrganizationRequest("RetrieveVersion")); + } + } + """); + + Assert.Empty(manifest.AllRequirements); + Assert.Empty(manifest.Unreached.SelectMany(m => m.Unresolved)); + } + + [Fact] + public void MembersSetThroughLocalAreRead() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) + { + var request = new OrganizationRequest("Delete"); + request["Target"] = new EntityReference("contact", id); + service.Execute(request); + + var update = new UpdateRequest(); + update.Target = new Account(); + service.Execute(update); + + var retrieve = new OrganizationRequest { RequestName = "Retrieve" }; + retrieve.Parameters.Add("Target", new EntityReference("account", id)); + service.Execute(retrieve); + } + } + """); + + Assert.Equal(["account:Read", "account:Write", "contact:Delete"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void ExecuteMultipleReadsEveryRequest() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, List accounts, Guid id) + { + var batch = new ExecuteMultipleRequest { Requests = new OrganizationRequestCollection() }; + foreach (var account in accounts) batch.Requests.Add(new UpdateRequest { Target = account }); + batch.Requests.Add(new DeleteRequest { Target = new EntityReference("contact", id) }); + service.Execute(batch); + } + } + """); + + Assert.Equal(["account:Write", "contact:Delete"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void RequestsPassThroughBatchingAndHelpers() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => Run(c.OrganizationService, Guid.Empty)); + + static void Run(IOrganizationService service, Guid id) + { + var requests = new List(); + requests.Add(new CreateRequest { Target = new Account() }); + requests.AddRange(Deletes(id)); + foreach (var chunk in requests.Chunk(100)) Send(service, chunk); + } + + static IEnumerable Deletes(Guid id) => [new DeleteRequest { Target = new EntityReference("contact", id) }]; + + static void Send(IOrganizationService service, IEnumerable requests) + { + var transaction = new ExecuteTransactionRequest { Requests = new OrganizationRequestCollection() }; + transaction.Requests.AddRange(requests); + service.Execute(transaction); + } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["account:Create", "contact:Delete"], entry.Requirements()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void EntitiesPassThroughListsAndLoops() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var records = new List { new Account() }; + records.Add(new Entity("lead")); + foreach (var record in records) service.Update(record); + records.ForEach(r => service.Delete(r.LogicalName, r.Id)); + } + } + """); + + Assert.Equal(["account:Write", "account:Delete", "lead:Write", "lead:Delete"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void RequestsBuiltBySelectAreRead() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid[] ids) + { + var requests = new OrganizationRequestCollection(); + requests.AddRange(ids.Select(id => new DeleteRequest { Target = new EntityReference("contact", id) })); + service.Execute(new ExecuteMultipleRequest { Requests = requests }); + } + } + """); + + Assert.Equal(["contact:Delete"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void MultipleRequestsReadTheirTargets() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, List contacts) + { + service.Execute(new CreateMultipleRequest { Targets = new EntityCollection { EntityName = "account" } }); + service.Execute(new UpsertMultipleRequest { Targets = new EntityCollection(contacts.Cast().ToList()) }); + } + } + """); + + Assert.Equal(["account:Create", "contact:Create", "contact:Write"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void RequestParameterResolvesPerCall() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, + c => Send(c.OrganizationService, new UpdateRequest { Target = new Contact() })); + + static void Send(IOrganizationService service, OrganizationRequest request) => service.Execute(request); + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["contact:Write"], entry.Requirements()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void UnboundRequestParameterIsReportedOnce() + { + var manifest = Analyze.Code(""" + public static class Extensions + { + public static void Send(this IOrganizationService service, OrganizationRequest request) => service.Execute(request); + } + """); + + var unresolved = Assert.Single(Assert.Single(manifest.Unreached).Unresolved); + Assert.Equal("request comes from parameter 'request'", unresolved.Reason); + Assert.Empty(unresolved.Privileges); + } + + [Fact] + public void RequestWithoutRuleIsReported() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, string name) + { + service.Execute(new AddMembersTeamRequest()); + service.Execute(new OrganizationRequest(name)); + } + } + """); + + Assert.Equal(["no rule for message 'AddMembersTeam'", "request name is computed at runtime"], method.Unresolved.Select(u => u.Reason).Order(StringComparer.Ordinal)); + } + + [Fact] + public void UnknownTargetIsReportedWithItsPrivileges() + { + var method = Analyze.Method(""" + class C + { + private Entity _target = null!; + + void M(IOrganizationService service) => service.Execute(new AssignRequest { Target = _target.ToEntityReference() }); + } + """); + + var unresolved = Assert.Single(method.Unresolved); + Assert.Equal("entity comes from field '_target'", unresolved.Reason); + Assert.Equal([Privilege.Write, Privilege.Assign], unresolved.Privileges); + } + + [Fact] + public void GrantAccessNeedsTheGrantedRights() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, EntityReference user, Guid id) => service.Execute(new GrantAccessRequest + { + Target = new EntityReference("account", id), + PrincipalAccess = new PrincipalAccess { Principal = user, AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess }, + }); + } + """); + + Assert.Equal(["account:Read", "account:Write", "account:Share"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void ConditionalCheckAppliesWhenItsFlagIsSet() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) => service.Execute(new QualifyLeadRequest + { + LeadId = new EntityReference("lead", id), + CreateContact = true, + CreateAccount = false, + Status = new OptionSetValue(3), + }); + } + """); + + Assert.Equal(["contact:Create", "lead:Write"], method.Requirements()); + } + + [Fact] + public void ConfiguredRuleReplacesAndAddsRules() + { + var manifest = Analyze.Code( + """ + class C + { + void M(IOrganizationService service, Guid id) + { + service.Execute(new OrganizationRequest("ctx_Approve") { ["Target"] = new EntityReference("account", id) }); + service.Execute(new WhoAmIRequest()); + } + } + """, + rules: + [ + new RequestRule("ctx_Approve") { Checks = [new RuleCheck([Privilege.Write]) { Member = "Target" }] }, + new RequestRule("WhoAmIRequest") { Checks = [new RuleCheck([Privilege.Read]) { Table = "systemuser" }] }, + ]); + + Assert.Equal(["account:Write", "systemuser:Read"], Assert.Single(manifest.Unreached).Requirements()); + } + + [Fact] + public void MessageEndingInRequestIsMatchedByItsName() + { + var manifest = Analyze.Code( + """ + class C + { + void M(IOrganizationService service, Guid id) + { + service.Execute(new OrganizationRequest("ctx_ApproveRequest") { ["Target"] = new EntityReference("account", id) }); + service.Execute(new OrganizationRequest("ctx_Close") { ["Target"] = new EntityReference("contact", id) }); + service.Execute(new OrganizationRequest("ctx_Save") { ["Target"] = new Entity("lead") }); + } + } + """, + rules: + [ + new RequestRule("ctx_Approve") { Checks = [new RuleCheck([Privilege.Write]) { Member = "Target" }] }, + new RequestRule("ctx_CloseRequest") { Checks = [new RuleCheck([Privilege.Write]) { Member = "Target" }] }, + new RequestRule("ctx_Save") { As = ["CreateRequest"] }, + ]); + + var method = Assert.Single(manifest.Unreached); + Assert.Equal(["contact:Write", "lead:Create"], method.Requirements()); + Assert.StartsWith("custom API 'ctx_ApproveRequest' is called", Assert.Single(method.Unresolved).Reason); + } + + [Fact] + public void NullRequestNeedsNothing() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id, bool flag) + { + var request = Build(id, flag); + if (request is null) return; + service.Execute(request); + } + + static OrganizationRequest? Build(Guid id, bool flag) => flag ? new DeleteRequest { Target = new EntityReference("contact", id) } : null; + } + """); + + Assert.Equal(["contact:Delete"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void TypeThatIsACollectionOfItselfIsNotARequest() + { + var method = Analyze.Method(""" + class Node : IEnumerable + { + public IEnumerator GetEnumerator() => throw new NotImplementedException(); + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + class C + { + void M(IOrganizationService service) => Save(service, new Node()); + void Save(IOrganizationService service, Node node) => service.Create(new Account()); + } + """); + + Assert.Equal(["account:Create"], method.Requirements()); + } + + [Fact] + public void RulesAreReadFromConfiguration() + { + var rules = RuleSetup.Create(Configuration(""" + [ + { "Message": "ctx_Approve", "Target": "Target", "Privileges": ["Write", "$Access"] }, + { "Message": "ctx_ApproveMultiple", "Targets": "Targets", "As": ["ctx_Approve"] }, + { "Message": "ctx_Close", "Checks": [{ "Table": "Task", "Privileges": ["Create"], "When": "CreateTask" }], "Enforced": false }, + { "Message": "WhoAmIRequest" }, + { "Message": "ctx_Purge", "GlobalPrivileges": [" prvBulkDelete ", "PRVBULKDELETE"], "Assumption": "purges one table" } + ] + """)); + + Assert.Equal( + [ + new RequestRule("ctx_Approve") { Checks = [new RuleCheck([Privilege.Write]) { Member = "Target", AccessMask = "Access" }] }, + new RequestRule("ctx_ApproveMultiple") { As = ["ctx_Approve"], Targets = "Targets" }, + new RequestRule("ctx_Close") { Checks = [new RuleCheck([Privilege.Create]) { Table = "task", When = "CreateTask" }], Enforced = false }, + new RequestRule("WhoAmIRequest"), + new RequestRule("ctx_Purge") { GlobalPrivileges = ["prvBulkDelete"], Assumption = "purges one table" }, + ], + rules, + RuleComparer.Instance); + } + + [Theory] + [InlineData("""[{ "Target": "Target" }]""", "XrmMockup:Permissions:Rules:0 has no Message")] + [InlineData("""[{ "Message": "ctx_A", "Privileges": ["Write"] }]""", "XrmMockup:Permissions:Rules:0 has Privileges but no Target")] + [InlineData("""[{ "Message": "ctx_A", "Target": "Target", "Privileges": ["Update"] }]""", "XrmMockup:Permissions:Rules:0 has an unknown privilege 'Update'")] + [InlineData("""[{ "Message": "ctx_A", "Checks": [{ "Privileges": ["Read"] }] }]""", "XrmMockup:Permissions:Rules:0:Checks:0 needs either a Member or a Table")] + [InlineData("""[{ "Message": "ctx_A", "GlobalPrivileges": [" "] }]""", "XrmMockup:Permissions:Rules:0 has an empty GlobalPrivileges entry")] + public void ConfiguredRuleMistakesNameTheSetting(string rules, string error) + { + var exception = Assert.Throws(() => RuleSetup.Create(Configuration(rules))); + + Assert.StartsWith(error, exception.Message); + } + + private static PermissionsConfiguration Configuration(string rules) + { + var directory = Directory.CreateTempSubdirectory("permissions-rules").FullName; + try + { + File.WriteAllText(Path.Combine(directory, "appsettings.json"), $$"""{ "XrmMockup": { "Permissions": { "Rules": {{rules}} } } }"""); + return ConfigReader.Read(Path.Combine(directory, "appsettings.json")).Permissions; + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + /// + /// Records compare their lists by reference, so rules are compared by content. + /// + private sealed class RuleComparer : IEqualityComparer + { + public static RuleComparer Instance { get; } = new(); + + public bool Equals(RequestRule? x, RequestRule? y) => Describe(x!) == Describe(y!); + + public int GetHashCode(RequestRule obj) => Describe(obj).GetHashCode(); + + private static string Describe(RequestRule rule) => + $"{rule.Message} as [{string.Join(",", rule.As)}] targets {rule.Targets} requests {rule.Requests} enforced {rule.Enforced} " + + $"globals [{string.Join(",", rule.GlobalPrivileges)}] assumption {rule.Assumption} checks " + + string.Join(";", rule.Checks.Select(c => $"{c.Member}/{c.Table}/{c.AccessMask}/{c.When}:{string.Join(",", c.Privileges)}")); + } + + [Fact] + public void CustomApiCallIsReportedApart() + { + var manifest = Analyze.Code(""" + class C + { + void M(IOrganizationService service) + { + service.Execute(new OrganizationRequest("ctx_Recalculate")); + service.Execute(new OrganizationRequest("Recalculate")); + } + } + """, + setup: builder => builder.AddPluginSteps([new PluginStepRegistration("Contoso.Plugins.Recalculate", "Contoso.Plugins", "Recalculate", null, 40, null)])); + + Assert.Equal( + ["custom API 'Recalculate' is called; its code and execute privilege are unknown", "custom API 'ctx_Recalculate' is called; its code and execute privilege are unknown"], + Assert.Single(manifest.Unreached).Unresolved.Select(u => u.Reason).Order(StringComparer.Ordinal)); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExtractionTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExtractionTests.cs new file mode 100644 index 00000000..1e7a4fe2 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ExtractionTests.cs @@ -0,0 +1,305 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class ExtractionTests +{ + [Fact] + public void EarlyBoundCreateNeedsCreate() + { + var method = Analyze.Method(""" + class C { void M(IOrganizationService service) => service.Create(new Account()); } + """); + + Assert.Equal("C.M(IOrganizationService)", method.Id); + Assert.Equal(["account:Create"], method.Requirements()); + Assert.Equal(RequirementBasis.Direct, method.Requirements[0].Basis); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void LateBoundEntityWithConstantNameIsResolved() + { + var method = Analyze.Method(""" + class C + { + const string Table = "Contact"; + void M(IOrganizationService service) + { + service.Update(new Entity(Table)); + service.Delete("account", Guid.Empty); + } + } + """); + + Assert.Equal(["account:Delete", "contact:Write"], method.Requirements()); + } + + [Fact] + public void LocalsAndConditionalsResolveToEveryPossibleTable() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, bool flag) + { + var name = flag ? "account" : "contact"; + Entity entity = new Entity(name); + service.Create(entity); + } + } + """); + + Assert.Equal(["account:Create", "contact:Create"], method.Requirements()); + } + + [Fact] + public void RetrieveNeedsRead() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => + service.Retrieve(Contact.EntityLogicalName, Guid.Empty, new ColumnSet(true)); + } + """); + + Assert.Equal(["contact:Read"], method.Requirements()); + } + + [Fact] + public void QueryExpressionIncludesLinkedTables() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var query = new QueryExpression("account"); + query.AddLink("contact", "primarycontactid", "contactid"); + service.RetrieveMultiple(query); + } + } + """); + + Assert.Equal(["account:Read", "contact:Read"], method.Requirements()); + } + + [Fact] + public void NestedLinksAreReportedAsUnresolved() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var query = new QueryExpression("account"); + query.LinkEntities.Add(new LinkEntity("account", "contact", "primarycontactid", "contactid", JoinOperator.Inner)); + service.RetrieveMultiple(query); + } + } + """); + + Assert.Equal(["account:Read"], method.Requirements()); + Assert.Single(method.Unresolved); + } + + [Fact] + public void FetchXmlIncludesLinkEntities() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, string name) + { + var fetch = $""; + service.RetrieveMultiple(new FetchExpression(fetch)); + } + } + """); + + Assert.Equal(["account:Read", "contact:Read"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void FetchXmlBuiltFromItselfKeepsEachPart() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var links = ""; + links = links + ""; + service.RetrieveMultiple(new FetchExpression("" + links + "")); + } + } + """); + + Assert.Equal(["account:Read", "contact:Read", "lead:Read"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void QueryAssignedByCoalesceIsRead() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var query = default(QueryExpression); + query ??= new QueryExpression("contact"); + service.RetrieveMultiple(query); + } + } + """); + + // The analysis doesn't follow the flow, so the null the local starts as is still reported + Assert.Equal(["contact:Read"], method.Requirements()); + } + + [Fact] + public void AssociateNeedsAppendToOnTargetAndAppendOnRelated() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) => + service.Associate("account", id, new Relationship("contact_customer_accounts"), + new EntityReferenceCollection { new EntityReference("contact", id) }); + } + """); + + Assert.Equal(["account:Read", "account:AppendTo", "contact:Read", "contact:Append"], method.Requirements()); + } + + [Fact] + public void ParameterEntityIsReportedWithReason() + { + var method = Analyze.Method(""" + class C { void M(IOrganizationService service, Entity target) => service.Update(target); } + """); + + var unresolved = Assert.Single(method.Unresolved); + Assert.Equal("Update", unresolved.Operation); + Assert.Equal([Privilege.Write], unresolved.Privileges); + Assert.Equal("entity comes from parameter 'target'", unresolved.Reason); + Assert.Equal(("Code.cs", 18, 74), (unresolved.Source.Location.File, unresolved.Source.Location.Line, unresolved.Source.Location.Column)); + } + + [Fact] + public void IndexerIsDescribedWithItsKey() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, ParameterCollection inputs) => service.Update((Entity)inputs["Target"]); + } + """); + + Assert.Equal("entity comes from inputs[\"Target\"]", Assert.Single(method.Unresolved).Reason); + } + + [Fact] + public void TypeParameterIsDescribed() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) where T : Entity, new() => service.Create(new T()); + } + """); + + Assert.Equal("table depends on type parameter 'T'", Assert.Single(method.Unresolved).Reason); + } + + [Fact] + public void LoopOverRetrieveMultipleResolvesToQueryTable() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var query = new QueryExpression("contact"); + query.AddLink("account", "parentcustomerid", "accountid"); + foreach (var record in service.RetrieveMultiple(query).Entities) + { + service.Delete(record.LogicalName, record.Id); + } + } + } + """); + + Assert.Equal(["account:Read", "contact:Read", "contact:Delete"], method.Requirements()); + } + + [Fact] + public void LambdasAndLocalFunctionsCountTowardsTheirMember() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + Action create = () => service.Create(new Account()); + void Update() => service.Update(new Contact()); + create(); + Update(); + } + } + """); + + Assert.Equal(["account:Create", "contact:Write"], method.Requirements()); + } + + [Fact] + public void ServiceImplementationsAndAsyncMethodsAreRecognized() + { + var method = Analyze.Method(""" + class C + { + async Task M(Microsoft.PowerPlatform.Dataverse.Client.IOrganizationServiceAsync2 service) => + await service.CreateAsync(new Account()); + } + """); + + Assert.Equal(["account:Create"], method.Requirements()); + } + + [Fact] + public void CompilationWithoutSdkIsSkipped() + { + var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("Empty"); + Assert.False(new Core.Analysis.ManifestBuilder(Analyze.Root).Add(compilation)); + } + + [Theory] + [InlineData("public void Run(IOrganizationService service) => service.Create(new Entity(\"account\"));", false)] + [InlineData("public void Run(IOrganizationService service) => service.Create(Missing.Account());", true)] + [InlineData("public void Run(IOrganizationService service) => service.NoSuchMethod();", true)] + [InlineData("public void Run(Missing service) { var x = service; }", true)] + public void AddSaysWhenCodeDoesNotBind(string member, bool unbound) + { + var compilation = Analyze.Compile("namespace Contoso { public class Clean { } }"); + compilation = compilation.AddSyntaxTrees(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText( + $"using Microsoft.Xrm.Sdk; namespace Contoso {{ public class Importer {{ {member} }} }}", + path: Path.Combine(Analyze.Root, "Importer.cs"))); + + var builder = new Core.Analysis.ManifestBuilder(Analyze.Root); + Assert.True(builder.Add(compilation)); + Assert.Equal(unbound, builder.LastAddedHasUnboundCode); + } + + [Fact] + public void TablesWithoutRoleAreListed() + { + var manifest = Analyze.Code(""" + class C { void M(IOrganizationService service) { service.Create(new Account()); service.Create(new Contact()); } } + """, roleGovernedTables: ["Account"]); + + Assert.Equal(["contact"], manifest.NotRoleGoverned); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/FilteredAttributeTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/FilteredAttributeTests.cs new file mode 100644 index 00000000..54735920 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/FilteredAttributeTests.cs @@ -0,0 +1,206 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Update steps filtered on columns, which an update fires only when it sets one of them. +/// +public class FilteredAttributeTests +{ + private const string Step = "plugin:Contoso.OrderPlugin:Update:ctx_order:PostOperation"; + + /// + /// An order Update step filtered on the status, which deletes a lead. + /// + private const string Plugins = """ + namespace Contoso + { + public class OrderPlugin : Plugin + { + public OrderPlugin() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)) + .AddFilteredAttributes(o => o.Status); + } + } + + [EntityLogicalName("ctx_order")] + public class Order : Entity + { + public Order() : base("ctx_order") { } + + [AttributeLogicalName("ctx_name")] + public string? Name { get => GetAttributeValue("ctx_name"); set => this["ctx_name"] = value; } + + [AttributeLogicalName("ctx_status")] + public int? Status { get => GetAttributeValue("ctx_status"); set => this["ctx_status"] = value; } + } + } + """; + + [Fact] + public void UpdateOfOtherColumnsDoesNotFireTheStep() + { + var run = Run(""" + public void Run(IOrganizationService service) + { + var order = new Order { Id = Guid.NewGuid(), Name = "Renamed" }; + order["ctx_description"] = "Changed"; + service.Update(order); + } + """); + + Assert.Empty(run.Triggers); + Assert.Equal(["ctx_order:Write"], run.Requirements()); + } + + [Fact] + public void UpdateOfAFilteredColumnFiresTheStep() + { + var run = Run(""" + public void Run(IOrganizationService service) + { + var order = new Entity("ctx_order", Guid.NewGuid()); + order["ctx_status"] = 2; + service.Update(order); + } + """); + + Assert.Equal([Step], run.Triggers); + Assert.Equal(RequirementBasis.Direct, Assert.Single(run.Requirements, r => r.Table == "lead").Basis); + } + + [Fact] + public void UpdateOfUnknownColumnsFiresTheStepAsFilterUnknown() + { + var run = Run("public void Run(IOrganizationService service, Order order) => service.Update(order);", "Order"); + + Assert.Equal([Step], run.Triggers); + Assert.Equal(RequirementBasis.FilterUnknown, Assert.Single(run.Requirements, r => r.Table == "lead").Basis); + Assert.Equal(RequirementBasis.Direct, Assert.Single(run.Requirements, r => r.Table == "ctx_order").Basis); + } + + [Fact] + public void EntityPassedToAMethodThatCanSetMoreColumnsIsFilterUnknown() + { + var run = Run(""" + public void Run(IOrganizationService service) + { + var order = new Order { Name = "Renamed" }; + Fill(order); + service.Update(order); + } + + private static void Fill(Order order) => order.Status = 2; + """); + + Assert.Equal(RequirementBasis.FilterUnknown, Assert.Single(run.Requirements, r => r.Table == "lead").Basis); + } + + [Fact] + public void ColumnsAreFollowedIntoTheMethodThatUpdates() + { + var run = Run(""" + public void Run(IOrganizationService service) + { + Save(service, new Order { Name = "Renamed" }); + var order = new Order(); + order.Status = 2; + Save(service, order); + } + + private static void Save(IOrganizationService service, Order order) => service.Update(order); + """); + + Assert.Equal([Step], run.Triggers); + var lead = Assert.Single(run.Requirements, r => r.Table == "lead"); + Assert.Equal(RequirementBasis.Direct, lead.Basis); + } + + [Fact] + public void RequestTargetColumnsDecideTheStepsItFires() + { + var update = Run("public void Run(IOrganizationService service) => service.Execute(new UpdateRequest { Target = new Order { Name = \"Renamed\" } });"); + Assert.Empty(update.Triggers); + + var upsert = Run("public void Run(IOrganizationService service) => service.Execute(new UpsertRequest { Target = new Order { Status = 2 } });"); + Assert.Equal([Step], upsert.Triggers); + } + + [Fact] + public void FilterFromTheMetadataApplies() + { + var manifest = Analyze.Code( + """ + namespace Contoso + { + public class Importer + { + public void Rename(IOrganizationService service) => service.Update(new Entity("account") { ["name"] = "Renamed" }); + + public void Close(IOrganizationService service) => service.Update(new Entity("account") { ["statecode"] = 1 }); + } + } + """, + setup: builder => + { + builder.AddPluginSteps([new PluginStepRegistration("Other.AccountPlugin", "Other", "Update", "account", 40, null, ["statecode"])]); + builder.AddEntryMethods(["Contoso.Importer.Rename", "Contoso.Importer.Close"]); + }); + + Assert.Empty(manifest.Entry("method:Contoso.Importer.Rename(IOrganizationService)").Triggers); + Assert.Equal( + ["plugin:Other.AccountPlugin:Update:account:PostOperation"], + manifest.Entry("method:Contoso.Importer.Close(IOrganizationService)").Triggers); + } + + [Fact] + public void FilterCanBeGivenByColumnName() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() => + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)) + .AddFilteredAttributes("Name"); + } + + public class Importer + { + public void Run(IOrganizationService service) => service.Update(new Entity("account") { ["description"] = "Changed" }); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + + var step = manifest.Entry("plugin:Contoso.AccountPlugin:Update:account:PostOperation"); + Assert.Equal(["name"], step.Trigger!.FilteredAttributes); + Assert.Empty(manifest.Entry("method:Contoso.Importer.Run(IOrganizationService)").Triggers); + } + + [Fact] + public void FilterOfAStepRegisteredByMessageNameIgnoresCase() + { + var manifest = Analyze.Code(""" + public class AccountPlugin : Plugin + { + public AccountPlugin() => + RegisterPluginStep("update", ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)) + .AddFilteredAttributes("Name"); + } + """); + + Assert.Equal(["name"], Assert.Single(manifest.EntryPoints).Trigger!.FilteredAttributes); + } + + private static EntryPoint Run(string members, string parameter = "") + { + var manifest = Analyze.Code( + "namespace Contoso { public class Importer { " + members + " } }" + Plugins, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + var suffix = parameter.Length > 0 ? ", " + parameter : ""; + return manifest.Entry($"method:Contoso.Importer.Run(IOrganizationService{suffix})"); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/GlobalPrivilegeTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/GlobalPrivilegeTests.cs new file mode 100644 index 00000000..2ef1186f --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/GlobalPrivilegeTests.cs @@ -0,0 +1,198 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Requests that need a privilege by name, such as prvBulkDelete, rather than a privilege on the tables they act on. +/// +public class GlobalPrivilegeTests +{ + private static IReadOnlyList Globals(MethodManifest method) => + method.GlobalRequirements.Select(r => $"{r.Privilege} as {r.RunsAs.Kind}").ToList(); + + [Fact] + public void RequestNeedsThePrivilegeItsRuleNames() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => + service.Execute(new BulkDeleteRequest { JobName = "Purge", QuerySet = [new QueryExpression("account")] }); + } + """); + + var global = Assert.Single(method.GlobalRequirements); + Assert.Equal(("prvBulkDelete", RunsAsKind.Caller, RequirementBasis.Direct), (global.Privilege, global.RunsAs.Kind, global.Basis)); + Assert.Empty(method.Requirements); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void RequestCanNeedSeveralPrivileges() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => service.Execute(new RetrieveAuditDetailsRequest { AuditId = Guid.Empty }); + } + """); + + Assert.Equal(["prvReadAuditSummary as Caller", "prvReadRecordAuditHistory as Caller"], Globals(method)); + } + + [Fact] + public void RequestByNameNeedsThePrivilegeToo() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => service.Execute(new OrganizationRequest("PublishAllXml")); + } + """); + + Assert.Equal(["prvPublishCustomization as Caller"], Globals(method)); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void MergeNeedsPrvMergeAsWellAsTablePrivileges() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => + service.Execute(new MergeRequest { Target = new EntityReference("account", Guid.Empty), SubordinateId = Guid.Empty }); + } + """); + + Assert.Equal(["prvMerge as Caller"], Globals(method)); + Assert.Equal(["account:Read", "account:Write"], method.Requirements()); + } + + [Fact] + public void PrivilegeIsLookedUpInThePrivilegeCatalog() + { + var manifest = Analyze.Code(""" + class C + { + void M(IOrganizationService service) + { + service.Execute(new BulkDeleteRequest()); + service.Execute(new ExecuteWorkflowRequest { WorkflowId = Guid.Empty, EntityId = Guid.Empty }); + service.Execute(new PublishAllXmlRequest()); + } + } + """, + setup: builder => builder.AddPrivilegeCatalog( + [ + new PrivilegeDefinition("PRVBULKDELETE", null, []), + new PrivilegeDefinition("prvWorkflowExecution", Privilege.Read, ["workflow"]), + new PrivilegeDefinition("prvPublishCustomization", null, ["solution"]), + ], [])); + var method = Assert.Single(manifest.Unreached); + + // The catalog's spelling, a table privilege for one tied to a table, and unresolved where a role can't grant it + Assert.Equal(["PRVBULKDELETE as Caller"], Globals(method)); + Assert.Equal(["workflow:Read"], method.Requirements()); + var unresolved = Assert.Single(method.Unresolved); + Assert.Equal(("PublishAllXml", "the PublishAllXml request needs privilege 'prvPublishCustomization', whose access right isn't a table privilege"), (unresolved.Operation, unresolved.Reason)); + } + + [Fact] + public void PrivilegeMissingFromThePrivilegeCatalogIsUnresolved() + { + var manifest = Analyze.Code(""" + class C + { + void M(IOrganizationService service) => service.Execute(new OrganizationRequest("ctx_Purge")); + } + """, + setup: builder => builder.AddPrivilegeCatalog([new PrivilegeDefinition("prvBulkDelete", null, [])], []), + rules: [new RequestRule("ctx_Purge") { GlobalPrivileges = ["prvBulkDelte"] }]); + var method = Assert.Single(manifest.Unreached); + + Assert.Empty(method.GlobalRequirements); + Assert.Equal("the ctx_Purge request needs privilege 'prvBulkDelte', which isn't in the privilege catalog", Assert.Single(method.Unresolved).Reason); + } + + [Fact] + public void AsRuleAddsItsPrivilegesAndAssumption() + { + var manifest = Analyze.Code(""" + class C + { + void M(IOrganizationService service) => service.Execute(new OrganizationRequest("ctx_PurgeAll")); + } + """, + rules: + [ + new RequestRule("ctx_Purge") { GlobalPrivileges = ["prvBulkDelete"], Assumption = "only closed records are purged" }, + new RequestRule("ctx_PurgeAll") { As = ["ctx_Purge"], GlobalPrivileges = ["prvDeleteRecordChangeHistory"] }, + ]); + var method = Assert.Single(manifest.Unreached); + + Assert.Equal(["prvBulkDelete as Caller", "prvDeleteRecordChangeHistory as Caller"], Globals(method)); + Assert.Contains("only closed records are purged", method.Assumptions.Select(a => a.Reason)); + } + + [Fact] + public void SendEmailAssumesItIsSentAsTheCaller() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => service.Execute(new SendEmailRequest { EmailId = Guid.Empty, IssueSend = true }); + } + """); + + Assert.Contains("SendEmail sends the email as the calling user; sending it as another user needs prvSendAsUser", method.Assumptions.Select(a => a.Reason)); + Assert.Empty(method.GlobalRequirements); + } + + [Fact] + public void SettingOverriddenCreatedOnNeedsPrvOverrideCreatedOnCreatedBy() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + service.Create(new Account { ["overriddencreatedon"] = DateTime.UtcNow.AddYears(-1) }); + service.Execute(new CreateRequest { Target = new Contact { ["overriddencreatedon"] = DateTime.UtcNow } }); + service.Create(new Account { ["name"] = "Contoso" }); + } + } + """); + + var global = Assert.Single(method.GlobalRequirements); + Assert.Equal("prvOverrideCreatedOnCreatedBy", global.Privilege); + // The two that set it, not the third Create + Assert.Equal(2, global.Sources.Count); + } + + [Fact] + public void PrivilegeAStepNeedsIsNeededByTheEntryPointThatFiresIt() + { + var manifest = Analyze.Code(""" + namespace Contoso + { + public class AccountPlugin : Plugin + { + public AccountPlugin() => + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Execute(new BulkDeleteRequest())); + } + + public class Importer + { + public void Run(IOrganizationService service) => service.Create(new Account()); + } + } + """, + setup: builder => builder.AddEntryMethods(["Contoso.Importer.Run"])); + var run = manifest.Entry("method:Contoso.Importer.Run(IOrganizationService)"); + + var global = Assert.Single(run.GlobalRequirements); + Assert.Equal("prvBulkDelete", global.Privilege); + Assert.Contains("plugin:Contoso.AccountPlugin:Create:account:PostOperation", Assert.Single(global.Sources).Path); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/LookupTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/LookupTests.cs new file mode 100644 index 00000000..919759e6 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/LookupTests.cs @@ -0,0 +1,379 @@ +using Microsoft.Xrm.Sdk.Metadata; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Metadata; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Append on a record that gets a lookup set, and AppendTo on the record the lookup refers to, as XrmMockup checks +/// them on Create and Update. +/// +public class LookupTests +{ + /// + /// An early-bound table with a lookup property, as the context generator writes it. + /// + private const string Order = """ + + [EntityLogicalName("ctx_order")] + public class Order : Entity + { + public Order() : base("ctx_order") { } + + [AttributeLogicalName("ctx_customerid")] + public EntityReference? CustomerId { get => GetAttributeValue("ctx_customerid"); set => this["ctx_customerid"] = value; } + + [AttributeLogicalName("ctx_name")] + public string? Name { get => GetAttributeValue("ctx_name"); set => this["ctx_name"] = value; } + } + """; + + private static readonly LookupColumn[] Metadata = + [ + new("ctx_order", "ctx_customerid", ["account", "contact"]), + new("contact", "parentcustomerid", ["account", "contact"]), + new("account", "parentaccountid", ["account"]), + ]; + + [Fact] + public void CreateWithEarlyBoundLookupNeedsAppendAndAppendTo() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) => + service.Create(new Order { Name = "x", CustomerId = new EntityReference(Account.EntityLogicalName, id) }); + } + """ + Order); + + Assert.Equal(["account:AppendTo", "ctx_order:Create", "ctx_order:Append"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void LookupsSetThroughALocalAreFound() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) + { + var account = new Account { Id = id }; + var contact = new Entity("contact", id); + contact["parentcustomerid"] = account.ToEntityReference(); + contact.Attributes.Add("ctx_managerid", new EntityReference(Contact.EntityLogicalName, id)); + service.Update(contact); + } + } + """); + + Assert.Equal(["account:AppendTo", "contact:Write", "contact:Append", "contact:AppendTo"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void OwnerAndOtherColumnsNeedNoAppend() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) => + service.Create(new Entity("account") { ["name"] = "x", ["ownerid"] = new EntityReference("systemuser", id) }); + } + """); + + Assert.Equal(["account:Create"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void RetrievedEntityAddsNoLookups() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) + { + var account = service.Retrieve("account", id, new ColumnSet(true)).ToEntity(); + account["name"] = "x"; + service.Update(account); + } + } + """); + + Assert.Equal(["account:Read", "account:Write"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void DeconstructedEntityAddsOnlyTheLookupsSetOnIt() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) + { + var (account, _) = Pair(); + service.Update(account); + + var (contact, _) = (new Contact(), 1); + contact["parentcustomerid"] = new EntityReference("account", id); + service.Update(contact); + } + + static (Account, int) Pair() => (new Account(), 1); + } + """); + + Assert.Equal(["account:Write", "account:AppendTo", "contact:Write", "contact:Append"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void UnknownLookupValueIsUnresolvedWithoutMetadata() + { + var method = Analyze.Method(""" + class C + { + EntityReference parent = null!; + void M(IOrganizationService service) => service.Create(new Entity("account") { ["parentaccountid"] = parent }); + } + """); + + Assert.Equal(["account:Create", "account:Append"], method.Requirements()); + var unresolved = Assert.Single(method.Unresolved); + Assert.Equal("lookup value: entity comes from field 'parent'", unresolved.Reason); + Assert.Equal([Privilege.AppendTo], unresolved.Privileges); + } + + [Fact] + public void MetadataGivesTheTablesOfUnknownLookupValues() + { + var manifest = Analyze.Code( + """ + class C + { + EntityReference reference = null!; + void M(IOrganizationService service) + { + service.Create(new Entity("account") { ["parentaccountid"] = reference }); + service.Create(new Order { CustomerId = reference }); + } + } + """ + Order, + lookups: Metadata); + var method = Assert.Single(manifest.Unreached); + + Assert.Empty(method.Unresolved); + Assert.Equal( + [ + "account:Create Direct", + "account:Append Direct", + "account:AppendTo Direct", + "contact:AppendTo AllLookupTargets", + "ctx_order:Create Direct", + "ctx_order:Append Direct", + ], + method.Requirements.Select(r => $"{r.Table}:{r.Privilege} {r.Basis}")); + } + + [Fact] + public void EarlyBoundLookupPropertyGivesTheTablesItRefersTo() + { + var manifest = Analyze.Code( + """ + class C + { + void M(IOrganizationService service, Order order, Invoice invoice) + { + service.Delete(order.CustomerId!.LogicalName, order.CustomerId.Id); + service.Update(new Entity { LogicalName = invoice.AccountId!.LogicalName, Id = invoice.AccountId.Id }); + } + } + + [EntityLogicalName("ctx_invoice")] + public class Invoice : Entity + { + public Invoice() : base("ctx_invoice") { } + + [AttributeLogicalName("ctx_accountid")] + public EntityReference? AccountId { get => GetAttributeValue("ctx_accountid"); set => this["ctx_accountid"] = value; } + } + """ + Order, + lookups: [new("ctx_order", "ctx_customerid", ["account", "contact"]), new("ctx_invoice", "ctx_accountid", ["account"])]); + var method = Assert.Single(manifest.Unreached); + + Assert.Empty(method.Unresolved); + Assert.Equal( + ["account:Write Direct", "account:Delete AllLookupTargets", "contact:Delete AllLookupTargets"], + method.Requirements.Select(r => $"{r.Table}:{r.Privilege} {r.Basis}")); + } + + [Fact] + public void KnownTargetOfPolymorphicLookupIsKept() + { + var manifest = Analyze.Code( + """ + class C + { + void M(IOrganizationService service, Guid id) => + service.Create(new Order { CustomerId = new EntityReference("contact", id) }); + } + """ + Order, + lookups: Metadata); + var method = Assert.Single(manifest.Unreached); + + Assert.Equal(["contact:AppendTo", "ctx_order:Create", "ctx_order:Append"], method.Requirements()); + Assert.All(method.Requirements, r => Assert.Equal(RequirementBasis.Direct, r.Basis)); + } + + [Fact] + public void LookupsSetInAHelperAreBoundAtTheCallSite() + { + var entry = Single(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => M(c.OrganizationService, Guid.Empty)); + + void M(IOrganizationService service, Guid id) + { + Save(service, new Contact(), new EntityReference("account", id)); + Save(service, new Order(), null); + } + + void Save(IOrganizationService service, Entity entity, EntityReference? parent) + { + if (parent != null) entity["parentcustomerid"] = parent; + service.Create(entity); + } + } + """ + Order); + + Assert.Equal(["account:AppendTo", "contact:Create", "contact:Append", "ctx_order:Create", "ctx_order:Append"], entry.Requirements()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void EntityWithLookupsPassedToHelperNeedsAppend() + { + var entry = Single(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => + { + Save(c.OrganizationService, new Order { CustomerId = new EntityReference("contact", Guid.Empty) }); + Save(c.OrganizationService, new Account { ["name"] = "x" }); + }); + + static void Save(IOrganizationService service, Entity entity) => service.Create(entity); + } + """ + Order); + + Assert.Equal(["account:Create", "contact:AppendTo", "ctx_order:Create", "ctx_order:Append"], entry.Requirements()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void RequestsThatWriteEntitiesNeedAppendForTheirLookups() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid[] ids) + { + service.Execute(new UpsertRequest { Target = new Order { CustomerId = new EntityReference("account", ids[0]) } }); + + var contacts = new List(); + foreach (var id in ids) + { + var contact = new Entity("contact"); + contact["parentcustomerid"] = new EntityReference("account", id); + contacts.Add(contact); + } + service.Execute(new CreateMultipleRequest { Targets = new EntityCollection(contacts) { EntityName = "contact" } }); + } + } + """ + Order); + + Assert.Equal( + ["account:AppendTo", "contact:Create", "contact:Append", "ctx_order:Create", "ctx_order:Write", "ctx_order:Append"], + method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void LocalPassedToTheCallItIsAssignedFromIsResolvedOnce() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) + { + var entity = new Entity("account"); + entity = Prepare(entity); + service.Create(entity); + } + + static Entity Prepare(Entity entity) => entity; + } + """); + + Assert.Equal(["account:Create"], method.Requirements()); + } + + [Fact] + public void AssignNeedsNoAppend() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, Guid id) => + service.Execute(new AssignRequest { Target = new EntityReference("account", id), Assignee = new EntityReference("systemuser", id) }); + } + """); + + Assert.Equal(["account:Write", "account:Assign"], method.Requirements()); + } + + [Fact] + public void LoaderReadsLookupTargetsFromEntityMetadata() + { + var contact = new EntityMetadata { LogicalName = "contact" }; + var lookup = new LookupAttributeMetadata { LogicalName = "parentcustomerid", Targets = ["contact", "account"] }; + var name = new StringAttributeMetadata { LogicalName = "fullname" }; + typeof(EntityMetadata).GetProperty(nameof(EntityMetadata.Attributes))!.SetValue(contact, new AttributeMetadata[] { name, lookup }); + + Assert.Equal( + [new LookupColumn("contact", "parentcustomerid", ["account", "contact"])], + LookupLoader.Convert([contact]), + new LookupColumnComparer()); + } + + [Fact] + public void LoaderReadsXrmMockupMetadataFiles() + { + var columns = MetadataFileLoader.Load(XrmMockupMetadataDirectory()).Lookups; + + var parent = Assert.Single(columns, c => c.Table == "contact" && c.Column == "parentcustomerid"); + Assert.Equal(["account", "contact"], parent.Targets); + Assert.Empty(MetadataFileLoader.Load(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).Lookups); + } + + private static EntryPoint Single(string source) + { + var manifest = Analyze.Code(source); + Assert.Empty(manifest.Unreached); + return Assert.Single(manifest.EntryPoints); + } + + private static string XrmMockupMetadataDirectory([System.Runtime.CompilerServices.CallerFilePath] string path = "") => + Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path)!, "..", "..", "..", "tests", "XrmMockup365Test", "Metadata")); + + private sealed class LookupColumnComparer : IEqualityComparer + { + public bool Equals(LookupColumn? x, LookupColumn? y) => + x is not null && y is not null && x.Table == y.Table && x.Column == y.Column && x.Targets.SequenceEqual(y.Targets); + + public int GetHashCode(LookupColumn obj) => HashCode.Combine(obj.Table, obj.Column); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/MultiTargetTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/MultiTargetTests.cs new file mode 100644 index 00000000..340015b9 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/MultiTargetTests.cs @@ -0,0 +1,185 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Output; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Facts at the same source location can resolve differently in each target framework. +/// +public class MultiTargetTests +{ + [Theory] + [InlineData("Remove(s, Names.Table)", "static void Remove(IOrganizationService s, string table) => s.Delete(table, Guid.Empty);")] + [InlineData("s.Delete(Table(), Guid.Empty)", "static string Table() => Names.Table;")] + [InlineData("s.Delete(Table(), Guid.Empty)", "static string Table() => Echo(Names.Table); static string Echo(string table) => table;")] + [InlineData("s.Delete(Echo(Names.Table), Guid.Empty)", "static string Echo(string table) => table;")] + public void TablesPassedThroughHelpersAreKept(string call, string helper) + { + var source = """ + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => Cleanup.Run(c.OrganizationService)); + } + static class Cleanup + { + public static void Run(IOrganizationService s) { CALL; } + HELPERS + } + """.Replace("CALL", call).Replace("HELPERS", helper); + var first = source + """static class Names { public const string Table = "account"; }"""; + var second = source + """static class Names { public const string Table = "contact"; }"""; + + var entry = Build(first, second).Build().Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["account:Delete as Caller", "contact:Delete as Caller"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + AssertStable(first, second); + } + + [Theory] + [InlineData("Repository.Remove(c.OrganizationService)", "static class Repository { public static void Remove(IOrganizationService service) where T : Entity, new() => service.Delete(new T().LogicalName, Guid.Empty); }")] + [InlineData("new Repository(c.OrganizationService).Remove()", "class Repository(IOrganizationService service) where T : Entity, new() { public void Remove() => service.Delete(new T().LogicalName, Guid.Empty); }")] + public void GenericMethodAndReceiverTypeArgumentsAreKept(string call, string helper) + { + var source = """ + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => CALL); + } + [EntityLogicalName(Names.Table)] + public class Record : Entity { public Record() : base(Names.Table) { } } + HELPERS + """.Replace("CALL", call).Replace("HELPERS", helper); + var first = source + """static class Names { public const string Table = "account"; }"""; + var second = source + """static class Names { public const string Table = "contact"; }"""; + + var entry = Build(first, second).Build().Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["account:Delete as Caller", "contact:Delete as Caller"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + AssertStable(first, second); + } + + [Theory] + [InlineData("return Origins.Service(context);", "Helpers.Service(c).Delete(\"lead\", Guid.Empty)")] + [InlineData("return Echo(Origins.Service(context));", "Helpers.Service(c).Delete(\"lead\", Guid.Empty)")] + public void ServiceIdentitiesPassedThroughHelpersAreKept(string body, string call) + { + var source = """ + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => CALL); + } + static class Helpers + { + public static IOrganizationService Service(LocalPluginContext context) { BODY } + static IOrganizationService Echo(IOrganizationService service) => service; + } + """.Replace("CALL", call).Replace("BODY", body); + // The helper's body changes behind a shared call site, as under #if for each target framework. + var first = source + """static class Origins { public static IOrganizationService Service(LocalPluginContext c) => c.OrganizationService; }"""; + var second = source + """static class Origins { public static IOrganizationService Service(LocalPluginContext c) => c.OrganizationAdminService; }"""; + + var entry = Build(first, second).Build().Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["lead:Delete as Caller", "lead:Delete as System"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + AssertStable(first, second); + } + + [Theory] + [InlineData("Helpers.Remove(c.VALUE)", "static class Helpers { public static void Remove(IOrganizationService s) => s.Delete(\"lead\", Guid.Empty); }")] + [InlineData("new Cleanup(c.VALUE).Run()", "class Cleanup(IOrganizationService service) { public void Run() => service.Delete(\"lead\", Guid.Empty); }")] + public void ServiceArgumentsAndReceiverCreationAreKept(string call, string helper) + { + var source = """ + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => CALL); + } + HELPERS + """.Replace("CALL", call).Replace("HELPERS", helper); + var first = source.Replace("VALUE", "OrganizationService"); + var second = source.Replace("VALUE", "OrganizationAdminService"); + + var entry = Build(first, second).Build().Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["lead:Delete as Caller", "lead:Delete as System"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + AssertStable(first, second); + } + + [Fact] + public void ConstructorFieldWritesFromBothFrameworksAreKept() + { + var source = """ + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => new Cleanup(c).Run()); + } + class Cleanup + { + private readonly IOrganizationService service; + public Cleanup(LocalPluginContext context) { service = VALUE; } + public void Run() => service.Delete("lead", Guid.Empty); + } + """; + var first = source.Replace("VALUE", "context.OrganizationService"); + var second = source.Replace("VALUE", "context.OrganizationAdminService"); + + var entry = Build(first, second).Build().Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["lead:Delete as Caller", "lead:Delete as System"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + AssertStable(first, second); + } + + [Fact] + public void HelperArgumentsRetainThePluginCascadesOfBothTables() + { + var source = """ + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => Cleanup.Run(c.OrganizationService, Names.Table)); + RegisterPluginStep(EventOperation.Delete, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Entity("task"))); + RegisterPluginStep(EventOperation.Delete, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Entity("lead"))); + } + } + static class Cleanup + { + public static void Run(IOrganizationService service, string table) => service.Delete(table, Guid.Empty); + } + """; + var first = source + """static class Names { public const string Table = "account"; }"""; + var second = source + """static class Names { public const string Table = "contact"; }"""; + + var entry = Build(first, second).Build().Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["account:Delete", "contact:Delete", "lead:Create", "task:Create"], entry.Requirements()); + Assert.Equal(["plugin:P:Delete:account:PostOperation", "plugin:P:Delete:contact:PostOperation"], entry.Triggers); + AssertStable(first, second); + } + + private static ManifestBuilder Build(params string[] sources) + { + var builder = new ManifestBuilder(Analyze.Root); + foreach (var source in sources) Assert.True(builder.Add(Analyze.Compile(source))); + return builder; + } + + private static void AssertStable(string first, string second) + { + var forward = Build(first, second).Build(); + var backward = Build(second, first).Build(); + var repeated = Build(first, second, first, second).Build(); + foreach (var writer in new IManifestWriter[] { new TextManifestWriter(), new JsonManifestWriter(), new MarkdownManifestWriter(), new SarifManifestWriter() }) + { + Assert.Equal(Write(writer, forward), Write(writer, backward)); + Assert.Equal(Write(writer, forward), Write(writer, repeated)); + } + } + + private static string Write(IManifestWriter writer, Manifest manifest) + { + using var output = new StringWriter(); + writer.Write(manifest, null, output); + return output.ToString(); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/OperationTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/OperationTests.cs new file mode 100644 index 00000000..6a622937 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/OperationTests.cs @@ -0,0 +1,192 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// User operations given with --operation: the privileges the request needs as the caller, and the plugin +/// steps it fires. +/// +public class OperationTests +{ + private const string UpdateStep = "plugin:Contoso.OrderPlugin:Update:ctx_order:PostOperation"; + private const string CreateStep = "plugin:Contoso.OrderPlugin:Create:ctx_order:PostOperation"; + + /// + /// An order Update step filtered on the status, which deletes a lead, and a Create step, which creates a task. + /// + private const string Plugins = """ + namespace Contoso + { + public class OrderPlugin : Plugin + { + public OrderPlugin() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)) + .AddFilteredAttributes(o => o.Status); + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Create(new Entity("task"))); + } + } + + [EntityLogicalName("ctx_order")] + public class Order : Entity + { + public Order() : base("ctx_order") { } + + [AttributeLogicalName("ctx_status")] + public int? Status { get => GetAttributeValue("ctx_status"); set => this["ctx_status"] = value; } + } + } + """; + + [Fact] + public void UpdateOfAFilteredColumnFiresTheStep() + { + var operation = Run("Update", "ctx_order", ["CTX_Status"]); + + Assert.Equal("operation:Update ctx_order(ctx_status)", operation.Id); + Assert.Equal(EntryPointKind.Operation, operation.Kind); + Assert.Equal([UpdateStep], operation.Triggers); + Assert.Equal(["ctx_order:Write", "lead:Delete"], operation.Requirements()); + Assert.All(operation.Requirements, r => Assert.Equal(RunsAs.Caller, r.RunsAs)); + Assert.All(operation.Requirements, r => Assert.Equal(RequirementBasis.Direct, r.Basis)); + } + + [Fact] + public void UpdateOfOtherColumnsDoesNotFireTheStep() + { + var operation = Run("Update", "ctx_order", ["ctx_name"]); + + Assert.Empty(operation.Triggers!); + Assert.Equal(["ctx_order:Write"], operation.Requirements()); + } + + [Fact] + public void UpdateWithoutAttributesFiresFilteredStepsAsFilterUnknown() + { + var operation = Run("Update", "ctx_order"); + + Assert.Equal("operation:Update ctx_order", operation.Id); + Assert.Equal([UpdateStep], operation.Triggers); + Assert.Equal(RequirementBasis.FilterUnknown, Assert.Single(operation.Requirements, r => r.Table == "lead").Basis); + } + + [Fact] + public void UpsertFiresCreateAndUpdateSteps() + { + var operation = Run("UpsertRequest", "ctx_order", ["ctx_status"]); + + Assert.Equal([CreateStep, UpdateStep], operation.Triggers); + Assert.Equal(["ctx_order:Create", "ctx_order:Write", "lead:Delete", "task:Create"], operation.Requirements()); + } + + [Fact] + public void LookupColumnsNeedAppendAndAppendTo() + { + var operation = Run( + "Create", + "ctx_order", + ["ctx_customerid", "ctx_ownerteamid"], + [new LookupColumn("ctx_order", "ctx_customerid", ["account", "contact"]), new LookupColumn("ctx_order", "ctx_ownerteamid", ["team"])]); + + Assert.Equal( + ["account:AppendTo", "contact:AppendTo", "ctx_order:Create", "ctx_order:Append", "task:Create", "team:AppendTo"], + operation.Requirements()); + Assert.Equal(RequirementBasis.AllLookupTargets, Assert.Single(operation.Requirements, r => r.Table == "account").Basis); + Assert.Equal(RequirementBasis.Direct, Assert.Single(operation.Requirements, r => r.Table == "team").Basis); + } + + [Fact] + public void RequestMembersOtherThanTheTableAreUnresolved() + { + var operation = Run("Associate", "ctx_order"); + + Assert.Equal(["ctx_order:Read", "ctx_order:AppendTo"], operation.Requirements()); + var unresolved = Assert.Single(operation.Unresolved); + Assert.Equal("RelatedEntities of the Associate request isn't known", unresolved.Reason); + Assert.Equal([Privilege.Read, Privilege.Append], unresolved.Privileges); + Assert.Equal("--operation", unresolved.Source.Location.ToString()); + } + + [Fact] + public void ChecksThatDependOnTheUsersChoicesApply() + { + var operation = Run("QualifyLead", "lead"); + + Assert.Equal(["account:Create", "contact:Create", "lead:Write", "opportunity:Create"], operation.Requirements()); + } + + [Fact] + public void ClosingARecordIsAnOperationOnTheRecord() + { + var operation = Run("CloseIncident", "incident"); + + // Not Create on the incident: the request creates the resolution, which is another member + Assert.Equal(["incident:Write"], operation.Requirements()); + var unresolved = Assert.Single(operation.Unresolved); + Assert.Equal("IncidentResolution of the CloseIncident request isn't known", unresolved.Reason); + Assert.Equal([Privilege.Create], unresolved.Privileges); + } + + [Fact] + public void AccessRightsTheUserGrantsAreUnresolved() + { + var operation = Run("GrantAccess", "ctx_order"); + + Assert.Equal(["ctx_order:Share"], operation.Requirements()); + Assert.Equal("the rights granted in PrincipalAccess.AccessMask aren't known", Assert.Single(operation.Unresolved).Reason); + } + + [Fact] + public void MessageWithoutARuleIsUnresolved() + { + var operation = Run("ctx_Recalculate", "ctx_order"); + + Assert.Empty(operation.Requirements); + Assert.Equal("custom API 'ctx_Recalculate' is called; its code and execute privilege are unknown", Assert.Single(operation.Unresolved).Reason); + } + + [Fact] + public void StepsFiredByTheOperationHaveItsPath() + { + var operation = Run("Update", "ctx_order", ["ctx_status"]); + + var lead = Assert.Single(Assert.Single(operation.Requirements, r => r.Table == "lead").Sources); + Assert.Equal(["Update ctx_order", UpdateStep], lead.Path.Take(2)); + } + + [Fact] + public void OperationNeedsTheGlobalPrivilegesAndAssumptionsOfItsRule() + { + var merge = Run("Merge", "account"); + Assert.Equal(["prvMerge"], merge.GlobalRequirements.Select(r => r.Privilege)); + + var send = Run("SendEmail", "email"); + Assert.Contains(send.Assumptions, a => a.Reason.StartsWith("SendEmail sends the email as the calling user", StringComparison.Ordinal)); + } + + [Fact] + public void OperationScopeSelectsOnlyItsOperation() + { + var manifest = Analyze.Code( + Plugins, + scope: EntryPointSelector.Operation("UpdateRequest", "Account"), + setup: builder => + { + builder.AddOperation("Update", "account"); + builder.AddOperation("Create", "account"); + builder.AddOperation("Update", "contact"); + }); + Assert.Equal("operation:Update account", Assert.Single(manifest.EntryPoints).Id); + } + + private static EntryPoint Run(string message, string table, IReadOnlyList? columns = null, IEnumerable? lookups = null) + { + var manifest = Analyze.Code( + Plugins, + scope: EntryPointSelector.Operation(message, table), + setup: builder => builder.AddOperation(message, table, columns), + lookups: lookups); + return Assert.Single(manifest.EntryPoints); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/OutputFormatTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/OutputFormatTests.cs new file mode 100644 index 00000000..4507eadc --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/OutputFormatTests.cs @@ -0,0 +1,211 @@ +using System.CommandLine; +using System.Text.Json; +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Commands; +using XrmMockup.PermissionAnalyzer.Tool.Output; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// The Markdown report for pull requests and the SARIF findings for code scanning. +/// +public class OutputFormatTests +{ + private static readonly RoleDefinition Salesperson = new("Salesperson", new Dictionary> + { + ["account"] = new Dictionary { [Privilege.Read] = PrivilegeDepth.User }, + }); + + /// + /// An account Update step that reads an account (granted), creates a contact (missing) and deletes one as SYSTEM, + /// and methods nothing calls that delete an account (missing) and a record of an unknown table. + /// + private const string Source = """ + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + } + + private void Execute(LocalPluginContext context) + { + context.OrganizationService.Retrieve("account", Guid.Empty, new ColumnSet()); + context.OrganizationService.Create(new Contact()); + context.OrganizationAdminService.Delete("contact", Guid.Empty); + } + } + + public class Purger + { + public void Purge(IOrganizationService service) => service.Delete("account", Guid.Empty); + + public void Remove(IOrganizationService service, string table) => service.Delete(table, Guid.Empty); + } + """; + + private const string UpdateStep = "plugin:P:Update:account:PostOperation"; + + private static string Write(IManifestWriter writer, RoleDefinition? role = null, IReadOnlyList? suppress = null, string file = "Code.cs", string source = Source) + { + var builder = new ManifestBuilder(Analyze.Root); + Assert.True(builder.Add(Analyze.Compile(source, file: file))); + var manifest = builder.Build(["account", "contact"]); + var coverage = role is null ? null : CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([role], "--role"), Suppress = suppress ?? [] }); + using var output = new StringWriter(); + writer.Write(manifest, coverage, output); + return output.ToString(); + } + + private static JsonElement Results(string sarif) => JsonDocument.Parse(sarif).RootElement.GetProperty("runs")[0].GetProperty("results"); + + private static string Uri(JsonElement location) => location.GetProperty("physicalLocation").GetProperty("artifactLocation").GetProperty("uri").GetString()!; + + [Fact] + public void MarkdownHasATablePerRoleSetWithEntryPointsAndUnresolvedFolded() + { + var markdown = Write(new MarkdownManifestWriter(), Salesperson); + + Assert.StartsWith("### ✘ 2 missing privileges\n\nResult: 1 granted, 2 missing, 1 as SYSTEM\n\n> [!WARNING]\n> Not checked: 1 unresolved operation", markdown); + Assert.Contains("#### Missing from Salesperson (--role), for Caller\n\n| Table | Privileges |\n| --- | --- |\n| `account` | Delete |\n| `contact` | Create |\n\n", markdown); + Assert.Contains($"
By entry point\n\n- `{UpdateStep}`\n\n| Table | Privileges |\n| --- | --- |\n| `contact` | Create |\n\n- `Purger.Purge(IOrganizationService)`\n", markdown); + Assert.Contains("
1 unresolved operation\n\n| Operation | Runs as | Reason | Source |\n| --- | --- | --- | --- |\n| `Delete` [Delete] | Caller", markdown); + Assert.EndsWith("1 unresolved\n", markdown); + } + + [Fact] + public void MarkdownWithoutRolesListsWhatEachIdentityNeeds() + { + var markdown = Write(new MarkdownManifestWriter()); + + Assert.StartsWith("### Required privileges\n\n#### Caller needs\n\n", markdown); + Assert.DoesNotContain("Result:", markdown); + Assert.DoesNotContain("System needs", markdown); + } + + [Fact] + public void MarkdownEscapesNamesAndIsNarrowedByTheFilter() + { + var role = new RoleDefinition("Sales | *Ops*", Salesperson.Privileges); + var markdown = Write(new MarkdownManifestWriter(new ReportFilter(["contact"], [], [], [])), role); + + Assert.Contains(@"#### Missing from Sales \| \*Ops\* (--role), for Caller", markdown); + Assert.DoesNotContain("| `account` |", markdown); + // The counts are of the whole analysis + Assert.StartsWith("### ✘ 2 missing privileges", markdown); + Assert.EndsWith("Filtered by --table contact: 2 of 4 requirements match\n", markdown); + } + + [Fact] + public void MarkdownHeadingCountsEachMissingPrivilegeOnce() + { + var markdown = Write(new MarkdownManifestWriter(), Salesperson, source: """ + public class Importer + { + public void First(IOrganizationService service) => service.Create(new Contact()); + + public void Second(IOrganizationService service) => service.Create(new Contact()); + } + """); + + Assert.StartsWith("### ✘ 1 missing privilege\n\nResult: 0 granted, 2 missing", markdown); + } + + [Theory] + [InlineData("a|b", @"`a\|b`")] + [InlineData("a`b", "`` a`b ``")] + [InlineData("``a`", "``` ``a` ```")] + [InlineData("a\n| x |\r\nb", @"`a \| x \| b`")] + public void MarkdownCodeSpansStayOnOneLineAndInTheirCell(string text, string expected) + { + Assert.Equal(expected, MarkdownManifestWriter.Code(text)); + } + + [Fact] + public void MarkdownTextHasNoLineBreaks() + { + Assert.Equal(@"Sales \# Ops", MarkdownManifestWriter.Text("Sales\n# Ops")); + } + + [Fact] + public void SarifHasAResultPerCallSiteWithItsEntryPoints() + { + var results = Results(Write(new SarifManifestWriter(), Salesperson)); + + Assert.Equal( + ["missing-privilege Create on contact", "missing-privilege Delete on account", "unresolved-operation Delete [Delete]"], + results.EnumerateArray().Select(r => $"{r.GetProperty("ruleId").GetString()} {r.GetProperty("message").GetProperty("text").GetString()!.Split(" is ")[0].Split(" as ")[0]}")); + // Sorted by location + var create = results[0]; + Assert.Equal("error", create.GetProperty("level").GetString()); + Assert.Equal($"Create on contact is missing from Salesperson (--role), needed as Caller, in {UpdateStep}", create.GetProperty("message").GetProperty("text").GetString()); + var location = create.GetProperty("locations")[0]; + Assert.Equal("Code.cs", Uri(location)); + Assert.Equal("%SRCROOT%", location.GetProperty("physicalLocation").GetProperty("artifactLocation").GetProperty("uriBaseId").GetString()); + var related = Assert.Single(create.GetProperty("relatedLocations").EnumerateArray()); + Assert.Equal(UpdateStep, related.GetProperty("message").GetProperty("text").GetString()); + Assert.Equal("contact", create.GetProperty("properties").GetProperty("table").GetString()); + Assert.Equal("warning", results[2].GetProperty("level").GetString()); + } + + [Fact] + public void SarifSuppressesSuppressedPrivilegesWithTheirReason() + { + var results = Results(Write(new SarifManifestWriter(), Salesperson, [new Suppression("contact", Privilege.Create, "Created by a flow")])); + + var suppression = Assert.Single(results.EnumerateArray(), r => r.TryGetProperty("suppressions", out _)).GetProperty("suppressions")[0]; + Assert.Equal("external", suppression.GetProperty("kind").GetString()); + Assert.Equal("Created by a flow", suppression.GetProperty("justification").GetString()); + } + + [Fact] + public void SarifWithoutRolesHasOnlyUnresolvedOperations() + { + var result = Assert.Single(Results(Write(new SarifManifestWriter())).EnumerateArray()); + Assert.Equal("unresolved-operation", result.GetProperty("ruleId").GetString()); + } + + [Fact] + public void SarifLocationsAreRelativeToTheRepository() + { + // The code is next to the analysis root, which is src/Functions in the repository + var results = Results(Write(new SarifManifestWriter(sourceRoot: "src/Functions/"), Salesperson, file: "../Plugins/Code.cs")); + + Assert.Equal("src/Plugins/Code.cs", Uri(results[0].GetProperty("locations")[0])); + Assert.DoesNotContain(results.EnumerateArray(), r => Uri(r.GetProperty("locations")[0]).Contains("..")); + } + + [Fact] + public void RepositoryPathIsTheRootBelowTheNearestGitFolder() + { + var repository = Directory.CreateTempSubdirectory(); + try + { + Directory.CreateDirectory(Path.Combine(repository.FullName, ".git")); + var root = Directory.CreateDirectory(Path.Combine(repository.FullName, "src", "Functions")); + + Assert.Equal("src/Functions/", SarifManifestWriter.RepositoryPath(root.FullName)); + Assert.Equal("", SarifManifestWriter.RepositoryPath(repository.FullName)); + } + finally + { + repository.Delete(recursive: true); + } + } + + [Theory] + [InlineData("markdown")] + [InlineData("sarif")] + public void FormatAcceptsMarkdownAndSarif(string format) + { + var command = new RootCommand(); + var options = new AnalysisOptions(); + options.AddTo(command); + var result = command.Parse(["--format", format]); + + Assert.Empty(result.Errors); + Assert.Equal(format, options.Read(result).Format.ToString().ToLowerInvariant()); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PermissionAnalyzer.Tests.csproj b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PermissionAnalyzer.Tests.csproj new file mode 100644 index 00000000..c74ef2ff --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PermissionAnalyzer.Tests.csproj @@ -0,0 +1,23 @@ + + + false + true + XrmMockup.PermissionAnalyzer.Tests + XrmMockup.PermissionAnalyzer.Tests + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PluginCodeTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PluginCodeTests.cs new file mode 100644 index 00000000..2b20525c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PluginCodeTests.cs @@ -0,0 +1,116 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Plugin code from another solution, added for cascades only, such as the plugins an Azure Function app fires. +/// +public class PluginCodeTests +{ + private const string Step = "plugin:Plugins.OrderPlugin:Create:ctx_order:PostOperation"; + + private const string Function = """ + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("ProcessOrder")] + public void Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + client.Create(new Entity("ctx_order")); + } + } + """; + + /// + /// An order Create step, which deletes a lead, and a helper no step calls. + /// + private const string Plugins = """ + namespace Plugins + { + public class OrderPlugin : Plugin + { + public OrderPlugin() => + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)); + } + + [EntityLogicalName("ctx_order")] + public class Order : Entity + { + public Order() : base("ctx_order") { } + } + + public class Unused + { + public void Run(IOrganizationService service) => service.Delete("task", Guid.Empty); + } + + public class AccountPlugin : IPlugin + { + public void Execute(IServiceProvider serviceProvider) { } + } + } + """; + + [Fact] + public void StepsInPluginCodeRunWhenFiredButAreNotReported() + { + var manifest = Build(); + + var function = Assert.Single(manifest.EntryPoints); + Assert.Equal("function:Functions/ProcessOrder", function.Id); + Assert.Equal([Step], function.Triggers); + Assert.Equal(["ctx_order:Create", "lead:Delete"], function.Requirements()); + Assert.Empty(manifest.Unreached); + } + + [Fact] + public void PluginCodePathsAreRelativeToTheAnalyzedSolution() + { + var lead = Assert.Single(Build().Entry("function:Functions/ProcessOrder").Requirements, r => r.Table == "lead"); + + Assert.Equal("../plugins/Code.cs", Assert.Single(lead.Sources).Location.File); + } + + [Fact] + public void ScopeSelectsEntryPointsInPluginCode() + { + var manifest = Build(EntryPointSelector.Plugin("OrderPlugin")); + + Assert.Equal(["lead:Delete"], Assert.Single(manifest.EntryPoints).Requirements()); + } + + [Fact] + public void MetadataStepsOfPluginCodeAreNotReported() + { + var manifest = Build(setup: builder => builder.AddPluginSteps([new PluginStepRegistration("Plugins.AccountPlugin", "Plugins", "Update", "account", 40, null)])); + + Assert.Equal(["function:Functions/ProcessOrder"], manifest.EntryPoints.Select(e => e.Id)); + Assert.Equal( + ["plugin:Plugins.AccountPlugin:Update:account:PostOperation"], + Build(EntryPointSelector.Plugin("AccountPlugin"), builder => builder.AddPluginSteps([new PluginStepRegistration("Plugins.AccountPlugin", "Plugins", "Update", "account", 40, null)])) + .EntryPoints.Select(e => e.Id)); + } + + [Fact] + public void CodeInTheAnalyzedSolutionIsReportedEvenWhenAlsoAddedAsPluginCode() + { + var builder = new ManifestBuilder(Analyze.Root); + builder.AddPluginCode(Analyze.Compile(Plugins, "Plugins")); + builder.Add(Analyze.Compile(Plugins, "Plugins")); + + var manifest = builder.Build(); + + Assert.Contains(manifest.EntryPoints, e => e.Id == Step); + Assert.Equal("Plugins.Unused.Run(IOrganizationService)", Assert.Single(manifest.Unreached).Id); + } + + private static Manifest Build(EntryPointSelector? scope = null, Action? setup = null) + { + var builder = new ManifestBuilder(Analyze.Root); + setup?.Invoke(builder); + Assert.True(builder.Add(Analyze.Compile(Function, "Functions"))); + Assert.True(builder.AddPluginCode(Analyze.Compile(Plugins, "Plugins", "../plugins/Code.cs"))); + return builder.Build(scope: scope); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PluginStepLoaderTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PluginStepLoaderTests.cs new file mode 100644 index 00000000..75cab4e6 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/PluginStepLoaderTests.cs @@ -0,0 +1,118 @@ +using System.Runtime.Serialization; +using XrmMockup.PermissionAnalyzer.Workspace.Serialization; +using Microsoft.Xrm.Sdk.Metadata; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Metadata; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class PluginStepLoaderTests +{ + [Fact] + public void ReadsPluginStepsFromMetadataFile() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(directory); + try + { + var userId = Guid.NewGuid(); + var skeleton = new MetadataSkeleton + { + Plugins = + [ + new MetaPlugin { AssemblyName = "Contoso.B", PluginTypeAssemblyName = "Contoso", MessageName = "Update", PrimaryEntity = "account", Stage = 40, ImpersonatingUserId = userId }, + new MetaPlugin { AssemblyName = "Contoso.A", MessageName = "Create", PrimaryEntity = "none", Stage = 20, Mode = 1 }, + ], + }; + using (var stream = File.Create(Path.Combine(directory, MetadataFileLoader.MetadataFile))) + { + new DataContractSerializer(typeof(MetadataSkeleton)).WriteObject(stream, skeleton); + } + + var steps = MetadataFileLoader.Load(directory).PluginSteps; + + Assert.Equal( + [ + new PluginStepRegistration("Contoso.A", null, "Create", null, 20, null, Asynchronous: true), + new PluginStepRegistration("Contoso.B", "Contoso", "Update", "account", 40, userId.ToString()), + ], + steps); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void ReadsLookupsAndStepsInOnePassAndStepsOnlyFromTheMainFile() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(directory); + try + { + Write(Path.Combine(directory, MetadataFileLoader.MetadataFile), Skeleton("contact", "parentcustomerid", "Contoso.Main")); + Write(Path.Combine(directory, "Extra" + MetadataFileLoader.MetadataFile), Skeleton("ctx_order", "ctx_customerid", "Contoso.Extra")); + + var contents = MetadataFileLoader.Load(directory); + + Assert.Equal(["contact.parentcustomerid", "ctx_order.ctx_customerid"], contents.Lookups.Select(c => $"{c.Table}.{c.Column}")); + Assert.Equal(["Contoso.Main"], contents.PluginSteps.Select(s => s.TypeName)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void AnEntityInTheMainFileWinsOverTheSameEntityInAnExtraFile() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(directory); + try + { + // "Extra" sorts before "Metadata", but XrmMockup reads the main file first and ignores an entity it has + Write(Path.Combine(directory, MetadataFileLoader.MetadataFile), Skeleton("contact", "parentcustomerid", "Contoso.Main", "account")); + Write(Path.Combine(directory, "Extra" + MetadataFileLoader.MetadataFile), Skeleton("contact", "ctx_ownerid", "Contoso.Extra", "systemuser")); + + var contents = MetadataFileLoader.Load(directory); + + Assert.Equal(["contact.parentcustomerid -> account"], contents.Lookups.Select(c => $"{c.Table}.{c.Column} -> {string.Join(",", c.Targets)}")); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + private static MetadataSkeleton Skeleton(string table, string lookup, string plugin, string target = "account") + { + var entity = new EntityMetadata { LogicalName = table }; + typeof(EntityMetadata).GetProperty(nameof(EntityMetadata.Attributes))!.SetValue(entity, new AttributeMetadata[] + { + new LookupAttributeMetadata { LogicalName = lookup, Targets = [target] }, + }); + return new MetadataSkeleton + { + EntityMetadata = new() { [table] = entity }, + Plugins = [new MetaPlugin { AssemblyName = plugin, MessageName = "Create", PrimaryEntity = table, Stage = 20 }], + }; + } + + private static void Write(string file, MetadataSkeleton skeleton) + { + using var stream = File.Create(file); + new DataContractSerializer(typeof(MetadataSkeleton)).WriteObject(stream, skeleton); + } + + [Fact] + public void MetadataWithoutStepsGivesNone() + { + Assert.Empty(MetadataFileLoader.Load(RoleLoaderTestsDirectory()).PluginSteps); + Assert.Empty(MetadataFileLoader.Load(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).PluginSteps); + } + + private static string RoleLoaderTestsDirectory([System.Runtime.CompilerServices.CallerFilePath] string path = "") => + Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path)!, "..", "..", "..", "tests", "XrmMockup365Test", "Metadata")); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ProjectFilterTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ProjectFilterTests.cs new file mode 100644 index 00000000..2c6ee70c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ProjectFilterTests.cs @@ -0,0 +1,95 @@ +using XrmMockup.PermissionAnalyzer.Tool; +using XrmMockup.PermissionAnalyzer.Tool.Options; +using XrmMockup.PermissionAnalyzer.Tool.Workspace; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class ProjectFilterTests +{ + private static readonly string Root = Path.Combine(Path.GetTempPath(), "repo"); + + private static string ProjectPath(string relative) => Path.Combine(Root, relative.Replace('/', Path.DirectorySeparatorChar)); + + [Theory] + [InlineData("*.Tests", "src/Contoso.Plugins.Tests/Contoso.Plugins.Tests.csproj", true)] + [InlineData("*.tests", "src/Contoso.Plugins.Tests/Contoso.Plugins.Tests.csproj", true)] + [InlineData("*.Tests", "src/Contoso.Plugins/Contoso.Plugins.csproj", false)] + [InlineData("Contoso.?lugins", "src/Contoso.Plugins/Contoso.Plugins.csproj", true)] + [InlineData("Contoso", "src/Contoso.Plugins/Contoso.Plugins.csproj", false)] + [InlineData("tests/*", "tests/Unit/Unit.csproj", true)] + [InlineData("tests/*", "src/Tests/Tests.csproj", false)] + [InlineData(@"tests\*", "tests/Unit/Unit.csproj", true)] + public void MatchesNamesOrRelativePaths(string pattern, string project, bool excluded) + { + var filter = new ProjectFilter(Root, [pattern]); + Assert.Equal(excluded ? pattern.Replace('\\', '/') : null, filter.Excludes(ProjectPath(project))); + } + + [Fact] + public void PathPatternsMatchRelativeToTheProjectsSolution() + { + var filter = new ProjectFilter(Root, ["tests/*"]); + + Assert.Null(filter.Excludes(ProjectPath("plugins/tests/Unit/Unit.csproj"))); + Assert.Equal("tests/*", filter.Excludes(ProjectPath("plugins/tests/Unit/Unit.csproj"), ProjectPath("plugins"))); + } + + [Fact] + public void ReportsPatternsThatMatchNothing() + { + var filter = new ProjectFilter(Root, ["*.Tests", "Typo", " ", "*.TESTS"]); + filter.Excludes(ProjectPath("a/A.Tests.csproj")); + filter.Excludes(ProjectPath("b/B.csproj")); + + Assert.Equal(["*.Tests", "Typo"], filter.Patterns); + Assert.Equal(["Typo"], filter.Unused); + } + + [Fact] + public void CommandLinePatternsAddToConfiguredOnes() + { + var directory = Directory.CreateTempSubdirectory("permissions-config").FullName; + try + { + File.WriteAllText(Path.Combine(directory, "Contoso.slnx"), ""); + File.WriteAllText(Path.Combine(directory, "appsettings.json"), """ + { "XrmMockup": { "Permissions": { "Solution": "Contoso.slnx", "ExcludeProjects": ["*.Tests", "tests/*"] } } } + """); + + var configuration = ConfigReader.Read(Path.Combine(directory, "appsettings.json")); + var settings = AnalysisSettings.Resolve(null, null, configuration, ["Tools"]); + + Assert.Equal(["*.Tests", "tests/*", "Tools"], settings.ExcludeProjects); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void PluginSolutionsAreRelativeToWhereTheyAreGiven() + { + var directory = Directory.CreateTempSubdirectory("permissions-config").FullName; + try + { + Directory.CreateDirectory(Path.Combine(directory, "plugins")); + File.WriteAllText(Path.Combine(directory, "Contoso.slnx"), ""); + File.WriteAllText(Path.Combine(directory, "plugins", "Plugins.slnx"), ""); + File.WriteAllText(Path.Combine(directory, "appsettings.json"), """ + { "XrmMockup": { "Permissions": { "Solution": "Contoso.slnx", "PluginSolutions": ["plugins/Plugins.slnx", "Contoso.slnx"] } } } + """); + var configuration = ConfigReader.Read(Path.Combine(directory, "appsettings.json")); + + var settings = AnalysisSettings.Resolve(null, null, configuration, pluginSolutions: [Path.Combine(directory, "plugins", "Plugins.slnx")]); + Assert.Equal([Path.Combine(directory, "plugins", "Plugins.slnx")], settings.PluginSolutions); + + var missing = Assert.Throws(() => AnalysisSettings.Resolve(null, null, configuration, pluginSolutions: [Path.Combine(directory, "Missing.sln")])); + Assert.Equal($"Plugin solution or project not found: {Path.Combine(directory, "Missing.sln")}", missing.Message); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReferencedCodeTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReferencedCodeTests.cs new file mode 100644 index 00000000..4612bf6c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReferencedCodeTests.cs @@ -0,0 +1,72 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Code of a library the analyzed project references, such as a data access library that several apps share. +/// +public class ReferencedCodeTests +{ + /// + /// A repository with a method the function calls and one only other apps call. + /// + private const string Library = """ + namespace Shared + { + public class Repository + { + public void DeleteLead(IOrganizationService service) => service.Delete("lead", Guid.Empty); + + public void DeleteTask(IOrganizationService service) => service.Delete("task", Guid.Empty); + } + } + """; + + private const string Function = """ + public class Functions + { + [Microsoft.Azure.Functions.Worker.Function("PurgeLead")] + public void Run([Microsoft.Azure.Functions.Worker.HttpTrigger] object request) + { + var client = new Microsoft.PowerPlatform.Dataverse.Client.ServiceClient("AuthType=ClientSecret"); + new Shared.Repository().DeleteLead(client); + } + } + """; + + [Fact] + public void CodeTheProjectCallsIsAnalyzedButTheRestIsNotUnreached() + { + var library = Analyze.Compile(Library, "Shared", "shared/Code.cs"); + var builder = new ManifestBuilder(Analyze.Root); + Assert.True(builder.AddReferencedCode(library)); + Assert.True(builder.Add(Analyze.Compile(Function, "Functions", references: library))); + + var manifest = builder.Build(); + + Assert.Equal(["lead:Delete"], manifest.Entry("function:Functions/PurgeLead").Requirements()); + Assert.Empty(manifest.Unreached); + } + + [Fact] + public void EntryPointsInReferencedCodeAreReported() + { + var builder = new ManifestBuilder(Analyze.Root); + builder.AddReferencedCode(Analyze.Compile(Function, "Functions", references: Analyze.Compile(Library, "Shared"))); + + Assert.Equal(["function:Functions/PurgeLead"], builder.Build().EntryPoints.Select(e => e.Id)); + } + + [Fact] + public void CodeInTheAnalyzedProjectIsUnreachedEvenWhenAlsoAddedAsReferencedCode() + { + var library = Analyze.Compile(Library, "Shared"); + var builder = new ManifestBuilder(Analyze.Root); + builder.AddReferencedCode(library); + builder.Add(library); + + Assert.Equal( + ["Shared.Repository.DeleteLead(IOrganizationService)", "Shared.Repository.DeleteTask(IOrganizationService)"], + builder.Build().Unreached.Select(m => m.Id)); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReportTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReportTests.cs new file mode 100644 index 00000000..3155ab30 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReportTests.cs @@ -0,0 +1,345 @@ +using System.CommandLine; +using System.Text.RegularExpressions; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Commands; +using XrmMockup.PermissionAnalyzer.Tool.Output; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// How much of the report is shown, and filters that narrow it, applied after analysis. +/// +public class ReportTests +{ + private static readonly RoleDefinition Salesperson = new("Salesperson", new Dictionary> + { + ["account"] = new Dictionary { [Privilege.Read] = PrivilegeDepth.User }, + }); + + /// + /// An account Update step that reads an account (granted), creates a contact through a store (missing) and + /// deletes one as SYSTEM, a contact Create step that only reads an account, and a method nothing calls that + /// deletes an account (missing). + /// + private const string Source = """ + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, c => c.OrganizationService.Retrieve("account", Guid.Empty, new ColumnSet())); + } + + private void Execute(LocalPluginContext context) + { + context.OrganizationService.Retrieve("account", Guid.Empty, new ColumnSet()); + new Store().Save(context.OrganizationService); + context.OrganizationAdminService.Delete("contact", Guid.Empty); + } + } + + public class Store + { + public void Save(IOrganizationService service) => service.Create(new Contact()); + } + + public class Purger + { + public void Purge(IOrganizationService service) => service.Delete("account", Guid.Empty); + } + """; + + private const string UpdateStep = "plugin:P:Update:account:PostOperation"; + private const string CreateStep = "plugin:P:Create:contact:PostOperation"; + + private static string Text(ReportOptions options, bool roles = true) + { + var manifest = Analyze.Code(Source, ["account", "contact"]); + var coverage = roles ? CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }) : null; + using var output = new StringWriter(); + new TextManifestWriter(options).Write(manifest, coverage, output); + return output.ToString(); + } + + private static ReportFilter Filter(string[]? tables = null, string[]? privileges = null, RunsAsKind[]? identities = null, RequirementBasis[]? bases = null) => + new(tables ?? [], privileges ?? [], identities ?? [], bases ?? []); + + private static string[] Lines(string text) => text.Split('\n'); + + /// + /// The line is a requirement row matching , whose columns are padded to the widest value. + /// + private static bool Row(string line, string pattern) => Regex.IsMatch(line, $"^ {pattern}$"); + + [Fact] + public void NormalShowsOnlyWhatNeedsAttention() + { + var lines = Lines(Text(new ReportOptions(Detail.Normal))); + + Assert.Contains(lines, l => Row(l, "✘ contact +Create +Caller +missing +Code.cs:36")); + Assert.Contains(lines, l => Row(l, @"✘ account +Delete +Caller \(assumed\) +missing +Code.cs:41")); + Assert.DoesNotContain(lines, l => l.StartsWith(" ✔ ", StringComparison.Ordinal) || l.StartsWith(" · ", StringComparison.Ordinal)); + // The Create step needs nothing the roles don't grant + Assert.DoesNotContain(lines, l => l.StartsWith(CreateStep, StringComparison.Ordinal)); + Assert.DoesNotContain("Privileges per table", lines); + Assert.DoesNotContain(lines, l => l.Contains(" → ", StringComparison.Ordinal)); + Assert.Contains("Result: 2 granted, 2 missing, 1 as SYSTEM", lines); + Assert.Contains("Missing privileges:", lines); + Assert.Equal("Not shown: 3 requirements with nothing to fix, 1 assumption. --detail detailed lists them, full also adds every source and call path", lines[^2]); + } + + [Fact] + public void DetailedAddsGrantedRequirementsButNotCallPaths() + { + var lines = Lines(Text(new ReportOptions(Detail.Detailed))); + + Assert.Contains(lines, l => Row(l, "✔ account +Read +Caller +User +Code.cs:23, Code.cs:28")); + Assert.Contains(lines, l => Row(l, "· contact +Delete +System +SYSTEM +Code.cs:30")); + Assert.Contains(" ~ service comes from parameter 'service' Code.cs:41", lines); + Assert.Contains(lines, l => l.StartsWith(CreateStep, StringComparison.Ordinal)); + Assert.Contains("Privileges per table", lines); + Assert.DoesNotContain(lines, l => l.Contains(" → ", StringComparison.Ordinal)); + Assert.Equal("Not shown: every source and call path. --detail full adds them", lines[^2]); + } + + [Fact] + public void MinimalIsTheDefaultAndListsWhatEachRoleSetLacks() + { + var lines = Lines(Text(ReportOptions.Default)); + + Assert.Equal(Detail.Minimal, ReportOptions.Default.Detail); + Assert.Equal( + [ + "Missing from Salesperson (--role), for Caller:", + " account Delete", + " contact Create", + "", + ], + lines.Take(4)); + Assert.DoesNotContain(lines, l => l.Contains(UpdateStep, StringComparison.Ordinal) || l.Contains("Code.cs", StringComparison.Ordinal)); + Assert.DoesNotContain("Missing privileges:", lines); + Assert.Contains("Result: 2 granted, 2 missing, 1 as SYSTEM", lines); + Assert.Equal("Not shown: entry points, sources and requirements with nothing to fix. --detail compact adds the entry points, normal the sources, detailed everything", lines[^2]); + } + + [Fact] + public void CompactAddsTheEntryPointsThatNeedEachPrivilege() + { + var lines = Lines(Text(new ReportOptions(Detail.Compact))); + + Assert.Equal( + [ + "Missing from Salesperson (--role), for Caller:", + " account Delete", + " contact Create", + "", + " By entry point:", + "", + " " + UpdateStep, + " contact Create", + "", + " Purger.Purge(IOrganizationService)", + " account Delete", + "", + ], + lines.Take(12)); + Assert.Equal("Not shown: sources and requirements with nothing to fix. --detail normal adds the sources, detailed everything", lines[^2]); + } + + [Fact] + public void CompactListsEntryPointsThatNeedTheSameTogether() + { + const string source = """ + public class P : Plugin + { + public P() + { + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, Execute); + RegisterPluginStep(EventOperation.Delete, ExecutionStage.PostOperation, c => c.OrganizationService.Delete("lead", Guid.Empty)); + } + + private void Execute(LocalPluginContext context) + { + context.OrganizationService.Delete("account", Guid.Empty); + context.OrganizationService.Delete("contact", Guid.Empty); + context.OrganizationService.Create(new Entity("lead")); + } + } + """; + // Deleting a contact fires the contact Delete step, so both Update steps also need Delete on lead + var manifest = Analyze.Code(source, ["account", "contact", "lead"]); + using var output = new StringWriter(); + new TextManifestWriter(new ReportOptions(Detail.Compact)).Write(manifest, null, output); + + Assert.Equal( + [ + "Caller needs:", + " account Delete", + " contact Delete", + " lead Create, Delete", + "", + " By entry point:", + "", + " plugin:P:Delete:contact:PostOperation", + " lead Delete", + "", + " plugin:P:Update:account:PostOperation", + " plugin:P:Update:contact:PostOperation", + " account Delete", + " contact Delete", + " lead Create, Delete", + "", + ], + Lines(output.ToString()).Take(16)); + } + + [Fact] + public void FullShowsCallPathsAndNothingIsLeftOut() + { + var text = Text(new ReportOptions(Detail.Full)); + + Assert.Contains("P.Execute → Store.Save", text); + Assert.DoesNotContain("Not shown", text); + } + + [Fact] + public void WithoutRolesMinimalOnlyLeavesOutSystem() + { + var lines = Lines(Text(ReportOptions.Default, roles: false)); + + Assert.Equal("Not shown: entry points, sources and what runs as SYSTEM. --detail compact adds the entry points, normal the sources, detailed everything", lines[^2]); + } + + [Fact] + public void WithoutRolesNormalShowsEveryRequirement() + { + var lines = Lines(Text(new ReportOptions(Detail.Normal), roles: false)); + + Assert.Contains(lines, l => Row(l, "account +Read +Caller +Code.cs:23, Code.cs:28")); + Assert.Contains(lines, l => Row(l, "contact +Delete +System +Code.cs:30")); + Assert.Contains(lines, l => l.StartsWith(CreateStep, StringComparison.Ordinal)); + Assert.Contains("Privileges per table", lines); + } + + [Fact] + public void TableFilterNarrowsTheSectionsAndMissingPrivilegesButNotTheCounts() + { + var lines = Lines(Text(new ReportOptions(Detail.Detailed, Filter(tables: ["CONTACT"])))); + + Assert.DoesNotContain(lines, l => l.StartsWith(" ✔ account", StringComparison.Ordinal) || l.StartsWith(" ✘ account", StringComparison.Ordinal)); + Assert.DoesNotContain(lines, l => l.StartsWith(CreateStep, StringComparison.Ordinal)); + Assert.DoesNotContain("Not reached from any entry point", lines); + Assert.Contains(lines, l => l.StartsWith(UpdateStep, StringComparison.Ordinal)); + Assert.Contains("Filtered by --table CONTACT: 2 of 5 requirements match", lines); + Assert.Contains("Result: 2 granted, 2 missing, 1 as SYSTEM", lines); + var missing = lines.SkipWhile(l => l != "Missing privileges:").Skip(1).TakeWhile(l => l.StartsWith(" ✘ ", StringComparison.Ordinal)); + Assert.Equal([" ✘ contact Create Caller Salesperson (--role) in " + UpdateStep], missing); + } + + [Fact] + public void MinimalIsNarrowedByTheFilter() + { + var lines = Lines(Text(new ReportOptions(Detail.Minimal, Filter(tables: ["account"])))); + + Assert.DoesNotContain(lines, l => l.Contains("contact", StringComparison.Ordinal)); + Assert.Contains(" account Delete", lines); + } + + [Fact] + public void FilterThatMatchesNothingLeavesOnlyTheTotals() + { + var lines = Lines(Text(ReportOptions.Default with { Filter = Filter(bases: [RequirementBasis.AllImplementations]) })); + + Assert.DoesNotContain(lines, l => l.StartsWith("plugin:", StringComparison.Ordinal)); + Assert.DoesNotContain("Missing privileges:", lines); + Assert.Contains("Filtered by --basis all-implementations: 0 of 5 requirements match", lines); + Assert.Contains("Result: 2 granted, 2 missing, 1 as SYSTEM", lines); + } + + [Fact] + public void IdentityAndPrivilegeFiltersCombine() + { + var lines = Lines(Text(new ReportOptions(Detail.Detailed, Filter(privileges: ["delete"], identities: [RunsAsKind.System])))); + + var rows = lines.Where(l => l.StartsWith(" · ", StringComparison.Ordinal) || l.StartsWith(" ✔ ", StringComparison.Ordinal) || l.StartsWith(" ✘ ", StringComparison.Ordinal)); + Assert.True(Row(Assert.Single(rows), "· contact +Delete +System +SYSTEM +Code.cs:30")); + } + + [Fact] + public void JsonIsNarrowedByTheFilterButKeepsTheResult() + { + var manifest = Analyze.Code(Source, ["account", "contact"]); + var coverage = CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = RoleSet.Combine([Salesperson], "--role") }); + using var output = new StringWriter(); + new JsonManifestWriter(Filter(tables: ["contact"])).Write(manifest, coverage, output); + var json = output.ToString(); + + // account Read and Delete are left out; the Update step's trigger is still on account + Assert.DoesNotContain("\"privilege\": \"Read\"", json); + Assert.Contains("\"privilege\": \"Create\"", json); + Assert.DoesNotContain($"\"id\": \"{CreateStep}\"", json); + Assert.Contains("\"unreached\": []", json); + Assert.Contains("\"missing\": 2", json); + Assert.Contains("\"missing\": [\n {\n \"table\": \"contact\"", json); + } + + [Fact] + public void FiltersTakeCommaSeparatedAndRepeatedValues() + { + var command = new RootCommand(); + var options = new AnalysisOptions(); + options.AddTo(command); + var result = command.Parse(["--table", "account,contact", "--table", "lead", "--runs-as", "system", "--basis", "filter-unknown", "-d", "full"]); + + Assert.Empty(result.Errors); + var report = options.Read(result).Report!; + Assert.Equal(Detail.Full, report.Detail); + Assert.Equal("--table account, contact, lead; --runs-as System; --basis filter-unknown", report.Filter.ToString()); + } + + [Fact] + public void StrictAlsoFailsOnMissing() + { + var command = new RootCommand(); + var options = new AnalysisOptions(); + options.AddTo(command); + + var plain = options.Read(command.Parse([])); + Assert.False(plain.FailOnMissing); + var strict = options.Read(command.Parse(["--strict"])); + Assert.True(strict.FailOnMissing); + Assert.True(strict.Strict); + } + + [Fact] + public void NoRolesCantBeUsedWithRolesOrFailing() + { + var command = new RootCommand(); + new AnalysisOptions().AddTo(command); + + Assert.Empty(command.Parse(["--no-roles"]).Errors); + Assert.Equal( + "--no-roles can't be used with --fail-on-missing, which needs roles.", + Assert.Single(command.Parse(["--no-roles", "--fail-on-missing"]).Errors).Message); + Assert.Equal( + "--no-roles can't be used with --role, which needs roles.", + Assert.Single(command.Parse(["--no-roles", "-r", "Salesperson", "--strict"]).Errors).Message); + } + + [Fact] + public void UnknownIdentityOrBasisIsAnError() + { + var command = new RootCommand(); + new AnalysisOptions().AddTo(command); + var result = command.Parse(["--runs-as", "Admin", "--basis", "guess"]); + + Assert.Equal( + [ + "Unknown identity 'Admin' in --runs-as. Use Caller, User, ApplicationUser, ImpersonatedCaller, System.", + "Unknown basis 'guess' in --basis. Use direct, execute-privilege, all-implementations, all-lookup-targets, filter-unknown.", + ], + result.Errors.Select(e => e.Message)); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReturnedTableTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReturnedTableTests.cs new file mode 100644 index 00000000..7888057b --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/ReturnedTableTests.cs @@ -0,0 +1,240 @@ +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Tables that reach a service call through a method's return value or a generic method's type argument. +/// +public class ReturnedTableTests +{ + [Fact] + public void EntityReturnedByHelperResolvesToEveryReturnedTable() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service, bool flag) => service.Create(Build(flag)); + + Entity Build(bool flag) + { + if (flag) return new Account(); + return new Contact(); + } + } + """); + + Assert.Equal(["account:Create", "contact:Create"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void ReturnedValueUsesTheArgumentsOfTheCall() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => service.Delete(Table("contact"), Guid.Empty); + + static string Table(string name) => name; + } + """); + + Assert.Equal(["contact:Delete"], method.Requirements()); + Assert.Empty(method.Unresolved); + } + + [Fact] + public void QueryFromGenericHelperResolvesThroughTypeArguments() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => new Repository(c.OrganizationService).ByIds()); + } + + public class Repository(IOrganizationService service) + { + public List ByIds() where E : Entity => Retrieve(Query()); + + private List Retrieve(QueryExpression query) where E : Entity => + service.RetrieveMultiple(query).Entities.Cast().ToList(); + + private static QueryExpression Query() where E : Entity + { + var instance = Activator.CreateInstance(); + var query = new QueryExpression(instance.LogicalName); + query.ColumnSet.AddColumn("name"); + return query; + } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["contact:Read as Caller"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void GenericExtensionMethodResolvesTypeArgument() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => c.OrganizationService.Get(Guid.Empty)); + } + + public static class Extensions + { + public static T Get(this IOrganizationService service, Guid id) where T : Entity, new() => + service.Retrieve(new T().LogicalName, id, new ColumnSet(true)).ToEntity(); + } + """); + + Assert.Equal(["contact:Read as Caller"], manifest.Entry("plugin:P:Update:account:PostOperation").RequirementsWithIdentity()); + } + + [Fact] + public void UnboundTypeParameterIsStillReported() + { + var manifest = Analyze.Code(""" + public static class Extensions + { + public static void Remove(this IOrganizationService service, Guid id) where T : Entity, new() => + service.Delete(new T().LogicalName, id); + } + """); + + Assert.Equal("table depends on type parameter 'T'", Assert.Single(Assert.Single(manifest.Unreached).Unresolved).Reason); + } + + [Fact] + public void TypeParameterOfAGenericTypeIsTheReceiversTypeArgument() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => + { + new Repository(c.OrganizationService).Remove(Guid.Empty); + new TaskRepository(c.OrganizationService).Archive(Guid.Empty); + }); + } + + public class Repository(IOrganizationService service) where T : Entity, new() + { + public virtual void Remove(Guid id) => service.Delete(new T().LogicalName, id); + + public void Archive(Guid id) => Remove(id); + } + + public class TaskRepository(IOrganizationService service) : Repository(service); + + [EntityLogicalName("task")] + public class Task : Entity + { + public Task() : base("task") { } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["contact:Delete as Caller", "task:Delete as Caller"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void TypeParameterOfAGenericTypeIsPassedOnByAnOverride() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => + { + Repository repository = new LoggedRepository(c.OrganizationService); + repository.Remove(Guid.Empty); + }); + } + + public class Repository(IOrganizationService service) where T : Entity, new() + { + protected IOrganizationService Service { get; } = service; + + public virtual void Remove(Guid id) => Service.Delete(new T().LogicalName, id); + } + + public class LoggedRepository(IOrganizationService service) : Repository(service) where E : Entity, new() + { + public override void Remove(Guid id) + { + Service.Create(new E()); + base.Remove(id); + } + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["contact:Create as Caller", "contact:Delete as Caller"], entry.RequirementsWithIdentity()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void TypeParameterOfAGenericTypeIsTheTypeArgumentOfTheInterfaceItIsCalledOn() + { + var manifest = Analyze.Code(""" + public class P : Plugin + { + public P() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, c => Remove(Repositories.Contacts(c.OrganizationService))); + + private static void Remove(IRepository contacts) => contacts.Remove(Guid.Empty); + } + + public interface IRepository where T : Entity + { + void Remove(Guid id); + } + + public class Repository(IOrganizationService service) : IRepository where E : Entity, new() + { + public void Remove(Guid id) => service.Delete(new E().LogicalName, id); + } + + public static class Repositories + { + public static IRepository Contacts(IOrganizationService service) => new Repository(service); + } + """); + + var entry = manifest.Entry("plugin:P:Update:account:PostOperation"); + Assert.Equal(["contact:Delete"], entry.Requirements()); + Assert.Empty(entry.Unresolved); + } + + [Fact] + public void ReasonInsideHelperIsReported() + { + var method = Analyze.Method(""" + class C + { + private Entity? _pending; + + void M(IOrganizationService service) => service.Create(Pending()); + + Entity Pending() => _pending!; + } + """); + + Assert.Equal("entity comes from field '_pending'", Assert.Single(method.Unresolved).Reason); + } + + [Fact] + public void RecursiveHelperTerminates() + { + var method = Analyze.Method(""" + class C + { + void M(IOrganizationService service) => service.RetrieveMultiple(Query(3)); + + QueryExpression Query(int depth) => depth == 0 ? new QueryExpression("account") : Query(depth - 1); + } + """); + + Assert.Equal(["account:Read"], method.Requirements()); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/RoleLoaderTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/RoleLoaderTests.cs new file mode 100644 index 00000000..c6f2443f --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/RoleLoaderTests.cs @@ -0,0 +1,117 @@ +using System.Runtime.Serialization; +using XrmMockup.PermissionAnalyzer.Workspace.Serialization; +using Microsoft.Crm.Sdk.Messages; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Metadata; +using CrmDepth = Microsoft.Crm.Sdk.Messages.PrivilegeDepth; +using RolePrivilege = XrmMockup.PermissionAnalyzer.Workspace.Serialization.RolePrivilege; +using PrivilegeDepth = XrmMockup.PermissionAnalyzer.Core.Model.PrivilegeDepth; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class RoleLoaderTests +{ + private static string MetadataDirectory([System.Runtime.CompilerServices.CallerFilePath] string path = "") => + Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path)!, "..", "..", "..", "tests", "XrmMockup365Test", "Metadata")); + + [Fact] + public void LoadsTheTestSecurityRolesSortedByName() + { + var roles = RoleLoader.Load(MetadataDirectory()); + + Assert.NotEmpty(roles); + Assert.Equal(roles.Select(r => r.Name).OrderBy(n => n, StringComparer.Ordinal), roles.Select(r => r.Name)); + Assert.All(roles, r => Assert.NotEmpty(r.Privileges)); + Assert.Contains(roles, r => r.Privileges.Values.Any(p => p.ContainsKey(Privilege.Read))); + } + + [Fact] + public void RolesWithTheSameNameAreInFileNameOrder() + { + // Every business unit has its own copy of a role, so names repeat + var directory = Directory.CreateTempSubdirectory().FullName; + try + { + var roles = Directory.CreateDirectory(Path.Combine(directory, RoleLoader.SecurityRolesFolder)).FullName; + foreach (var (file, old) in new[] { ("b.xml", true), ("a.xml", false) }) + { + using var stream = File.Create(Path.Combine(roles, file)); + new DataContractSerializer(typeof(SecurityRole)).WriteObject(stream, new SecurityRole + { + Name = "Salesperson", + Privileges = [], + GlobalPrivileges = old ? null! : new(), + }); + } + + Assert.Equal([false, true], RoleLoader.Load(directory).Select(r => r.GlobalPrivileges is null)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void MissingFolderGivesNoRoles() + { + Assert.Empty(RoleLoader.Load(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()))); + } + + [Fact] + public void GlobalPrivilegesAreConvertedByName() + { + var role = RoleLoader.Convert(new SecurityRole + { + Name = "Integration", + Privileges = [], + GlobalPrivileges = new() { ["prvActOnBehalfOfAnotherUser"] = new RolePrivilege { PrivilegeDepth = CrmDepth.Global } }, + }); + + Assert.Equal(PrivilegeDepth.Organization, role.GlobalPrivileges!["PRVACTONBEHALFOFANOTHERUSER"]); + } + + [Fact] + public void RoleFromOlderMetadataHasNoGlobalPrivileges() + { + Assert.Null(RoleLoader.Convert(new SecurityRole { Name = "Old", Privileges = [] }).GlobalPrivileges); + } + + [Fact] + public void PrivilegeCatalogIsLoadedFromTheMetadataFolder() + { + var directory = Directory.CreateTempSubdirectory().FullName; + try + { + using (var stream = File.Create(Path.Combine(directory, PrivilegeCatalogLoader.FileName))) + { + new DataContractSerializer(typeof(PrivilegeCatalog)).WriteObject(stream, new PrivilegeCatalog + { + Privileges = + [ + new MetaPrivilege { Name = "prvReadctx_Order", AccessRight = AccessRights.ReadAccess, Tables = ["ctx_order"] }, + new MetaPrivilege { Name = "prvActOnBehalfOfAnotherUser", AccessRight = AccessRights.None, Tables = [] }, + ], + CustomApis = [new MetaCustomApi { UniqueName = "ctx_Ping" }], + }); + } + + var (privileges, customApis) = PrivilegeCatalogLoader.Load(directory)!.Value; + + Assert.Equal( + ["prvActOnBehalfOfAnotherUser ", "prvReadctx_Order Read ctx_order"], + privileges.Select(p => $"{p.Name} {p.Privilege} {string.Join(",", p.Tables)}")); + Assert.Equal(new CustomApiDefinition("ctx_Ping", null), Assert.Single(customApis)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void MissingPrivilegeCatalogGivesNull() + { + Assert.Null(PrivilegeCatalogLoader.Load(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()))); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/SdkAnalysisTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/SdkAnalysisTests.cs new file mode 100644 index 00000000..35d2040e --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/SdkAnalysisTests.cs @@ -0,0 +1,221 @@ +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class SdkAnalysisTests +{ + private const string Plugins = """ + namespace Contoso { + public class ContactPlugin : Plugin { + public ContactPlugin() => RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, + c => c.OrganizationService.Update(new Account { ["name"] = "changed" })); + } + public class AccountPlugin : Plugin { + public AccountPlugin() => RegisterPluginStep(EventOperation.Update, ExecutionStage.PostOperation, + c => c.OrganizationService.Delete("lead", Guid.Empty)).SetExecutionMode(ExecutionMode.Asynchronous).AddFilteredAttributes("name"); + } + } + """; + + [Fact] + public void FreshMetadataCopiesReuseSourceAndIncludeRecursiveAsyncCascades() + { + var builder = Source(Plugins); + var metadata = new PermissionMetadata { RoleGovernedTables = ["contact", "account", "lead"] }; + var copy = builder.WithMetadata(metadata); + copy.AddOperation("Create", "contact"); + var manifest = copy.Build(metadata.RoleGovernedTables, EntryPointSelector.Operation("Create", "contact")); + var entry = Assert.Single(manifest.EntryPoints); + Assert.Equal(["account:Write", "contact:Create", "lead:Delete"], entry.Requirements()); + Assert.Equal(2, entry.Triggers.Count); + Assert.Empty(manifest.Unreached); + var next = builder.WithMetadata(metadata); + next.AddOperation("Create", "task"); + Assert.Equal(["task:Create"], Assert.Single(next.Build(scope: EntryPointSelector.Operation("Create", "task")).EntryPoints).Requirements()); + } + + [Theory] + [InlineData("name", true)] + [InlineData("description", false)] + public void OperationFilteringAttributesApply(string attribute, bool fires) + { + var builder = Source(Plugins).WithMetadata(new PermissionMetadata()); + builder.AddOperation("Update", "account", [attribute]); + var entry = Assert.Single(builder.Build(scope: EntryPointSelector.Operation("Update", "account")).EntryPoints); + Assert.Equal(fires, entry.Triggers.Count != 0); + Assert.Contains(entry.Requirements, r => r.Table == "account" && r.Privilege == Privilege.Write); + } + + [Fact] + public void CurrentLookupMetadataAppliesToSyntheticOperation() + { + var builder = Source(Plugins).WithMetadata(new PermissionMetadata { Lookups = [new LookupColumn("task", "regardingobjectid", ["account", "contact"])] }); + builder.AddOperation("Create", "task", ["regardingobjectid"]); + var entry = Assert.Single(builder.Build(scope: EntryPointSelector.Operation("Create", "task")).EntryPoints); + Assert.Equal(["account:AppendTo", "contact:AppendTo", "task:Create", "task:Append"], entry.Requirements()); + } + + [Fact] + public void CheckTimeWorkflowsReplaceLoadedFileRegistrations() + { + var source = Source(Plugins); + source.AddWorkflows([new WorkflowRegistration("File workflow", "task", true, false, null, false, null)]); + var active = source.WithMetadata(new PermissionMetadata()); + active.AddOperation("Create", "task"); + Assert.Contains(Assert.Single(active.Build(scope: EntryPointSelector.Operation("Create", "task")).EntryPoints).Unresolved, u => u.Reason.Contains("File workflow")); + var disabled = source.WithMetadata(new PermissionMetadata { Workflows = [] }); + disabled.AddOperation("Create", "task"); + Assert.Empty(Assert.Single(disabled.Build(scope: EntryPointSelector.Operation("Create", "task")).EntryPoints).Unresolved); + } + + [Fact] + public void SourceLookupRequirementsUseCheckTimeMetadataAndCanChange() + { + var source = Source(""" + [EntityLogicalName("ctx_order")] + public class Order : Entity { + [AttributeLogicalName("ctx_customerid")] + public EntityReference Customer => GetAttributeValue("ctx_customerid"); + } + class C { + public void Run(IOrganizationService service, Order order) => service.Delete(order.Customer.LogicalName, order.Customer.Id); + } + """); + source.AddEntryMethods(["C.Run"]); + var first = source.WithMetadata(new PermissionMetadata { Lookups = [new LookupColumn("ctx_order", "ctx_customerid", ["account"])] }); + var second = source.WithMetadata(new PermissionMetadata { Lookups = [new LookupColumn("ctx_order", "ctx_customerid", ["contact"])] }); + Assert.Equal(["account:Delete"], Assert.Single(first.Build(scope: EntryPointSelector.Methods(["C.Run"])).EntryPoints).Requirements()); + Assert.Equal(["contact:Delete"], Assert.Single(second.Build(scope: EntryPointSelector.Methods(["C.Run"])).EntryPoints).Requirements()); + } + + [Fact] + public void TypedPluginRequiresFullIdentityAndMessageStage() + { + var builder = Source(Plugins); + var scope = PermissionScope.ForPlugin("Contoso.ContactPlugin", "Test", "Create", "PostOperation"); + var entry = Assert.Single(builder.Build(scope: EntryPointSelector.TypedPlugin(scope)).EntryPoints); + Assert.Equal("Contoso.ContactPlugin", entry.Type); + Assert.Empty(builder.Build(scope: EntryPointSelector.TypedPlugin(PermissionScope.ForPlugin("ContactPlugin", "Test"))).EntryPoints); + Assert.Empty(builder.Build(scope: EntryPointSelector.TypedPlugin(PermissionScope.ForPlugin("Contoso.ContactPlugin", "Other"))).EntryPoints); + Assert.Empty(builder.Build(scope: EntryPointSelector.TypedPlugin(PermissionScope.ForPlugin("Contoso.ContactPlugin", "Test", "Delete"))).EntryPoints); + } + + [Fact] + public void SharedEngineParity() + { + var source = Source(Plugins); + source.AddOperation("Create", "contact"); + var cli = source.Build(scope: EntryPointSelector.Operation("Create", "contact")); + var sdk = source.WithMetadata(new PermissionMetadata()); + sdk.AddOperation("Create", "contact"); + var manifest = sdk.Build(scope: EntryPointSelector.Operation("Create", "contact")); + Assert.Equal(Assert.Single(cli.EntryPoints).RequirementsWithIdentity(), Assert.Single(manifest.EntryPoints).RequirementsWithIdentity()); + Assert.Equal(Assert.Single(cli.EntryPoints).Triggers, Assert.Single(manifest.EntryPoints).Triggers); + } + + [Fact] + public void UnknownIdentityCannotPassJustBecauseATableIsNotGoverned() + { + var source = Source(""" + public class P : Plugin { + public P() => RegisterPluginStep(EventOperation.Create, ExecutionStage.PostOperation, + c => c.OrganizationService.Delete("not_governed", Guid.Empty)).SetUserContext(Guid.Parse("6f1c2a9e-0000-4000-8000-000000000001")); + } + """); + var manifest = source.Build([], EntryPointSelector.Plugin("P")); + var options = new CoverageOptions { Roles = RoleSet.Combine([], "test") }; + Assert.True(CoverageEvaluator.Evaluate(manifest, options).Summary.Passed(strict: true)); // CLI parity + var result = new PermissionCheckResult(manifest, CoverageEvaluator.EvaluateForPermissionCheck(manifest, options)); + Assert.False(result.Passed); + Assert.Equal(1, result.Coverage.Summary.NotChecked); + Assert.Throws(result.ThrowIfFailed); + } + + [Fact] + public void ResultIsAlwaysStrictAndExceptionIncludesDiagnostics() + { + var source = Source("class C { public void Run(IOrganizationService s) { s.Create(new Account()); s.Execute(new OrganizationRequest(\"unknown\")); } }"); + source.AddEntryMethods(["C.Run"]); + var manifest = source.Build(["account"], EntryPointSelector.Methods(["C.Run"])); + var roles = RoleSet.Combine([new RoleDefinition("Display role name", new Dictionary>())], "test"); + var result = new PermissionCheckResult(manifest, CoverageEvaluator.Evaluate(manifest, new CoverageOptions { Roles = roles })); + Assert.False(result.Passed); + var error = Assert.Throws(result.ThrowIfFailed); + Assert.Same(result, error.Result); + Assert.Contains("Display role name", error.Message); + Assert.Contains("Code.cs", error.Message); + Assert.Contains("Unresolved", error.Message); + Assert.Contains("account Create", error.Message); + } + + [Theory] + [InlineData(false, false, false, false)] + [InlineData(true, false, false, false)] + [InlineData(false, true, false, false)] + [InlineData(false, false, true, false)] + [InlineData(false, false, false, true)] + public void AllIncompleteCategoriesFail(bool unresolved, bool uncheckedIdentity, bool unavailable, bool truncated) + { + var summary = new CoverageSummary(0, 0, 0, 0, uncheckedIdentity ? 1 : 0, 0, unresolved ? 1 : 0, 0, 0, 0, unavailable ? 1 : 0, truncated ? 1 : 0); + var result = new PermissionCheckResult(new Manifest([], []), new CoverageReport(new Dictionary(), new Dictionary(), summary, [], [], false)); + Assert.Equal(!summary.Incomplete, result.Passed); + if (summary.Incomplete) Assert.Throws(result.ThrowIfFailed); + else result.ThrowIfFailed(); + } + + [Fact] + public async Task WorkspaceLoadDoesNotSilentlyIgnoreCompilationErrors() + { + var directory = Path.Combine(Path.GetTempPath(), "permission-sdk-" + Guid.NewGuid()); + Directory.CreateDirectory(directory); + try + { + var project = Path.Combine(directory, "BrokenSource.csproj"); + var sdkAssembly = System.Security.SecurityElement.Escape(typeof(Microsoft.Xrm.Sdk.IPlugin).Assembly.Location); + await File.WriteAllTextAsync(project, $""" + + net10.0 + {sdkAssembly} + + """); + await File.WriteAllTextAsync(Path.Combine(directory, "Broken.cs"), """ + using System; + using Microsoft.Xrm.Sdk; + public class P : IPlugin { + public void Execute(IServiceProvider provider) { ThisMethodDoesNotExist(); } + } + """); + var start = new System.Diagnostics.ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") + { + Arguments = $"restore \"{project}\" --ignore-failed-sources", + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + using var restore = System.Diagnostics.Process.Start(start)!; + var output = await restore.StandardOutput.ReadToEndAsync(); + var errors = await restore.StandardError.ReadToEndAsync(); + await restore.WaitForExitAsync(); + Assert.True(restore.ExitCode == 0, output + errors); + var analysis = await PermissionAnalysis.LoadAsync(project); + var manifest = analysis.Analyze(PermissionScope.ForOperation("Create", "task"), new PermissionMetadata()); + Assert.Contains(Assert.Single(manifest.EntryPoints).Unresolved, u => u.Operation == "source compilation" && u.Reason.Contains("ThisMethodDoesNotExist")); + var result = new PermissionCheckResult(manifest, CoverageEvaluator.Evaluate(manifest, new CoverageOptions + { + Roles = RoleSet.Combine([], "test") + })); + Assert.False(result.Passed); + Assert.Throws(result.ThrowIfFailed); + } + finally { Directory.Delete(directory, recursive: true); } + } + + private static ManifestBuilder Source(string code) + { + var builder = new ManifestBuilder(Analyze.Root); + Assert.True(builder.Add(Analyze.Compile(code))); + return builder; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/WorkflowLoaderTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/WorkflowLoaderTests.cs new file mode 100644 index 00000000..8c2d8338 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/WorkflowLoaderTests.cs @@ -0,0 +1,77 @@ +using System.Runtime.Serialization; +using Microsoft.Xrm.Sdk; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Metadata; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +public class WorkflowLoaderTests +{ + [Fact] + public void ReadsTheWorkflowsThatRunOnATable() + { + var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(Path.Combine(directory, WorkflowLoader.WorkflowsFolder)); + try + { + var ownerId = Guid.NewGuid(); + Write(directory, "a.xml", Workflow("Notify owner", "account", mode: 1, runAs: 1, ownerId, onCreate: true, updateColumns: "statecode, Name")); + Write(directory, "b.xml", Workflow("Send welcome", "contact", mode: 0, runAs: 1, ownerId, onCreate: true)); + Write(directory, "c.xml", Workflow("On demand only", "account", mode: 1, runAs: 1, ownerId)); + var action = Workflow("ctx_DoThing", "none", mode: 1, runAs: 1, ownerId, onCreate: true); + action["category"] = new OptionSetValue(3); + Write(directory, "d.xml", action); + + Assert.Equal( + [ + new WorkflowRegistration("Notify owner", "account", true, false, ["name", "statecode"], true, null), + new WorkflowRegistration("Send welcome", "contact", true, false, null, false, ownerId.ToString()), + ], + WorkflowLoader.Load(directory), + new WorkflowComparer()); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void MetadataWithoutWorkflowsGivesNone() + { + Assert.Empty(WorkflowLoader.Load(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()))); + } + + private static Entity Workflow(string name, string table, int mode, int runAs, Guid ownerId, bool onCreate = false, string? updateColumns = null) => + new("workflow", Guid.NewGuid()) + { + ["name"] = name, + ["category"] = new OptionSetValue(0), + ["primaryentity"] = table, + ["mode"] = new OptionSetValue(mode), + ["runas"] = new OptionSetValue(runAs), + ["ownerid"] = new EntityReference("systemuser", ownerId), + ["triggeroncreate"] = onCreate, + ["triggerondelete"] = false, + ["triggeronupdateattributelist"] = updateColumns, + }; + + private static void Write(string directory, string file, Entity workflow) + { + using var stream = File.Create(Path.Combine(directory, WorkflowLoader.WorkflowsFolder, file)); + new DataContractSerializer(typeof(Entity)).WriteObject(stream, workflow); + } + + /// + /// Compares the update columns by value, which the record's own equality doesn't. + /// + private sealed class WorkflowComparer : IEqualityComparer + { + public bool Equals(WorkflowRegistration? x, WorkflowRegistration? y) => + x is not null && y is not null + && x with { UpdateColumns = null } == y with { UpdateColumns = null } + && (x.UpdateColumns ?? []).SequenceEqual(y.UpdateColumns ?? []); + + public int GetHashCode(WorkflowRegistration obj) => obj.Name.GetHashCode(); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tests/WorkflowTests.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/WorkflowTests.cs new file mode 100644 index 00000000..4ee4c5a1 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tests/WorkflowTests.cs @@ -0,0 +1,79 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Output; + +namespace XrmMockup.PermissionAnalyzer.Tests; + +/// +/// Workflows from the metadata, which operations fire like plugin steps but whose steps aren't analyzed. +/// +public class WorkflowTests +{ + private const string UserId = "6f1c2a9e-0000-4000-8000-000000000001"; + + private const string Importer = """ + namespace Contoso + { + public class Importer + { + public void Create(IOrganizationService service) => service.Create(new Entity("account")); + + public void Rename(IOrganizationService service) => service.Update(new Entity("account") { ["name"] = "Renamed" }); + + public void Close(IOrganizationService service) => service.Update(new Entity("account") { ["statecode"] = 1 }); + } + } + """; + + [Fact] + public void FiredRealTimeWorkflowIsUnresolved() + { + var manifest = Run(new WorkflowRegistration("Set credit limit", "account", OnCreate: true, OnDelete: false, null, RealTime: true, null)); + + var run = manifest.Entry("method:Contoso.Importer.Create(IOrganizationService)"); + Assert.Equal(["account:Create"], run.Requirements()); + Assert.Equal(["workflow:Set credit limit:Create:account"], run.Triggers); + var unresolved = Assert.Single(run.Unresolved); + Assert.Equal("fires real-time workflow 'Set credit limit', whose steps aren't analyzed", unresolved.Reason); + Assert.Equal(RunsAsKind.ApplicationUser, unresolved.RunsAs.Kind); + Assert.Empty(unresolved.Privileges); + } + + [Fact] + public void UpdateFiresTheWorkflowOnlyForItsColumns() + { + var manifest = Run(new WorkflowRegistration("Notify owner", "account", OnCreate: false, OnDelete: false, ["statecode"], RealTime: true, null)); + + Assert.Empty(manifest.Entry("method:Contoso.Importer.Create(IOrganizationService)").Unresolved); + Assert.Empty(manifest.Entry("method:Contoso.Importer.Rename(IOrganizationService)").Unresolved); + Assert.Equal(["workflow:Notify owner:Update:account"], manifest.Entry("method:Contoso.Importer.Close(IOrganizationService)").Triggers); + } + + [Fact] + public void BackgroundWorkflowRunsAsItsOwner() + { + var manifest = Run(new WorkflowRegistration("Send welcome", "account", OnCreate: true, OnDelete: false, null, RealTime: false, UserId)); + + var unresolved = Assert.Single(manifest.Entry("method:Contoso.Importer.Create(IOrganizationService)").Unresolved); + Assert.Equal("fires background workflow 'Send welcome', whose steps aren't analyzed", unresolved.Reason); + Assert.Equal(RunsAs.User(UserId), unresolved.RunsAs); + } + + [Fact] + public void ResultCountsFiredWorkflows() + { + var manifest = Run(new WorkflowRegistration("Set credit limit", "account", OnCreate: true, OnDelete: false, null, RealTime: true, null)); + + var summary = CoverageEvaluator.Evaluate(manifest, new CoverageOptions()).Summary; + Assert.Equal(1, summary.UnresolvedWorkflow); + Assert.False(summary.Passed(strict: true)); + Assert.Equal("Not checked: 1 unresolved operation (1 workflow whose steps aren't analyzed)", ReportText.NotChecked(summary with { NotChecked = 0 })); + } + + private static Manifest Run(WorkflowRegistration workflow) => + Analyze.Code(Importer, setup: builder => + { + builder.AddWorkflows([workflow]); + builder.AddEntryMethods(["Contoso.Importer.Create", "Contoso.Importer.Rename", "Contoso.Importer.Close"]); + }); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/CHANGELOG.md b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/CHANGELOG.md new file mode 100644 index 00000000..7af962da --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/CHANGELOG.md @@ -0,0 +1,18 @@ +# Changelog + +All notable changes to XrmMockup.PermissionAnalyzer will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +### v1.0.0-rc.1 - 23 October 2026 +* Add: `xrmmockup-permissions`, which lists the Dataverse table privileges, and privileges not tied to a table, that a solution or project needs, found by static analysis of its `IOrganizationService`, request and `OrganizationServiceContext` calls +* Add: Checking them against security roles from the XrmMockup metadata, with `--fail-on-missing` to exit with `1` when a privilege is missing (`--strict` also fails on what couldn't be checked) +* Add: Entry points (XrmPluginCore plugin steps and custom APIs, plugin steps from the metadata, code activities and Azure Functions), followed through the call graph and dependency injection, with the identity each operation runs as +* Add: Plugin cascades, including filtered attributes, bypass parameters and plugin code from other solutions (`--plugin-solution`) +* Add: Workflows from the metadata that an operation fires are reported as unresolved, since their steps aren't analyzed +* Add: Scopes to analyze one entry point or user operation (`--plugin`, `--custom-api`, `--function`, `--entry`, `--operation`) +* Add: Roles per identity from `--role`, `--caller-role` and the `Principals` and `Users` settings, with `Suppress` and `Rules` for custom messages, under `XrmMockup:Permissions` in `appsettings.json` +* Add: Text, JSON, Markdown and SARIF output (`--format`), with `--detail` levels and `--table`, `--privilege`, `--runs-as` and `--basis` filters. The default shows only the privileges to change per role +* Add: Operations whose table can't be determined are reported as unresolved, with the reason +* Fix: Preserve framework-specific helper arguments, return values and constructor service fields when merging a multi-targeted project, including their plugin cascades diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/CliOptions.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/CliOptions.cs new file mode 100644 index 00000000..85905353 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/CliOptions.cs @@ -0,0 +1,155 @@ +namespace XrmMockup.PermissionAnalyzer.Tool; + +/// +/// CLI option definitions for consistency. +/// +internal static class CliOptions +{ + internal static class Solution + { + public const string Primary = "--solution"; + public const string Alias = "-s"; + public const string Description = "Solution (.sln or .slnx) or project (.csproj) to analyze. A project is analyzed with the projects it references. Default: XrmMockup:Permissions:Solution, else the single solution in the current directory"; + } + + internal static class Metadata + { + public const string Primary = "--metadata"; + public const string Alias = "-m"; + public const string Description = "XrmMockup metadata folder. Default: XrmMockup:Permissions:MetadataDirectory, else XrmMockup:Metadata:OutputDirectory, else ./Metadata next to the configuration when it exists"; + } + + internal static class Exclude + { + public const string Primary = "--exclude"; + public const string Alias = "-x"; + public const string Description = "Leave out projects matching this pattern, e.g. \"*.Tests\" or \"tests/*\". Repeatable; adds to XrmMockup:Permissions:ExcludeProjects"; + } + + internal static class PluginSolution + { + public const string Primary = "--plugin-solution"; + public const string Description = "A solution or project with plugin code that the analyzed code fires but doesn't include. Used for plugin cascades only. Repeatable; adds to XrmMockup:Permissions:PluginSolutions"; + } + + internal static class Config + { + public const string Primary = "--config"; + public const string Alias = "-c"; + public const string Description = "Configuration file. appsettings.{DOTNET_ENVIRONMENT}.json in its folder and environment variables apply over it. Default: appsettings.json in the current directory, when it exists"; + } + + internal static class Format + { + public const string Primary = "--format"; + public const string Alias = "-f"; + public const string Description = "Output format: text, json, markdown (for a pull request comment or job summary) or sarif (for code scanning)"; + public static readonly string[] AllowedValues = Enum.GetNames().Select(n => n.ToLowerInvariant()).ToArray(); + } + + internal static class Output + { + public const string Primary = "--output"; + public const string Alias = "-o"; + public const string Description = "Write the report to this file instead of standard output"; + } + + internal static class Plugin + { + public const string Primary = "--plugin"; + public const string Description = "Only analyze one plugin, or some of its steps: [:[:]], e.g. AccountPostPlugin:Update"; + } + + internal static class CustomApi + { + public const string Primary = "--custom-api"; + public const string Description = "Only analyze one custom API, by unique name"; + } + + internal static class Function + { + public const string Primary = "--function"; + public const string Description = "Only analyze one Azure Function, by function name"; + } + + internal static class Entry + { + public const string Primary = "--entry"; + public const string Description = "Only analyze this method, e.g. Contoso.Sync.Importer.Run, as an entry point. Repeatable"; + } + + internal static class Operation + { + public const string Primary = "--operation"; + public const string Description = "Only analyze a user operation on a table and the plugin steps it fires: \"
\", e.g. \"Update account\""; + } + + internal static class Attributes + { + public const string Primary = "--attributes"; + public const string Description = "The columns the --operation sets, which decide the Update steps filtered on columns it fires. Comma-separated or repeatable"; + } + + internal static class Role + { + public const string Primary = "--role"; + public const string Alias = "-r"; + public const string Description = "Security role of the caller and the application user, by name. Repeatable; roles combine. Replaces XrmMockup:Permissions:Principals"; + } + + internal static class CallerRole + { + public const string Primary = "--caller-role"; + public const string Description = "Security role of the user that app code acts for by setting CallerId, by name. Repeatable"; + } + + internal static class Detail + { + public const string Primary = "--detail"; + public const string Alias = "-d"; + public const string Description = "How much of the text report to show: minimal shows only the privileges to change per role, compact adds the entry points that need them, normal shows what needs attention with its sources, detailed adds granted requirements and assumptions, full adds every source and call path. Text only; the other formats ignore it"; + public static readonly string[] AllowedValues = Enum.GetNames().Select(n => n.ToLowerInvariant()).ToArray(); + } + + internal static class Table + { + public const string Primary = "--table"; + public const string Description = "Only report requirements on these tables. Comma-separated or repeatable"; + } + + internal static class Privilege + { + public const string Primary = "--privilege"; + public const string Description = "Only report these privileges, such as Write or prvBulkDelete. Comma-separated or repeatable"; + } + + internal static class RunsAs + { + public const string Primary = "--runs-as"; + public const string Description = "Only report requirements of these identities: Caller, User, ApplicationUser, ImpersonatedCaller or System. Comma-separated or repeatable"; + } + + internal static class Basis + { + public const string Primary = "--basis"; + public const string Description = "Only report requirements with these bases: direct, execute-privilege, all-implementations, all-lookup-targets or filter-unknown. Comma-separated or repeatable"; + } + + internal static class NoRoles + { + public const string Primary = "--no-roles"; + public const string Description = "Only list what the code needs, without checking it against the roles in XrmMockup:Permissions:Principals and Users"; + } + + internal static class FailOnMissing + { + public const string Primary = "--fail-on-missing"; + public const string Description = "Exit with 1 when the roles don't grant a privilege the code needs, and with 2 when there are no roles to check against"; + } + + internal static class Strict + { + public const string Primary = "--strict"; + public const string Description = "Fail like --fail-on-missing, and also on unresolved operations, identities without roles and privileges that can't be checked"; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/AnalysisOptions.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/AnalysisOptions.cs new file mode 100644 index 00000000..80802e3d --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/AnalysisOptions.cs @@ -0,0 +1,187 @@ +using System.CommandLine; +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Output; + +namespace XrmMockup.PermissionAnalyzer.Tool.Commands; + +/// +/// The options of the command: what to analyze, the scope, the roles, when to fail and the output. +/// +internal sealed class AnalysisOptions +{ + private readonly Option _solution = new(CliOptions.Solution.Primary, CliOptions.Solution.Alias) { Description = CliOptions.Solution.Description }; + private readonly Option _metadata = new(CliOptions.Metadata.Primary, CliOptions.Metadata.Alias) { Description = CliOptions.Metadata.Description }; + private readonly Option _exclude = new(CliOptions.Exclude.Primary, CliOptions.Exclude.Alias) { Description = CliOptions.Exclude.Description }; + private readonly Option _pluginSolution = new(CliOptions.PluginSolution.Primary) { Description = CliOptions.PluginSolution.Description }; + private readonly Option _config = new(CliOptions.Config.Primary, CliOptions.Config.Alias) { Description = CliOptions.Config.Description }; + private readonly Option _output = new(CliOptions.Output.Primary, CliOptions.Output.Alias) { Description = CliOptions.Output.Description }; + private readonly Option _plugin = new(CliOptions.Plugin.Primary) { Description = CliOptions.Plugin.Description }; + private readonly Option _customApi = new(CliOptions.CustomApi.Primary) { Description = CliOptions.CustomApi.Description }; + private readonly Option _function = new(CliOptions.Function.Primary) { Description = CliOptions.Function.Description }; + private readonly Option _entry = new(CliOptions.Entry.Primary) { Description = CliOptions.Entry.Description }; + private readonly Option _operation = new(CliOptions.Operation.Primary) { Description = CliOptions.Operation.Description }; + private readonly Option _attributes = new(CliOptions.Attributes.Primary) { Description = CliOptions.Attributes.Description }; + private readonly Option _role = new(CliOptions.Role.Primary, CliOptions.Role.Alias) { Description = CliOptions.Role.Description }; + private readonly Option _callerRole = new(CliOptions.CallerRole.Primary) { Description = CliOptions.CallerRole.Description }; + private readonly Option _noRoles = new(CliOptions.NoRoles.Primary) { Description = CliOptions.NoRoles.Description }; + private readonly Option _failOnMissing = new(CliOptions.FailOnMissing.Primary) { Description = CliOptions.FailOnMissing.Description }; + private readonly Option _strict = new(CliOptions.Strict.Primary) { Description = CliOptions.Strict.Description }; + private readonly Option _table = new(CliOptions.Table.Primary) { Description = CliOptions.Table.Description }; + private readonly Option _privilege = new(CliOptions.Privilege.Primary) { Description = CliOptions.Privilege.Description }; + private readonly Option _runsAs = new(CliOptions.RunsAs.Primary) { Description = CliOptions.RunsAs.Description }; + private readonly Option _basis = new(CliOptions.Basis.Primary) { Description = CliOptions.Basis.Description }; + private readonly Option _format; + private readonly Option _detail; + + public AnalysisOptions() + { + _format = new Option(CliOptions.Format.Primary, CliOptions.Format.Alias) + { + Description = CliOptions.Format.Description, + HelpName = string.Join("|", CliOptions.Format.AllowedValues), + DefaultValueFactory = _ => CliOptions.Format.AllowedValues[0] + }; + _format.AcceptOnlyFromAmong(CliOptions.Format.AllowedValues); + _detail = new Option(CliOptions.Detail.Primary, CliOptions.Detail.Alias) + { + Description = CliOptions.Detail.Description, + HelpName = string.Join("|", CliOptions.Detail.AllowedValues), + DefaultValueFactory = _ => CliOptions.Detail.AllowedValues[0] + }; + _detail.AcceptOnlyFromAmong(CliOptions.Detail.AllowedValues); + } + + /// + /// Adds the options and their validation to , in the order the README lists them: input, + /// output, filters, scope, roles and failing. + /// + public void AddTo(Command command) + { + foreach (var option in new Option[] { _solution, _metadata, _exclude, _pluginSolution, _config, _format, _output, _detail, _table, _privilege, _runsAs, _basis, _plugin, _customApi, _function, _entry, _operation, _attributes, _role, _callerRole, _noRoles, _failOnMissing, _strict }) + { + command.Options.Add(option); + } + + command.Validators.Add(result => + { + var scopes = new Option[] { _plugin, _customApi, _function, _entry, _operation }.Count(o => result.GetResult(o) is not null); + if (scopes > 1) + { + result.AddError($"Use only one of {CliOptions.Plugin.Primary}, {CliOptions.CustomApi.Primary}, {CliOptions.Function.Primary}, {CliOptions.Entry.Primary} and {CliOptions.Operation.Primary}."); + } + + if (result.GetResult(_operation) is not null && OperationRequest.Parse(result.GetValue(_operation)!, null) is null) + { + result.AddError($"{CliOptions.Operation.Primary} takes a message and a table, such as \"Update account\"."); + } + if (result.GetResult(_attributes) is not null && result.GetResult(_operation) is null) + { + result.AddError($"{CliOptions.Attributes.Primary} needs {CliOptions.Operation.Primary}."); + } + if (result.GetValue(_noRoles) && new Option[] { _role, _callerRole, _failOnMissing, _strict }.FirstOrDefault(o => result.GetResult(o) is not null) is { } conflict) + { + result.AddError($"{CliOptions.NoRoles.Primary} can't be used with {conflict.Name}, which needs roles."); + } + + foreach (var name in Values(result.GetValue(_runsAs)).Where(n => ParseRunsAs(n) is null)) + { + result.AddError($"Unknown identity '{name}' in {CliOptions.RunsAs.Primary}. Use {string.Join(", ", Enum.GetNames())}."); + } + foreach (var name in Values(result.GetValue(_basis)).Where(n => BasisNames.Parse(n) is null)) + { + result.AddError($"Unknown basis '{name}' in {CliOptions.Basis.Primary}. Use {string.Join(", ", BasisNames.All)}."); + } + }); + } + + public AnalysisRequest Read(ParseResult parseResult) + { + var plugin = parseResult.GetValue(_plugin); + var customApi = parseResult.GetValue(_customApi); + var function = parseResult.GetValue(_function); + var entry = parseResult.GetValue(_entry) ?? []; + var operationText = parseResult.GetValue(_operation); + var attributes = parseResult.GetValue(_attributes); + var operation = operationText is null ? null : OperationRequest.Parse(operationText, attributes?.SelectMany(a => a.Split(',')).ToList()); + + var scope = plugin is not null ? EntryPointSelector.Plugin(plugin) + : customApi is not null ? EntryPointSelector.CustomApi(customApi) + : function is not null ? EntryPointSelector.Function(function) + : entry.Length > 0 ? EntryPointSelector.Methods(entry) + : operation is not null ? EntryPointSelector.Operation(operation.Message, operation.Table) + : null; + + return new AnalysisRequest( + parseResult.GetValue(_solution), + parseResult.GetValue(_metadata), + parseResult.GetValue(_exclude) ?? [], + parseResult.GetValue(_config), + Enum.Parse(parseResult.GetValue(_format)!, ignoreCase: true), + parseResult.GetValue(_output), + scope, + entry, + parseResult.GetValue(_role) ?? [], + parseResult.GetValue(_callerRole) ?? [], + operation, + parseResult.GetValue(_pluginSolution) ?? [], + parseResult.GetValue(_noRoles), + parseResult.GetValue(_failOnMissing) || parseResult.GetValue(_strict), + parseResult.GetValue(_strict), + new ReportOptions( + Enum.Parse(parseResult.GetValue(_detail)!, ignoreCase: true), + new ReportFilter( + Values(parseResult.GetValue(_table)), + Values(parseResult.GetValue(_privilege)), + Values(parseResult.GetValue(_runsAs)).Select(n => ParseRunsAs(n)!.Value).Distinct().ToList(), + Values(parseResult.GetValue(_basis)).Select(n => BasisNames.Parse(n)!.Value).Distinct().ToList()))); + } + + /// + /// The values of a repeatable option whose values may also be comma-separated. + /// + private static IReadOnlyList Values(string[]? values) => + (values ?? []).SelectMany(v => v.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + + /// + /// The identity by name, ignoring case; null for any other text, numbers included. + /// + private static RunsAsKind? ParseRunsAs(string name) => + Enum.GetValues().Cast().FirstOrDefault(k => string.Equals(k.ToString(), name, StringComparison.OrdinalIgnoreCase)); +} + +/// +/// The command line of one run. is also set by --strict. +/// +internal sealed record AnalysisRequest( + string? Solution, + string? Metadata, + IReadOnlyList Exclude, + string? Config, + ReportFormat Format, + string? Output, + EntryPointSelector? Scope, + IReadOnlyList EntryMethods, + IReadOnlyList Roles, + IReadOnlyList CallerRoles, + OperationRequest? Operation, + IReadOnlyList PluginSolutions, + bool NoRoles, + bool FailOnMissing, + bool Strict, + ReportOptions Report); + +/// +/// The user operation of --operation, with the columns of --attributes when given. +/// +internal sealed record OperationRequest(string Message, string Table, IReadOnlyList? Columns) +{ + /// + /// Reads "<message> <table>"; null when it isn't two words. + /// + public static OperationRequest? Parse(string text, IReadOnlyList? columns) + { + var parts = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + return parts.Length == 2 ? new OperationRequest(parts[0], parts[1], columns) : null; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/AnalysisRunner.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/AnalysisRunner.cs new file mode 100644 index 00000000..6be40d43 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/AnalysisRunner.cs @@ -0,0 +1,200 @@ +using System.Reflection; +using System.Text; +using Microsoft.Extensions.Logging; +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Metadata; +using XrmMockup.PermissionAnalyzer.Tool.Options; +using XrmMockup.PermissionAnalyzer.Tool.Output; +using XrmMockup.PermissionAnalyzer.Tool.Workspace; + +namespace XrmMockup.PermissionAnalyzer.Tool.Commands; + +/// +/// One run of the tool: analyze the code, check it against roles when there are any, and write the report. +/// +internal static class AnalysisRunner +{ + /// + /// Runs the analysis and writes the report. Exits with when + /// is set and the roles don't grant everything, and with + /// on errors. + /// + public static async Task RunAsync(AnalysisRequest request, CancellationToken cancellationToken) + { + using var loggerFactory = ToolLogging.Create(); + var logger = loggerFactory.CreateLogger(typeof(AnalysisRunner)); + + var version = Assembly.GetExecutingAssembly() + .GetCustomAttribute()?.InformationalVersion ?? "unknown"; + logger.LogInformation("XrmMockup Permission Analyzer v{Version}", version); + + try + { + var configuration = ConfigReader.Read(request.Config); + var settings = AnalysisSettings.Resolve(request.Solution, request.Metadata, configuration, request.Exclude, request.PluginSolutions); + + var roles = LoadRoles(settings.MetadataDirectory, logger); + // Role names are checked before the slow part, so a typo fails fast + var coverageOptions = request.NoRoles + ? null + : CoverageSetup.Create(roles, request.Roles, request.CallerRoles, configuration.Permissions, request.FailOnMissing); + + var root = Path.GetDirectoryName(settings.Target)!; + var metadataFile = settings.MetadataDirectory is { } fileDirectory ? LoadMetadataFile(fileDirectory, logger) : null; + var builder = new ManifestBuilder(root, RuleSetup.Create(configuration.Permissions), metadataFile?.Lookups); + if (settings.MetadataDirectory is { } metadataDirectory) AddMetadata(builder, metadataDirectory, metadataFile?.PluginSteps ?? [], logger); + builder.AddEntryMethods(configuration.Permissions.EntryPoints.Concat(request.EntryMethods).Distinct(StringComparer.Ordinal)); + if (request.Operation is { } operation) builder.AddOperation(operation.Message, operation.Table, operation.Columns); + + await XrmMockup.PermissionAnalyzer.Workspace.SourceLoader.AddAsync(builder, settings, loggerFactory, cancellationToken); + + var manifest = builder.Build(roles?.SelectMany(r => r.Privileges.Keys), request.Scope); + if (request.Scope is not null && manifest.EntryPoints.Count == 0) + { + throw new ToolException($"No entry point matches {request.Scope}"); + } + + CoverageReport? coverage = null; + if (coverageOptions is not null) + { + coverage = CoverageEvaluator.Evaluate(manifest, coverageOptions); + // Other entry points' settings are expected not to match when the analysis is narrowed to some + if (request.Scope is null) + { + foreach (var key in coverage.UnusedPrincipals) + { + logger.LogWarning("{Setting}:Principals:{Key} matches no analyzed assembly or function", PermissionsConfiguration.SectionPath, key); + } + foreach (var id in coverage.UnusedUsers) + { + logger.LogWarning("{Setting}:Users:{Id} is a user no analyzed operation runs as", PermissionsConfiguration.SectionPath, id); + } + } + if (coverageOptions.Roles is null && coverageOptions.CallerRoles is null && !coverage.UsesConfiguredRoles) + { + if (request.FailOnMissing) + { + throw new ToolException( + $"No roles to check against: no {CliOptions.Role.Primary} or {CliOptions.CallerRole.Primary}, and nothing analyzed matches " + + $"{PermissionsConfiguration.SectionPath}:Principals or {PermissionsConfiguration.SectionPath}:Users"); + } + // The settings name no identity of the code analyzed, so the run just lists what it needs + coverage = null; + } + } + + var writer = ManifestWriters.Create(request.Format, request.Report, root, version); + if (request.Output is null) + { + writer.Write(manifest, coverage, Console.Out); + } + else + { + var path = Path.GetFullPath(request.Output); + await using var file = new StreamWriter(path, append: false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + writer.Write(manifest, coverage, file); + logger.LogInformation("Wrote {Path}", path); + } + + return coverage is not null && request.FailOnMissing ? ExitCode(coverage, request.Strict, logger) : ExitCodes.Success; + } + catch (ToolException ex) + { + logger.LogError("{Message}", ex.Message); + return ExitCodes.Error; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Analysis failed"); + return ExitCodes.Error; + } + } + + /// + /// The exit code of a run with --fail-on-missing or --strict, with the reason it fails logged. + /// + private static int ExitCode(CoverageReport coverage, bool strict, ILogger logger) + { + var summary = coverage.Summary; + if (summary.Passed(strict)) + { + if (summary.Incomplete) + { + logger.LogWarning( + "The roles grant every privilege found, but the result is incomplete: {Unresolved} unresolved operations, " + + "{NotChecked} requirements without roles, {Unverifiable} privileges not tied to a table that the role metadata predates " + + "and {Truncated} entry points or methods whose analysis stopped at the call limit weren't checked. " + + "See 'Not checked' in the report, or pass {Strict} to fail on them", + summary.Unresolved, summary.NotChecked, summary.Unverifiable, summary.Truncated, CliOptions.Strict.Primary); + } + return ExitCodes.Success; + } + + if (summary.Missing > 0) + { + var privileges = coverage.Missing.Select(m => $"{m.Table} {m.Privilege}").Concat(coverage.MissingGlobal.Select(m => m.Privilege)).Distinct().ToList(); + logger.LogError("The roles don't grant {Count} privileges: {Privileges}. See the report", privileges.Count, string.Join(", ", privileges)); + } + else + { + logger.LogError( + "{Strict}: {Unresolved} unresolved, {NotChecked} not checked, {Unverifiable} unverifiable, {Truncated} stopped at the call limit", + CliOptions.Strict.Primary, summary.Unresolved, summary.NotChecked, summary.Unverifiable, summary.Truncated); + } + return ExitCodes.MissingPrivileges; + } + + /// + /// The lookup columns and plugin steps of the metadata files, which are read together because they're large. + /// + private static MetadataFileContents LoadMetadataFile(string metadataDirectory, ILogger logger) + { + var contents = MetadataFileLoader.Load(metadataDirectory); + logger.LogInformation("Loaded {Count} lookup columns from {Directory}", contents.Lookups.Count, metadataDirectory); + logger.LogInformation("Loaded {Count} plugin steps from {Directory}", contents.PluginSteps.Count, metadataDirectory); + return contents; + } + + /// + /// The plugin steps, and the workflows and the privilege catalog of the metadata folder. + /// + private static void AddMetadata(ManifestBuilder builder, string metadataDirectory, IReadOnlyList steps, ILogger logger) + { + builder.AddPluginSteps(steps); + + var workflows = WorkflowLoader.Load(metadataDirectory); + logger.LogInformation("Loaded {Count} workflows that run on a table from {Directory}", workflows.Count, metadataDirectory); + builder.AddWorkflows(workflows); + + if (PrivilegeCatalogLoader.Load(metadataDirectory) is var (privileges, customApis)) + { + logger.LogInformation("Loaded {Count} privileges and {CustomApis} custom APIs from {File}", privileges.Count, customApis.Count, PrivilegeCatalogLoader.FileName); + builder.AddPrivilegeCatalog(privileges, customApis); + } + else + { + logger.LogWarning("No {File} in {Directory}, so execute privileges set by name can't be looked up. Regenerate the metadata to add it", PrivilegeCatalogLoader.FileName, metadataDirectory); + } + } + + private static IReadOnlyList? LoadRoles(string? metadataDirectory, ILogger logger) + { + if (metadataDirectory is null) + { + logger.LogWarning("No metadata folder found, so security roles and plugin step registrations aren't used. Pass {Metadata} or set {Setting}:MetadataDirectory", CliOptions.Metadata.Primary, PermissionsConfiguration.SectionPath); + return null; + } + + var roles = RoleLoader.Load(metadataDirectory); + if (roles.Count == 0) + { + logger.LogWarning("No security roles in {Directory}", Path.Combine(metadataDirectory, RoleLoader.SecurityRolesFolder)); + return null; + } + + logger.LogInformation("Loaded {Count} security roles from {Directory}", roles.Count, metadataDirectory); + return roles; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/CoverageSetup.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/CoverageSetup.cs new file mode 100644 index 00000000..504e2468 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Commands/CoverageSetup.cs @@ -0,0 +1,112 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Options; + +namespace XrmMockup.PermissionAnalyzer.Tool.Commands; + +/// +/// Turns role names from the command line and configuration into the role sets to check against. +/// +internal static class CoverageSetup +{ + /// + /// The roles to check against: the role options, else the Principals and Users settings. + /// null to report without coverage, when there are none and isn't set, + /// or only settings and no roles to look them up in. Unknown role names are an error that suggests the closest + /// names. + /// + public static CoverageOptions? Create( + IReadOnlyList? roles, + IReadOnlyList roleNames, + IReadOnlyList callerRoleNames, + PermissionsConfiguration configuration, + bool requireRoles) + { + var given = roleNames.Count > 0 || callerRoleNames.Count > 0; + if (!given && configuration.Principals.Count == 0 && configuration.Users.Count == 0) + { + if (!requireRoles) return null; + throw new ToolException( + $"No roles to check against. Pass {CliOptions.Role.Primary}, or map the application user's roles in " + + $"{PermissionsConfiguration.SectionPath}:Principals or users' roles in {PermissionsConfiguration.SectionPath}:Users"); + } + + if (roles is null) + { + // Without metadata a plain run lists what the code needs; the missing metadata is already warned about + if (!given && !requireRoles) return null; + throw new ToolException($"No security roles loaded, so there is nothing to check against. Pass {CliOptions.Metadata.Primary} with a folder that has SecurityRoles"); + } + + var catalog = new RoleCatalog(roles); + return new CoverageOptions + { + Roles = roleNames.Count > 0 ? Resolve(catalog, roleNames, CliOptions.Role.Primary, CliOptions.Role.Primary) : null, + CallerRoles = callerRoleNames.Count > 0 ? Resolve(catalog, callerRoleNames, CliOptions.CallerRole.Primary, CliOptions.CallerRole.Primary) : null, + // --role replaces the principals, so a stale mapping among them doesn't stop the run + Principals = roleNames.Count > 0 ? new Dictionary(StringComparer.OrdinalIgnoreCase) : configuration.Principals + .OrderBy(p => p.Key, StringComparer.Ordinal) + .ToDictionary( + p => p.Key, + p => Resolve(catalog, p.Value.Roles, $"Principals: {p.Key}", $"{PermissionsConfiguration.SectionPath}:Principals:{p.Key}"), + StringComparer.OrdinalIgnoreCase), + Users = configuration.Users + .OrderBy(u => u.Key, StringComparer.Ordinal) + .ToDictionary( + u => UserId(u.Key), + u => Resolve(catalog, u.Value.Roles, $"Users: {u.Value.Name ?? u.Key}", $"{PermissionsConfiguration.SectionPath}:Users:{u.Key}"), + StringComparer.OrdinalIgnoreCase), + Suppress = configuration.Suppress.Select(Suppression).ToList(), + }; + } + + /// + /// A Users key as the id the analysis writes, so braces and case don't matter. + /// + internal static string UserId(string key) => + Guid.TryParse(key, out var id) + ? id.ToString("D") + : throw new ToolException($"{PermissionsConfiguration.SectionPath}:Users:{key} isn't a user id. Use the systemuserid, such as 6f1c2a9e-0000-4000-8000-000000000001"); + + private static RoleSet Resolve(RoleCatalog catalog, IReadOnlyList names, string origin, string setting) + { + if (names.Count == 0) throw new ToolException($"{setting} has no roles"); + + var found = new List(); + foreach (var name in names) + { + var matches = catalog.Find(name); + if (matches.Count == 0) + { + var suggestions = catalog.Suggest(name); + throw new ToolException( + $"Unknown security role '{name}' in {setting}." + + (suggestions.Count > 0 ? $" Did you mean {string.Join(", ", suggestions.Select(s => $"'{s}'"))}?" : "")); + } + found.AddRange(matches); + } + return RoleSet.Combine(found, origin); + } + + internal static Suppression Suppression(SuppressionConfiguration suppression, int index) + { + var setting = $"{PermissionsConfiguration.SectionPath}:Suppress:{index}"; + if (string.IsNullOrWhiteSpace(suppression.Table)) + { + // A privilege not tied to a table is suppressed by its name, such as prvActOnBehalfOfAnotherUser + if (suppression.Privilege is { } name && !string.IsNullOrWhiteSpace(name) && RuleSetup.ParsePrivilege(name) is null) + { + return new Suppression("", null, suppression.Reason, name.Trim()); + } + throw new ToolException($"{setting} has no Table. Leave it out only to suppress a privilege not tied to a table by its name, such as prvActOnBehalfOfAnotherUser"); + } + + Privilege? privilege = null; + if (suppression.Privilege is { } text) + { + privilege = RuleSetup.ParsePrivilege(text) + ?? throw new ToolException($"{setting} has an unknown Privilege '{text}'. Use one of {RuleSetup.PrivilegeNames}"); + } + return new Suppression(suppression.Table.Trim().ToLowerInvariant(), privilege, suppression.Reason); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/ExitCodes.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/ExitCodes.cs new file mode 100644 index 00000000..7f3ca1be --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/ExitCodes.cs @@ -0,0 +1,16 @@ +namespace XrmMockup.PermissionAnalyzer.Tool; + +internal static class ExitCodes +{ + public const int Success = 0; + + /// + /// With --fail-on-missing or --strict: the roles don't grant everything the code needs. + /// + public const int MissingPrivileges = 1; + + /// + /// Invalid arguments, missing files or a failed analysis. + /// + public const int Error = 2; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/IManifestWriter.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/IManifestWriter.cs new file mode 100644 index 00000000..72aeb3d8 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/IManifestWriter.cs @@ -0,0 +1,13 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// Writes a manifest in one output format. Output always uses '\n' line endings, so it's the same on every OS. +/// +internal interface IManifestWriter +{ + /// Role coverage to show with each requirement, or null for the plain manifest. + void Write(Manifest manifest, CoverageReport? coverage, TextWriter writer); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/JsonManifestWriter.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/JsonManifestWriter.cs new file mode 100644 index 00000000..f63b2f11 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/JsonManifestWriter.cs @@ -0,0 +1,201 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The manifest as JSON, for diffing in CI and for other tools. Privileges and identities keep their names +/// (AppendTo, ApplicationUser); a basis and a coverage status are written in kebab case +/// (all-implementations, not-checked). A privilege not tied to a table is a requirement without a +/// table, with the privilege name as its privilege. Coverage properties are only written with coverage. A filter +/// leaves out the requirements and unresolved operations it doesn't match, the entry points and methods left without +/// any and the missing privileges no matching requirement is missing; the result counts stay those of the whole +/// analysis. +/// +internal sealed class JsonManifestWriter(ReportFilter? filter = null) : IManifestWriter +{ + private readonly ReportFilter _filter = filter ?? ReportFilter.None; + + private static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + WriteIndented = true, + NewLine = "\n", + Converters = + { + new JsonStringEnumConverter(), + new JsonStringEnumConverter(), + new JsonStringEnumConverter(), + new JsonStringEnumConverter(), + new JsonStringEnumConverter(JsonNamingPolicy.KebabCaseLower), + new JsonStringEnumConverter(JsonNamingPolicy.KebabCaseLower), + }, + }; + + public void Write(Manifest manifest, CoverageReport? coverage, TextWriter writer) + { + (IReadOnlyList Missing, IReadOnlyList MissingGlobal)? missing = coverage is null ? null : _filter.Missing(manifest, coverage); + var document = new ManifestDocument( + manifest.EntryPoints.Where(e => _filter.IsEmpty || _filter.Matches(e)).Select(e => new EntryPointDocument( + e.Id, + e.Kind, + e.Type, + e.Assembly, + e.Trigger is { } trigger ? new TriggerDocument(trigger.Message, trigger.Table, trigger.Stage, trigger.Binding, trigger.FilteredAttributes) : null, + e.ImpersonatingUserId, + Declaration(e.Declaration), + Requirements(e, coverage?.For(e)), + Unresolved(e.Unresolved), + Assumptions(e.Assumptions), + e.Triggers.Count > 0 ? e.Triggers : null, + Roles(coverage?.For(e)))) + .ToList(), + manifest.Unreached.Where(m => _filter.IsEmpty || _filter.Matches(m)).Select(m => new MethodDocument( + m.Id, + Declaration(m.Declaration), + Requirements(m, coverage?.For(m)), + Unresolved(m.Unresolved), + Assumptions(m.Assumptions), + Roles(coverage?.For(m)))) + .ToList(), + manifest.NotRoleGoverned, + missing?.Missing.Select(m => Missing(m.Table, m.Privilege.ToString(), m.RunsAs, m.Roles, m.In)) + .Concat(missing.Value.MissingGlobal.Select(m => Missing(null, m.Privilege, m.RunsAs, m.Roles, m.In))) + .ToList(), + coverage?.Summary is { } summary + ? new ResultDocument(summary.Granted, summary.NotGoverned, summary.Missing, summary.Suppressed, summary.NotChecked, summary.System, summary.Unresolved, summary.UnresolvedNoRule, summary.UnresolvedCustomApi, summary.UnresolvedWorkflow, summary.Unverifiable, summary.Truncated, summary.Incomplete) + : null); + + writer.Write(JsonSerializer.Serialize(document, Options)); + writer.Write('\n'); + } + + private IReadOnlyList Requirements(IManifestSection section, SectionCoverage? coverage) => + PrivilegeNeed.Of(section, coverage, _filter).Select(n => Requirement(n.Table, n.PrivilegeName, n.RunsAs, n.Basis, n.Sources, n.Coverage)).ToList(); + + private static RequirementDocument Requirement(string? table, string privilege, RunsAs runsAs, RequirementBasis basis, IReadOnlyList sources, RequirementCoverage? coverage) => + new(table, privilege, runsAs.Kind, runsAs.UserId, Assumed(runsAs), basis, sources.Select(Source).ToList(), Coverage(coverage)); + + /// + /// true for an assumed identity, else left out of the JSON. + /// + private static bool? Assumed(RunsAs runsAs) => runsAs.Assumed ? true : null; + + private static MissingDocument Missing(string? table, string privilege, RunsAs runsAs, RoleSet roles, IReadOnlyList @in) => + new(table, privilege, runsAs.Kind, runsAs.UserId, roles.Names, roles.Origin, @in); + + private static CoverageDocument? Coverage(RequirementCoverage? result) => + result is null ? null : new CoverageDocument(result.Status, result.Depth, result.Reason); + + private static IReadOnlyList? Roles(SectionCoverage? coverage) => + coverage?.Identities.Select(i => new IdentityRolesDocument(i.RunsAs.Kind, i.RunsAs.UserId, i.Roles?.Names, i.Roles?.Origin, i.Note)).ToList(); + + private IReadOnlyList Unresolved(IEnumerable unresolved) => + unresolved.Where(_filter.Matches).Select(u => new UnresolvedDocument( + u.Operation, + u.Privileges, + u.Reason, + u.RunsAs.Kind, + u.RunsAs.UserId, + Assumed(u.RunsAs), + Source(u.Source))) + .ToList(); + + private static IReadOnlyList Assumptions(IEnumerable assumptions) => + assumptions.Select(a => new AssumptionDocument(a.Reason, Source(a.Source))).ToList(); + + private static SourceDocument Source(RequirementSource source) => + new(source.Location.File, source.Location.Line, source.Location.Column, source.Path); + + private static LocationDocument? Declaration(SourceLocation? location) => + location is null ? null : new LocationDocument(location.File, location.Line, location.Column); + + private sealed record ManifestDocument( + IReadOnlyList EntryPoints, + IReadOnlyList Unreached, + IReadOnlyList? NotRoleGoverned, + IReadOnlyList? Missing, + ResultDocument? Result); + + private sealed record MissingDocument( + string? Table, + string Privilege, + RunsAsKind RunsAs, + string? UserId, + IReadOnlyList Roles, + string Origin, + IReadOnlyList In); + + private sealed record EntryPointDocument( + string Id, + EntryPointKind Kind, + string Type, + string? Assembly, + TriggerDocument? Trigger, + string? ImpersonatingUserId, + LocationDocument? Declaration, + IReadOnlyList Requirements, + IReadOnlyList Unresolved, + IReadOnlyList Assumptions, + IReadOnlyList? Triggers, + IReadOnlyList? Roles); + + private sealed record TriggerDocument(string? Message, string? Table, string? Stage, string? Binding, IReadOnlyList? FilteredAttributes); + + private sealed record MethodDocument( + string Id, + LocationDocument? Declaration, + IReadOnlyList Requirements, + IReadOnlyList Unresolved, + IReadOnlyList Assumptions, + IReadOnlyList? Roles); + + private sealed record RequirementDocument( + string? Table, + string Privilege, + RunsAsKind RunsAs, + string? UserId, + bool? Assumed, + RequirementBasis Basis, + IReadOnlyList Sources, + CoverageDocument? Coverage); + + private sealed record CoverageDocument(CoverageStatus Status, PrivilegeDepth? Depth, string? Reason); + + private sealed record IdentityRolesDocument(RunsAsKind RunsAs, string? UserId, IReadOnlyList? Roles, string? Origin, string? Note); + + private sealed record ResultDocument( + int Granted, + int NotGoverned, + int Missing, + int Suppressed, + int NotChecked, + int System, + int Unresolved, + int UnresolvedNoRule, + int UnresolvedCustomApi, + int UnresolvedWorkflow, + int Unverifiable, + int Truncated, + bool Incomplete); + + private sealed record UnresolvedDocument( + string Operation, + IReadOnlyList Privileges, + string Reason, + RunsAsKind RunsAs, + string? UserId, + bool? Assumed, + SourceDocument Source); + + private sealed record AssumptionDocument(string Reason, SourceDocument Source); + + private sealed record SourceDocument(string File, int Line, int Column, IReadOnlyList Path); + + private sealed record LocationDocument(string File, int Line, int Column); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ManifestWriters.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ManifestWriters.cs new file mode 100644 index 00000000..afe6d75b --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ManifestWriters.cs @@ -0,0 +1,17 @@ +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The writer of each output format. +/// +internal static class ManifestWriters +{ + /// The analysis root, which SARIF paths are made relative to the repository from. + /// The tool version SARIF output names. + public static IManifestWriter Create(ReportFormat format, ReportOptions report, string root, string? version) => format switch + { + ReportFormat.Json => new JsonManifestWriter(report.Filter), + ReportFormat.Markdown => new MarkdownManifestWriter(report.Filter), + ReportFormat.Sarif => new SarifManifestWriter(report.Filter, SarifManifestWriter.RepositoryPath(root), version), + _ => new TextManifestWriter(report), + }; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/MarkdownManifestWriter.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/MarkdownManifestWriter.cs new file mode 100644 index 00000000..b13c2742 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/MarkdownManifestWriter.cs @@ -0,0 +1,114 @@ +using System.Text.RegularExpressions; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The report as GitHub-flavored Markdown, for a pull request comment or a job summary: the result, the privileges to +/// change per role set () as a table, with the entry points that need them and the +/// unresolved operations folded away, then the counts. A filter narrows the changes and the unresolved operations; the +/// counts and the result stay those of the whole analysis. There are no detail levels: the folded sections hold +/// what adds to the text report. +/// +internal sealed partial class MarkdownManifestWriter(ReportFilter? filter = null) : IManifestWriter +{ + private readonly ReportFilter _filter = filter ?? ReportFilter.None; + + public void Write(Manifest manifest, CoverageReport? coverage, TextWriter writer) + { + if (coverage is null) + { + writer.Write("### Required privileges\n\n"); + } + else + { + // A privilege once per identity and roles, as the text report lists them, not once per entry point + var missing = coverage.Missing.Count + coverage.MissingGlobal.Count; + writer.Write(missing > 0 ? $"### ✘ {ReportText.Count(missing, "missing privilege")}\n\n" : "### ✔ No missing privileges\n\n"); + writer.Write(ReportText.Result(coverage.Summary) + "\n\n"); + if (ReportText.NotChecked(coverage.Summary) is { } notChecked) writer.Write($"> [!WARNING]\n> {Text(notChecked)}\n\n"); + } + + foreach (var block in RoleChanges.Of(manifest, coverage, _filter)) + { + writer.Write($"#### {Text(block.Heading)}\n\n"); + Tables(block.Tables, writer); + writer.Write("
By entry point\n\n"); + foreach (var group in block.EntryPoints) + { + foreach (var id in group.Ids) + { + writer.Write($"- {Code(id)}\n"); + } + writer.Write('\n'); + Tables(group.Tables, writer); + } + writer.Write("
\n\n"); + } + + var unresolved = UnresolvedSites.Of(manifest, _filter); + if (unresolved.Count > 0) + { + writer.Write($"
{ReportText.Count(unresolved.Count, "unresolved operation")}\n\n"); + writer.Write("| Operation | Runs as | Reason | Source |\n| --- | --- | --- | --- |\n"); + foreach (var site in unresolved) + { + var operation = site.Operation; + writer.Write($"| {Code(operation.Operation)}{UnresolvedSites.PrivilegeSuffix(operation)} | {operation.RunsAs} | {Text(operation.Reason)} | {Code(operation.Source.Location.ToString())} |\n"); + } + writer.Write("\n
\n\n"); + } + + writer.Write(ReportText.Totals(manifest) + "\n"); + if (!_filter.IsEmpty) writer.Write($"\n{Text(ReportText.Filtered(manifest, _filter))}\n"); + } + + /// + /// A row per table, privileges not tied to a table last. + /// + private static void Tables(IReadOnlyList tables, TextWriter writer) + { + writer.Write("| Table | Privileges |\n| --- | --- |\n"); + foreach (var table in tables) + { + var privileges = table.IsGlobal ? "not tied to a table" : string.Join(", ", table.Privileges); + writer.Write($"| {Code(table.Table)} | {privileges} |\n"); + } + writer.Write('\n'); + } + + /// + /// Text with the characters Markdown would format escaped, so a role or reason shows as written, also in a table. + /// + internal static string Text(string text) => MarkdownCharacters().Replace(OneLine(text), @"\$0"); + + /// + /// A code span that also works in a table cell, fenced with one backtick more than the longest run in the text. + /// + internal static string Code(string text) + { + var escaped = OneLine(text).Replace("|", @"\|"); + var longest = Backticks().Matches(escaped).Select(m => m.Length).DefaultIfEmpty(0).Max(); + if (longest == 0) return $"`{escaped}`"; + + // The spaces keep a backtick at either end apart from the fence; Markdown strips them + var fence = new string('`', longest + 1); + return $"{fence} {escaped} {fence}"; + } + + /// + /// with line breaks and other control characters as spaces, so it can't end a table row or + /// start a block of its own. + /// + private static string OneLine(string text) => ControlCharacters().Replace(text, " "); + + [GeneratedRegex(@"[\\`*_{}\[\]<>#|~]")] + private static partial Regex MarkdownCharacters(); + + [GeneratedRegex(@"`+")] + private static partial Regex Backticks(); + + [GeneratedRegex(@"\p{Cc}")] + private static partial Regex ControlCharacters(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/PrivilegeNeed.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/PrivilegeNeed.cs new file mode 100644 index 00000000..b3c44257 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/PrivilegeNeed.cs @@ -0,0 +1,40 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// A requirement of an entry point or unreached method as the reports list it: a privilege on a table, or a privilege +/// not tied to a table, with what the roles make of it. +/// +/// The table, or the name of a privilege not tied to a table. +/// The privilege on ; null for a privilege not tied to a table. +internal sealed record PrivilegeNeed( + string Name, + Privilege? TablePrivilege, + RunsAs RunsAs, + RequirementBasis Basis, + IReadOnlyList Sources, + RequirementCoverage? Coverage) +{ + public bool IsGlobal => TablePrivilege is null; + + /// + /// The table; null for a privilege not tied to a table. + /// + public string? Table => IsGlobal ? null : Name; + + /// + /// The privilege, such as Write or prvMerge. + /// + public string PrivilegeName => TablePrivilege?.ToString() ?? Name; + + /// + /// The requirements of that matches, those on tables first. + /// + public static IEnumerable Of(IManifestSection section, SectionCoverage? coverage, ReportFilter filter) => + section.Requirements.Where(filter.Matches) + .Select(r => new PrivilegeNeed(r.Table, r.Privilege, r.RunsAs, r.Basis, r.Sources, coverage?.For(r))) + .Concat(section.GlobalRequirements.Where(filter.Matches) + .Select(r => new PrivilegeNeed(r.Privilege, null, r.RunsAs, r.Basis, r.Sources, coverage?.For(r)))); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ReportOptions.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ReportOptions.cs new file mode 100644 index 00000000..230c7e00 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ReportOptions.cs @@ -0,0 +1,151 @@ +using System.Text.Json; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The format of the report, by --format. +/// +internal enum ReportFormat +{ + Text, + Json, + Markdown, + Sarif, +} + +/// +/// How much of the text report to show. +/// +internal enum Detail +{ + /// + /// Only what to change: per role set, the privileges it lacks, a line per table. No entry points or sources. + /// The default. + /// + Minimal, + + /// + /// Also, per role set, the entry points and methods that need its privileges, those that need the same ones + /// listed together. + /// + Compact, + + /// + /// What needs attention: requirements the roles don't grant or that weren't checked, and unresolved operations. + /// Without roles, that is every requirement. Sources are shown without their call paths. + /// + Normal, + + /// + /// Also the requirements the roles grant, assumptions, the steps an entry point fires and the privileges per table. + /// + Detailed, + + /// + /// Everything, with every source and its call path. + /// + Full, +} + +/// +/// What the report shows. Both apply after analysis, so they never change what is computed, the counts or the exit +/// code. JSON ignores , so it is always complete, but is narrowed by . +/// +internal sealed record ReportOptions(Detail Detail = Detail.Minimal, ReportFilter? Filter = null) +{ + public static ReportOptions Default { get; } = new(); + + public ReportFilter Filter { get; init; } = Filter ?? ReportFilter.None; +} + +/// +/// Narrows the report to some tables, privileges, identities or bases. Each list matches any of its values, +/// ignoring case, and an empty list matches everything. A privilege not tied to a table has no table, so a table +/// filter leaves it out; an unresolved operation has no known table or basis, so only the identity and privilege +/// filters apply to it. +/// +internal sealed class ReportFilter( + IReadOnlyCollection tables, + IReadOnlyCollection privileges, + IReadOnlyCollection identities, + IReadOnlyCollection bases) +{ + public static ReportFilter None { get; } = new([], [], [], []); + + public bool IsEmpty => tables.Count + privileges.Count + identities.Count + bases.Count == 0; + + public bool Matches(Requirement requirement) => + Has(tables, requirement.Table) && Has(privileges, requirement.Privilege.ToString()) && Identity(requirement.RunsAs) && Basis(requirement.Basis); + + public bool MatchesTable(string table) => Has(tables, table); + + public bool Matches(GlobalRequirement requirement) => + tables.Count == 0 && Has(privileges, requirement.Privilege) && Identity(requirement.RunsAs) && Basis(requirement.Basis); + + public bool Matches(UnresolvedOperation operation) => + Identity(operation.RunsAs) && (privileges.Count == 0 || operation.Privileges.Count == 0 || operation.Privileges.Any(p => Has(privileges, p.ToString()))); + + /// + /// The section has a requirement or unresolved operation the filter matches. + /// + public bool Matches(IManifestSection section) => + section.Requirements.Any(Matches) || section.GlobalRequirements.Any(Matches) || section.Unresolved.Any(Matches); + + /// + /// The missing privileges of that some requirement the filter matches is missing, + /// so that a basis filter, which a merged missing privilege doesn't have, narrows them too. + /// + public (IReadOnlyList Missing, IReadOnlyList MissingGlobal) Missing(Manifest manifest, CoverageReport coverage) + { + if (IsEmpty) return (coverage.Missing, coverage.MissingGlobal); + + var missing = manifest.Sections + .SelectMany(s => PrivilegeNeed.Of(s, coverage.For(s), this)) + .Where(n => n.Coverage!.Status == CoverageStatus.Missing) + .Select(n => (n.Name, n.TablePrivilege, RunsAs: n.RunsAs with { Assumed = false })) + .ToHashSet(); + return ( + coverage.Missing.Where(m => missing.Contains((m.Table, m.Privilege, m.RunsAs))).ToList(), + coverage.MissingGlobal.Where(m => missing.Contains((m.Privilege, null, m.RunsAs))).ToList()); + } + + /// + /// The filter as its options, such as --table account, contact; --basis direct. + /// + public override string ToString() + { + var parts = new List(); + void Add(string option, IEnumerable values) + { + var list = values.Select(v => v is RequirementBasis basis ? BasisNames.Of(basis) : v!.ToString()!).ToList(); + if (list.Count > 0) parts.Add($"{option} {string.Join(", ", list)}"); + } + Add(CliOptions.Table.Primary, tables); + Add(CliOptions.Privilege.Primary, privileges); + Add(CliOptions.RunsAs.Primary, identities); + Add(CliOptions.Basis.Primary, bases); + return string.Join("; ", parts); + } + + private bool Identity(RunsAs runsAs) => identities.Count == 0 || identities.Contains(runsAs.Kind); + + private bool Basis(RequirementBasis basis) => bases.Count == 0 || bases.Contains(basis); + + private static bool Has(IReadOnlyCollection values, string value) => + values.Count == 0 || values.Contains(value, StringComparer.OrdinalIgnoreCase); +} + +/// +/// A basis in kebab case, as the output and --basis write it: all-implementations. +/// +internal static class BasisNames +{ + public static string Of(RequirementBasis basis) => JsonNamingPolicy.KebabCaseLower.ConvertName(basis.ToString()); + + public static IReadOnlyList All { get; } = Enum.GetValues().Select(Of).ToList(); + + public static RequirementBasis? Parse(string name) => + Enum.GetValues().Cast().FirstOrDefault(b => string.Equals(Of(b!.Value), name, StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ReportText.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ReportText.cs new file mode 100644 index 00000000..dae5c0a5 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/ReportText.cs @@ -0,0 +1,88 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The lines the text and Markdown reports share: the counts, what a filter matches and the result. +/// +internal static class ReportText +{ + /// + /// What was analyzed. A requirement is counted once per entry point or method that needs it; the tables merge + /// them. The counts are of the whole analysis, whatever is shown. + /// + public static string Totals(Manifest manifest) + { + var requirements = manifest.AllRequirements.ToList(); + var globalRequirements = manifest.AllGlobalRequirements.ToList(); + var unresolvedCount = manifest.EntryPoints.Sum(e => e.Unresolved.Count) + manifest.Unreached.Sum(m => m.Unresolved.Count); + var tables = requirements.Select(r => r.Table).Distinct(StringComparer.Ordinal).Count(); + var tablePrivileges = requirements.Select(r => (r.Table, r.Privilege)).Distinct().Count(); + var globalPrivileges = globalRequirements.Select(r => r.Privilege).Distinct(StringComparer.Ordinal).Count(); + return + $"{Count(manifest.EntryPoints.Count, "entry point")}, {Count(manifest.Unreached.Count, "unreached method")}, " + + $"{Count(tables, "table")}, {Count(tablePrivileges, "table privilege")} " + + $"({Count(requirements.Count, "requirement")} counted per entry point and method), " + + (globalPrivileges > 0 ? $"{Count(globalPrivileges, "privilege")} not tied to a table, " : "") + + $"{unresolvedCount} unresolved"; + } + + /// + /// What the filter matches, of every requirement. + /// + public static string Filtered(Manifest manifest, ReportFilter filter) + { + var all = manifest.AllRequirements.Count() + manifest.AllGlobalRequirements.Count(); + var matching = manifest.AllRequirements.Count(filter.Matches) + manifest.AllGlobalRequirements.Count(filter.Matches); + return $"Filtered by {filter}: {matching} of {Count(all, "requirement")} match"; + } + + /// + /// What became of each requirement. + /// + public static string Result(CoverageSummary summary) + { + var parts = new List { $"{summary.Granted} granted", $"{summary.Missing} missing" }; + void Add(int count, string text) + { + if (count > 0) parts.Add($"{count} {text}"); + } + Add(summary.NotGoverned, "not governed"); + Add(summary.Suppressed, "suppressed"); + Add(summary.System, "as SYSTEM"); + return "Result: " + string.Join(", ", parts); + } + + /// + /// What the result doesn't cover, so a pass isn't read as proof that the roles are enough; null when + /// everything was checked. + /// + public static string? NotChecked(CoverageSummary summary) + { + var parts = new List(); + if (summary.NotChecked > 0) parts.Add($"{Count(summary.NotChecked, "requirement")} without roles"); + if (summary.Unresolved > 0) + { + var details = new List(); + if (summary.UnresolvedNoRule > 0) details.Add($"{Count(summary.UnresolvedNoRule, "request")} without a rule"); + if (summary.UnresolvedCustomApi > 0) details.Add($"{Count(summary.UnresolvedCustomApi, "custom API call")}"); + if (summary.UnresolvedWorkflow > 0) details.Add($"{Count(summary.UnresolvedWorkflow, "workflow")} whose steps aren't analyzed"); + var other = summary.Unresolved - summary.UnresolvedNoRule - summary.UnresolvedCustomApi - summary.UnresolvedWorkflow; + if (other > 0) details.Add($"{other} with an unknown table or request"); + parts.Add($"{Count(summary.Unresolved, "unresolved operation")} ({string.Join(", ", details)})"); + } + if (summary.Unverifiable > 0) + { + parts.Add($"{Count(summary.Unverifiable, "privilege")} not tied to a table (the role metadata predates them; regenerate it)"); + } + if (summary.Truncated > 0) + { + var sections = summary.Truncated == 1 ? "entry point or method" : "entry points or methods"; + parts.Add($"{summary.Truncated} {sections} whose analysis stopped at the call limit"); + } + return parts.Count > 0 ? "Not checked: " + string.Join(", ", parts) : null; + } + + public static string Count(int count, string noun) => $"{count} {noun}{(count == 1 ? "" : "s")}"; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/RoleChanges.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/RoleChanges.cs new file mode 100644 index 00000000..6a5675d5 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/RoleChanges.cs @@ -0,0 +1,125 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The privileges to change, in a block per set of roles: what the roles lack, merged over every entry point and +/// identity they serve, since a role is changed once whatever needs it. Requirements that can't be checked get a block +/// per identity, and without roles, a block is every requirement of an identity that needs a role. Each block also +/// has the entry points and methods that need its privileges, those that need the same ones together. The text +/// report shows the blocks below , and Markdown always does. +/// +internal static class RoleChanges +{ + public static IReadOnlyList Of(Manifest manifest, CoverageReport? coverage, ReportFilter filter) + { + var blocks = new Dictionary<(BlockKind Kind, string Key), Block>(); + // Entry points before unreached methods, each in manifest order + var position = manifest.Sections.Select((s, i) => (s.Id, i)).ToDictionary(s => s.Id, s => s.i, StringComparer.Ordinal); + foreach (var section in manifest.Sections) + { + var sectionCoverage = coverage?.For(section); + foreach (var privilegeNeed in PrivilegeNeed.Of(section, sectionCoverage, filter)) + { + var identity = privilegeNeed.RunsAs with { Assumed = false }; + if (BlockOf(identity, privilegeNeed.Coverage, sectionCoverage) is not { } key) continue; + var need = new Need(privilegeNeed.Name, privilegeNeed.TablePrivilege); + if (!blocks.TryGetValue(key, out var block)) blocks.Add(key, block = new Block()); + block.Identities.Add(identity); + block.Needs.Add(need); + if (!block.Sections.TryGetValue(section.Id, out var sectionNeeds)) block.Sections.Add(section.Id, sectionNeeds = []); + sectionNeeds.Add(need); + } + } + + return blocks.OrderBy(b => b.Key.Kind).ThenBy(b => b.Key.Key, StringComparer.Ordinal).Select(b => + { + var ((kind, key), block) = (b.Key, b.Value); + var identities = string.Join(", ", block.Identities.Order()); + var heading = kind switch + { + BlockKind.Missing when coverage is null => $"{key} needs", + BlockKind.Missing => $"Missing from {key}, for {identities}", + BlockKind.NotChecked => key, + _ => $"Can't be checked against {key}, for {identities} (the role metadata predates privileges not tied to a table; regenerate it)", + }; + // Sections that need exactly the same privileges are one group, placed where its first section is + var groups = block.Sections + .GroupBy(s => string.Join("\n", s.Value.Select(n => $"{n.Name} {n.Privilege?.ToString() ?? ""}").Order(StringComparer.Ordinal)), StringComparer.Ordinal) + .Select(g => new EntryPointChange(g.Select(s => s.Key).OrderBy(id => position[id]).ToList(), Tables(g.First().Value))) + .OrderBy(g => position[g.Ids[0]]) + .ToList(); + return new RoleChange(heading, kind == BlockKind.Missing && coverage is not null, Tables(block.Needs), groups); + }).ToList(); + } + + /// + /// A line per table, so a role can be changed one table at a time, with the privileges in the order the role + /// editor has them; privileges not tied to a table come last. + /// + private static IReadOnlyList Tables(IEnumerable needs) => needs + .GroupBy(n => n.Name, StringComparer.Ordinal) + .Select(t => new TableChange(t.Key, t.Where(n => n.Privilege is not null).Select(n => n.Privilege!.Value).Distinct().Order().Select(p => p.ToString()).ToList(), t.Any(n => n.Privilege is null))) + .OrderBy(t => t.IsGlobal) + .ThenBy(t => t.Table, StringComparer.Ordinal) + .ToList(); + + /// + /// The block a requirement goes in, by kind and key: missing from a role set, or without roles needed by an + /// identity, not checked for an identity, or unverifiable against a role set; null when it needs no change. + /// + private static (BlockKind Kind, string Key)? BlockOf(RunsAs identity, RequirementCoverage? result, SectionCoverage? coverage) + { + var roles = coverage?.Identities.FirstOrDefault(i => i.RunsAs == identity); + return result?.Status switch + { + null => identity.Kind == RunsAsKind.System ? null : (BlockKind.Missing, identity.ToString()), + CoverageStatus.Missing => (BlockKind.Missing, roles!.Roles!.ToString()), + CoverageStatus.NotChecked => (BlockKind.NotChecked, $"{identity} needs ({roles?.Note ?? "not checked"})"), + CoverageStatus.Unverifiable => (BlockKind.Unverifiable, roles!.Roles!.ToString()), + _ => null, + }; + } + + /// + /// The kinds of block, in the order they are shown. + /// + private enum BlockKind + { + Missing, + NotChecked, + Unverifiable, + } + + /// + /// What one block lacks: in all, and per entry point or unreached method. + /// + private sealed class Block + { + public HashSet Identities { get; } = []; + + public HashSet Needs { get; } = []; + + public Dictionary> Sections { get; } = new(StringComparer.Ordinal); + } + + /// + /// A privilege on a table, or a privilege not tied to a table by its name, with no . + /// + private sealed record Need(string Name, Privilege? Privilege); +} + +/// What the block is, such as Missing from Salesperson (--role), for Caller. +/// The roles lack the privileges, rather than they weren't checked or are needed without roles. +/// Every table of the block. +/// The entry points and unreached methods that need the privileges, grouped. +internal sealed record RoleChange(string Heading, bool Missing, IReadOnlyList Tables, IReadOnlyList EntryPoints); + +/// The table, or the name of a privilege not tied to a table. +/// In role editor order; empty for a privilege not tied to a table. +/// is a privilege not tied to a table. +internal sealed record TableChange(string Table, IReadOnlyList Privileges, bool IsGlobal); + +/// Entry points and unreached methods that need exactly . +internal sealed record EntryPointChange(IReadOnlyList Ids, IReadOnlyList Tables); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/SarifManifestWriter.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/SarifManifestWriter.cs new file mode 100644 index 00000000..25ae0722 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/SarifManifestWriter.cs @@ -0,0 +1,254 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The findings as SARIF 2.1.0, for GitHub code scanning and other tools that annotate code: a result per call site +/// that needs a privilege the roles lack (an error; suppressed ones carry their reason as a suppression), can't be +/// checked (a note), or whose table or request isn't known (a warning, not for SYSTEM). The entry points and methods +/// that reach a call site are its related locations. Without roles, only unresolved operations are findings. A filter +/// leaves out what it doesn't match. +/// +/// The analysis root relative to %SRCROOT%, the repository root, such as +/// src/Functions/, so that locations, which are relative to the analysis root, are relative to the +/// repository too. No absolute path is written, so the output is the same on every machine. +/// The tool version, or null to leave it out. +internal sealed class SarifManifestWriter(ReportFilter? filter = null, string sourceRoot = "", string? version = null) : IManifestWriter +{ + private const string SourceRootId = "%SRCROOT%"; + + /// + /// The entry points named in a message; the related locations have all of them. + /// + private const int NamedSections = 3; + + private readonly ReportFilter _filter = filter ?? ReportFilter.None; + + // The rules by their index in Rules + private const int MissingRule = 0, UnresolvedRule = 1, NotCheckedRule = 2, UnverifiableRule = 3; + + private static readonly IReadOnlyList Rules = + [ + new("missing-privilege", "MissingPrivilege", + new("A security role lacks a privilege the code needs"), + new("None of the roles the identity is checked against grants a privilege an operation needs, so the operation fails with an access error. Add the privilege to one of the roles, or suppress it in XrmMockup:Permissions:Suppress with a reason."), + new("error")), + new("unresolved-operation", "UnresolvedOperation", + new("The privilege an operation needs isn't known"), + new("The table of the operation can't be determined statically, or the request has no rule, so the privilege it needs isn't checked. Name the table with a constant or an early-bound type, or add a rule in XrmMockup:Permissions:Rules."), + new("warning")), + new("not-checked", "NotChecked", + new("A privilege isn't checked, as no roles are known for the identity"), + new("The identity the operation runs as has no roles to check against. Map it to roles with --role, --caller-role, XrmMockup:Permissions:Principals or XrmMockup:Permissions:Users."), + new("note")), + new("unverifiable", "Unverifiable", + new("A privilege not tied to a table can't be checked"), + new("The role metadata was generated before privileges not tied to a table were downloaded. Regenerate it."), + new("note")), + ]; + + private static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + WriteIndented = true, + NewLine = "\n", + }; + + public void Write(Manifest manifest, CoverageReport? coverage, TextWriter writer) + { + var results = Findings(manifest, coverage).Concat(Unresolved(manifest)) + .OrderBy(r => r.RuleIndex) + .ThenBy(r => r.Locations?[0].PhysicalLocation.ArtifactLocation.Uri, StringComparer.Ordinal) + .ThenBy(r => r.Locations?[0].PhysicalLocation.Region?.StartLine) + .ThenBy(r => r.Locations?[0].PhysicalLocation.Region?.StartColumn) + .ThenBy(r => r.Message.Text, StringComparer.Ordinal) + .ToList(); + var document = new SarifDocument( + "https://json.schemastore.org/sarif-2.1.0.json", + "2.1.0", + [new RunDocument(new ToolDocument(new DriverDocument("xrmmockup-permissions", version, "https://github.com/delegateas/XrmMockup", Rules)), results)]); + + writer.Write(JsonSerializer.Serialize(document, Options)); + writer.Write('\n'); + } + + /// + /// The analysis root relative to the repository it is in, the nearest directory up with a .git folder or + /// file, with forward slashes and a trailing one; empty at the repository root or outside a repository. + /// + public static string RepositoryPath(string root) + { + var full = Path.GetFullPath(root); + for (var directory = new DirectoryInfo(full); directory is not null; directory = directory.Parent) + { + var git = Path.Combine(directory.FullName, ".git"); + if (!Directory.Exists(git) && !File.Exists(git)) continue; + + var relative = Path.GetRelativePath(directory.FullName, full).Replace('\\', '/'); + return relative == "." ? "" : relative + "/"; + } + return ""; + } + + /// + /// A result per call site and privilege the roles lack, or can't check, merged over the entry points that reach it. + /// + private IEnumerable Findings(Manifest manifest, CoverageReport? coverage) + { + if (coverage is null) yield break; + + var findings = new Dictionary<(int Rule, SourceLocation Location, string Privilege, RunsAs RunsAs, string Roles, string? Suppressed), (string Message, Properties Properties, List
In)>(); + foreach (var manifestSection in manifest.Sections) + { + var section = new Section(manifestSection.Id, manifestSection.Declaration); + var sectionCoverage = coverage.For(manifestSection); + foreach (var need in PrivilegeNeed.Of(manifestSection, sectionCoverage, _filter)) + { + var (table, privilege, result) = (need.Table, need.PrivilegeName, need.Coverage!); + var identity = need.RunsAs with { Assumed = false }; + var roles = sectionCoverage.Identities.FirstOrDefault(i => i.RunsAs == identity); + var what = table is null ? privilege : $"{privilege} on {table}"; + var (rule, message) = result.Status switch + { + CoverageStatus.Missing or CoverageStatus.Suppressed => ((int?)MissingRule, $"{what} is missing from {roles?.Roles}, needed as {identity}"), + CoverageStatus.NotChecked => (NotCheckedRule, $"{what} as {identity} isn't checked ({roles?.Note ?? "no roles"})"), + CoverageStatus.Unverifiable => (UnverifiableRule, $"{what} can't be checked against {roles?.Roles} for {identity} (the role metadata predates privileges not tied to a table)"), + _ => (null, ""), + }; + if (rule is not { } index) continue; + + var suppressed = result.Status == CoverageStatus.Suppressed ? result.Reason ?? "" : null; + var rolesText = roles?.Roles?.ToString() ?? ""; + foreach (var location in need.Sources.Select(s => s.Location).Distinct()) + { + var key = (index, location, $"{table} {privilege}", identity, rolesText, suppressed); + if (!findings.TryGetValue(key, out var finding)) + { + findings.Add(key, finding = (message, new Properties(table, privilege, identity.ToString(), roles?.Roles?.Names), [])); + } + finding.In.Add(section); + } + } + } + + foreach (var ((rule, location, _, _, _, suppressed), (message, properties, @in)) in findings) + { + yield return Result(rule, $"{message}, in {Sections(@in)}", location, @in, properties, + suppressed is null ? null : [new SuppressionDocument("external", suppressed.Length > 0 ? suppressed : null)]); + } + } + + /// + /// A result per unresolved call site that would need a role, so not those running as SYSTEM. + /// + private IEnumerable Unresolved(Manifest manifest) => + UnresolvedSites.Of(manifest, _filter).Where(s => s.Operation.RunsAs.Kind != RunsAsKind.System).Select(site => + { + var operation = site.Operation; + return Result(UnresolvedRule, $"{operation.Operation}{UnresolvedSites.PrivilegeSuffix(operation)} as {operation.RunsAs}: {operation.Reason}, in {Sections(site.In)}", operation.Source.Location, site.In, + new Properties(null, operation.Privileges.Count > 0 ? string.Join(", ", operation.Privileges) : null, operation.RunsAs.ToString(), null), null); + }); + + private ResultDocument Result(int rule, string message, SourceLocation location, IReadOnlyList
sections, Properties properties, IReadOnlyList? suppressions) + { + var related = sections + .Where(s => s.Declaration is { Line: > 0 }) + .Select((s, i) => new RelatedLocationDocument(i, Physical(s.Declaration!), new MessageDocument(s.Id))) + .ToList(); + // A location outside the code, such as --operation, isn't a location in a file, so the entry point is used + var primary = location.Line > 0 ? Physical(location) : related.FirstOrDefault()?.PhysicalLocation; + return new ResultDocument( + Rules[rule].Id, + rule, + Rules[rule].DefaultConfiguration.Level, + new MessageDocument(message), + primary is null ? null : [new LocationDocument(primary)], + related.Count > 0 ? related : null, + suppressions, + properties with { EntryPoints = sections.Select(s => s.Id).ToList() }); + } + + private static string Sections(IReadOnlyList
sections) + { + var named = string.Join(", ", sections.Take(NamedSections).Select(s => s.Id)); + return sections.Count > NamedSections ? $"{named} and {sections.Count - NamedSections} more" : named; + } + + private PhysicalLocationDocument Physical(SourceLocation location) => + new(Artifact(location.File), new RegionDocument(location.Line, location.Column)); + + /// + /// The file relative to %SRCROOT%, with ../ resolved; a file on another drive keeps its full path, + /// as a file URI. + /// + private ArtifactLocationDocument Artifact(string file) + { + if (file.StartsWith('/') || (file.Length > 1 && file[1] == ':')) + { + return new ArtifactLocationDocument("file:///" + Escape(file.TrimStart('/').Split('/')), null); + } + + var segments = new List(); + foreach (var segment in (sourceRoot + file).Split('/')) + { + if (segment is "" or ".") continue; + if (segment == ".." && segments.Count > 0 && segments[^1] != "..") segments.RemoveAt(segments.Count - 1); + else segments.Add(segment); + } + return new ArtifactLocationDocument(Escape(segments), SourceRootId); + } + + private static string Escape(IEnumerable segments) => + string.Join("/", segments.Select(s => s.EndsWith(':') ? s : Uri.EscapeDataString(s))); + + private sealed record SarifDocument( + [property: JsonPropertyName("$schema")] string Schema, + string Version, + IReadOnlyList Runs); + + private sealed record RunDocument(ToolDocument Tool, IReadOnlyList Results); + + private sealed record ToolDocument(DriverDocument Driver); + + private sealed record DriverDocument(string Name, string? Version, string InformationUri, IReadOnlyList Rules); + + private sealed record RuleDocument(string Id, string Name, MessageDocument ShortDescription, MessageDocument FullDescription, ConfigurationDocument DefaultConfiguration); + + private sealed record ConfigurationDocument(string Level); + + private sealed record ResultDocument( + string RuleId, + int RuleIndex, + string Level, + MessageDocument Message, + IReadOnlyList? Locations, + IReadOnlyList? RelatedLocations, + IReadOnlyList? Suppressions, + Properties Properties); + + private sealed record MessageDocument(string Text); + + private sealed record LocationDocument(PhysicalLocationDocument PhysicalLocation); + + private sealed record RelatedLocationDocument(int Id, PhysicalLocationDocument PhysicalLocation, MessageDocument Message); + + private sealed record PhysicalLocationDocument(ArtifactLocationDocument ArtifactLocation, RegionDocument? Region); + + private sealed record ArtifactLocationDocument(string Uri, string? UriBaseId); + + private sealed record RegionDocument(int StartLine, int StartColumn); + + private sealed record SuppressionDocument(string Kind, string? Justification); + + /// The table, or null for a privilege not tied to a table or an unresolved operation. + /// The privilege, or the privileges of an unresolved operation. + /// The roles checked against. + /// Ids of the entry points and unreached methods that reach the call site. + private sealed record Properties(string? Table, string? Privilege, string RunsAs, IReadOnlyList? Roles, IReadOnlyList? EntryPoints = null); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/TextManifestWriter.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/TextManifestWriter.cs new file mode 100644 index 00000000..263b7a87 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/TextManifestWriter.cs @@ -0,0 +1,356 @@ +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The manifest for reading in a terminal: requirements per entry point, the methods no entry point reaches, +/// then the privileges per table and the privileges not tied to a table. With coverage, each requirement is marked +/// granted (✔) or missing (✘), with the roles each identity was checked against. Below , +/// sources are shown without their call paths; at only what needs attention is shown, +/// and a last line says what was left out. and replace +/// the sections with the privileges to change (). A filter narrows the sections, the +/// privileges per table and the missing privileges; the counts and the result stay those of the whole analysis. +/// +internal sealed class TextManifestWriter(ReportOptions? options = null) : IManifestWriter +{ + private readonly ReportOptions _options = options ?? ReportOptions.Default; + + /// + /// The sources shown for a requirement below . + /// + private const int ShortSources = 3; + + /// + /// The privilege column of a privilege not tied to a table, whose name is in the table column. + /// + private const string GlobalColumn = "global"; + + public void Write(Manifest manifest, CoverageReport? coverage, TextWriter writer) => new Report(_options, manifest, coverage, writer).Write(); + + /// + /// One report being written, with what it has left out so far. + /// + private sealed class Report(ReportOptions options, Manifest manifest, CoverageReport? coverage, TextWriter writer) + { + private readonly ReportFilter _filter = options.Filter; + private readonly Detail _detail = options.Detail; + private int _hiddenRows; + private int _hiddenAssumptions; + private bool _trimmed; + private int _tableWidth; + private int _privilegeWidth; + private int _runsAsWidth; + private int _coverageWidth; + + public void Write() + { + if (_detail <= Detail.Compact) Needs(manifest, coverage, _filter, _detail == Detail.Compact, writer); + else Sections(); + + // With roles, the missing privileges below say what to change, so the summary of everything needed is detail + if (_detail > Detail.Normal || (coverage is null && _detail == Detail.Normal)) PrivilegesPerTable(); + + if (_detail > Detail.Compact && manifest.NotRoleGoverned?.Where(_filter.MatchesTable).ToList() is { Count: > 0 } notGoverned) + { + writer.Write($"Not in any security role, so XrmMockup allows every operation: {string.Join(", ", notGoverned)}\n\n"); + } + + writer.Write(ReportText.Totals(manifest) + "\n"); + + if (!_filter.IsEmpty) + { + writer.Write(ReportText.Filtered(manifest, _filter) + "\n"); + } + + if (coverage is not null) + { + writer.Write(ReportText.Result(coverage.Summary) + "\n"); + var (missing, missingGlobal) = _filter.Missing(manifest, coverage); + // Below normal, the blocks above already say what to change + if (_detail > Detail.Compact) Missing(missing, missingGlobal, writer); + if (ReportText.NotChecked(coverage.Summary) is { } notChecked) writer.Write(notChecked + "\n"); + } + + if (_detail <= Detail.Compact) + { + var which = _detail == Detail.Minimal ? "entry points, " : ""; + // Without roles every requirement is listed, so only what runs as SYSTEM is left out + var requirements = coverage is null ? "what runs as SYSTEM" : "requirements with nothing to fix"; + var adds = _detail == Detail.Minimal ? $"{Name(Detail.Compact)} adds the entry points, {Name(Detail.Normal)} the sources" : $"{Name(Detail.Normal)} adds the sources"; + writer.Write($"Not shown: {which}sources and {requirements}. {CliOptions.Detail.Primary} {adds}, {Name(Detail.Detailed)} everything\n"); + } + else if (NotShown(_hiddenRows, _hiddenAssumptions, _trimmed) is { } notShown) + { + writer.Write(notShown + "\n"); + } + } + + /// + /// The entry points, then the methods no entry point reaches. + /// + private void Sections() + { + var entryPoints = manifest.EntryPoints.Select(entryPoint => + { + var header = entryPoint.Declaration is { } declaration ? $"{entryPoint.Id} {declaration}" : entryPoint.Id; + if (entryPoint.ImpersonatingUserId is { } user) header += $" (runs as user {user})"; + return View(header, entryPoint.Triggers, entryPoint); + }).Where(s => s.Shown).ToList(); + var unreached = manifest.Unreached.Select(method => + { + var header = method.Declaration is { } declaration ? $"{method.Id} {declaration}" : method.Id; + return View(header, [], method); + }).Where(s => s.Shown).ToList(); + + var rows = entryPoints.Concat(unreached).SelectMany(s => s.Rows).ToList(); + _tableWidth = rows.Select(r => r.Table.Length).DefaultIfEmpty(0).Max(); + _privilegeWidth = Enum.GetNames().Append(GlobalColumn).Max(n => n.Length); + _runsAsWidth = rows.Select(r => r.RunsAs.ToString().Length).DefaultIfEmpty(0).Max(); + _coverageWidth = rows.Select(r => r.Coverage is { } result ? Label(result).Length : 0).DefaultIfEmpty(0).Max(); + + foreach (var section in entryPoints) + { + Section(section); + } + + if (unreached.Count > 0) + { + writer.Write("Not reached from any entry point\n\n"); + foreach (var section in unreached) + { + Section(section); + } + } + } + + private SectionView View(string header, IReadOnlyList triggers, IManifestSection section) + { + var sectionCoverage = coverage?.For(section); + var rows = PrivilegeNeed.Of(section, sectionCoverage, _filter) + .Select(n => new RowView(n.Name, n.TablePrivilege?.ToString() ?? GlobalColumn, n.RunsAs, n.Basis, n.Sources, n.Coverage)) + .Where(r => Shown(r.Coverage)) + .ToList(); + var assumptions = section.Assumptions; + var shownUnresolved = section.Unresolved.Where(_filter.Matches).ToList(); + var detailed = _detail > Detail.Normal; + // Every section is listed, as before, unless only what needs attention or matches a filter is shown + var shown = (detailed && _filter.IsEmpty) || rows.Count + shownUnresolved.Count > 0; + if (!detailed && (shown || _filter.IsEmpty)) _hiddenAssumptions += assumptions.Count; + if (detailed && triggers.Count > 0) header += $"\n fires: {string.Join(", ", triggers)}"; + return new SectionView(header, rows, shownUnresolved, detailed ? assumptions : [], sectionCoverage, shown); + } + + private bool Shown(RequirementCoverage? result) + { + var shown = _detail > Detail.Normal || result is null + || result.Status is CoverageStatus.Missing or CoverageStatus.NotChecked or CoverageStatus.Unverifiable; + if (!shown) _hiddenRows++; + return shown; + } + + private void Section(SectionView section) + { + writer.Write(section.Header + "\n"); + if (section.Coverage is not null) + { + foreach (var identity in section.Coverage.Identities) + { + var roles = identity.Roles is { } set ? set.ToString() : identity.Note; + writer.Write($" roles for {identity.RunsAs}: {roles}\n"); + } + } + + foreach (var row in section.Rows) + { + Row(row); + } + + foreach (var operation in section.Unresolved) + { + writer.Write($" ? {operation.Operation}{UnresolvedSites.PrivilegeSuffix(operation)} as {operation.RunsAs}: {operation.Reason} {Sources([operation.Source])}\n"); + } + + foreach (var assumption in section.Assumptions) + { + writer.Write($" ~ {assumption.Reason} {Sources([assumption.Source])}\n"); + } + writer.Write('\n'); + } + + private void Row(RowView row) + { + var basis = row.Basis == RequirementBasis.Direct ? "" : $" ({BasisNames.Of(row.Basis)})"; + var sources = Sources(row.Sources); + var text = $"{row.Table.PadRight(_tableWidth)} {row.Privilege.PadRight(_privilegeWidth)} {row.RunsAs.ToString().PadRight(_runsAsWidth)} "; + if (row.Coverage is { } result) + { + var reason = result.Status == CoverageStatus.Suppressed && result.Reason is { } why ? $" suppressed: {why}" : ""; + writer.Write($" {Mark(result.Status)} {text}{Label(result).PadRight(_coverageWidth)} {sources}{basis}{reason}\n"); + } + else + { + writer.Write($" {text}{sources}{basis}\n"); + } + } + + private string Sources(IReadOnlyList sources) + { + if (_detail == Detail.Full) return string.Join(", ", sources.Select(Source)); + + var locations = sources.Select(s => s.Location).Distinct().ToList(); + if (locations.Count > ShortSources || sources.Any(s => s.Path.Count > 1)) _trimmed = true; + var text = string.Join(", ", locations.Take(ShortSources)); + return locations.Count > ShortSources ? $"{text} and {locations.Count - ShortSources} more" : text; + } + + private void PrivilegesPerTable() + { + var byTable = manifest.AllRequirements + .Where(_filter.Matches) + .GroupBy(r => r.Table) + .OrderBy(g => g.Key, StringComparer.Ordinal) + .ToList(); + if (byTable.Count > 0) + { + writer.Write("Privileges per table\n"); + foreach (var table in byTable) + { + var privileges = table.Select(r => r.Privilege).Distinct().OrderBy(p => p); + writer.Write($" {table.Key.PadRight(_tableWidth)} {string.Join(", ", privileges)}\n"); + } + writer.Write('\n'); + } + + var shownGlobal = manifest.AllGlobalRequirements.Where(_filter.Matches).Select(r => r.Privilege).Distinct(StringComparer.Ordinal).OrderBy(p => p, StringComparer.Ordinal).ToList(); + if (shownGlobal.Count > 0) + { + writer.Write($"Privileges not tied to a table: {string.Join(", ", shownGlobal)}\n\n"); + } + } + } + + /// + /// The , each followed at by the entry points that need + /// its privileges. + /// + private static void Needs(Manifest manifest, CoverageReport? coverage, ReportFilter filter, bool byEntryPoint, TextWriter writer) + { + foreach (var block in RoleChanges.Of(manifest, coverage, filter)) + { + writer.Write($"{block.Heading}:\n"); + Tables(block.Tables, " "); + if (byEntryPoint) + { + writer.Write("\n By entry point:\n"); + foreach (var group in block.EntryPoints) + { + writer.Write('\n'); + foreach (var id in group.Ids) + { + writer.Write($" {id}\n"); + } + Tables(group.Tables, " "); + } + } + writer.Write('\n'); + } + + void Tables(IReadOnlyList tables, string indent) + { + var width = tables.Max(t => t.Table.Length); + foreach (var table in tables) + { + writer.Write($"{indent}{table.Table.PadRight(width)} {(table.IsGlobal ? GlobalColumn : string.Join(", ", table.Privileges))}\n"); + } + } + } + + private static string Name(Detail detail) => detail.ToString().ToLowerInvariant(); + + /// + /// What a lower detail level left out, and the level that shows it; null when nothing was. + /// + private static string? NotShown(int requirements, int assumptions, bool trimmed) + { + var parts = new List(); + if (requirements > 0) parts.Add($"{ReportText.Count(requirements, "requirement")} with nothing to fix"); + if (assumptions > 0) parts.Add(ReportText.Count(assumptions, "assumption")); + if (parts.Count > 0) + { + var full = trimmed ? $", {Name(Detail.Full)} also adds every source and call path" : ""; + return $"Not shown: {string.Join(", ", parts)}. {CliOptions.Detail.Primary} {Name(Detail.Detailed)} lists them{full}"; + } + return trimmed ? $"Not shown: every source and call path. {CliOptions.Detail.Primary} {Name(Detail.Full)} adds them" : null; + } + + /// + /// A requirement or privilege not tied to a table as one row, the privilege name in the table column. + /// + private sealed record RowView(string Table, string Privilege, RunsAs RunsAs, RequirementBasis Basis, IReadOnlyList Sources, RequirementCoverage? Coverage); + + /// + /// An entry point or unreached method with what is shown of it. + /// + private sealed record SectionView( + string Header, + IReadOnlyList Rows, + IReadOnlyList Unresolved, + IReadOnlyList Assumptions, + SectionCoverage? Coverage, + bool Shown); + + /// + /// Each missing privilege once, with the roles that lack it and where it is needed, so it doesn't have to be + /// collected from the sections above. + /// + private static void Missing(IReadOnlyList missing, IReadOnlyList missingGlobal, TextWriter writer) + { + var rows = missing + .Select(m => (Table: m.Table, Privilege: m.Privilege.ToString(), m.RunsAs, m.Roles, m.In)) + .Concat(missingGlobal.Select(m => (Table: m.Privilege, Privilege: GlobalColumn, m.RunsAs, m.Roles, m.In))) + .ToList(); + if (rows.Count == 0) return; + + var tableWidth = rows.Max(m => m.Table.Length); + var privilegeWidth = rows.Max(m => m.Privilege.Length); + var runsAsWidth = rows.Max(m => m.RunsAs.ToString().Length); + var rolesWidth = rows.Max(m => m.Roles.ToString().Length); + writer.Write("Missing privileges:\n"); + foreach (var privilege in rows) + { + writer.Write( + $" ✘ {privilege.Table.PadRight(tableWidth)} {privilege.Privilege.PadRight(privilegeWidth)} " + + $"{privilege.RunsAs.ToString().PadRight(runsAsWidth)} {privilege.Roles.ToString().PadRight(rolesWidth)} " + + $"in {string.Join(", ", privilege.In)}\n"); + } + } + + private static string Mark(CoverageStatus status) => status switch + { + CoverageStatus.Granted or CoverageStatus.NotGoverned => "✔", + CoverageStatus.Missing => "✘", + CoverageStatus.Suppressed => "-", + _ => "·", + }; + + /// + /// The granted depth, or what else became of the requirement. + /// + private static string Label(RequirementCoverage coverage) => coverage.Status switch + { + CoverageStatus.Granted => coverage.Depth.ToString()!, + CoverageStatus.NotGoverned => "not governed", + CoverageStatus.Missing => "missing", + CoverageStatus.Suppressed => "suppressed", + CoverageStatus.NotChecked => "not checked", + CoverageStatus.Unverifiable => "unverifiable", + _ => "SYSTEM", + }; + + /// + /// A source location, with the call path when the operation is in a called method. + /// + private static string Source(RequirementSource source) => + source.Path.Count > 1 ? $"{source.Location} ({string.Join(" → ", source.Path)})" : source.Location.ToString(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/UnresolvedSites.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/UnresolvedSites.cs new file mode 100644 index 00000000..a7c3edc2 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Output/UnresolvedSites.cs @@ -0,0 +1,48 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Output; + +/// +/// The unresolved operations a filter matches, each call site once with every entry point and unreached method that +/// reaches it, sorted by location, operation and identity. Markdown and SARIF list call sites rather than sections. +/// +internal static class UnresolvedSites +{ + public static IReadOnlyList Of(Manifest manifest, ReportFilter filter) + { + var sites = new Dictionary<(SourceLocation Location, string Operation, string Privileges, RunsAs RunsAs, string Reason), (UnresolvedOperation Operation, List
In)>(); + foreach (var section in manifest.Sections) + { + foreach (var operation in section.Unresolved.Where(filter.Matches)) + { + var key = (operation.Source.Location, operation.Operation, string.Join(", ", operation.Privileges), operation.RunsAs, operation.Reason); + if (!sites.TryGetValue(key, out var site)) sites.Add(key, site = (operation, [])); + site.In.Add(new Section(section.Id, section.Declaration)); + } + } + + return sites + .OrderBy(s => s.Key.Location) + .ThenBy(s => s.Key.Operation, StringComparer.Ordinal) + .ThenBy(s => s.Key.RunsAs) + .ThenBy(s => s.Key.Privileges, StringComparer.Ordinal) + .ThenBy(s => s.Key.Reason, StringComparer.Ordinal) + .Select(s => new UnresolvedSite(s.Value.Operation, s.Value.In)) + .ToList(); + } + + /// + /// The privileges an unresolved operation would need, such as [Write, Delete]; empty when they aren't known. + /// + public static string PrivilegeSuffix(UnresolvedOperation operation) => + operation.Privileges.Count > 0 ? $" [{string.Join(", ", operation.Privileges)}]" : ""; +} + +/// The operation, as found in the first section that reaches it. +/// The entry points and unreached methods that reach it, in manifest order. +internal sealed record UnresolvedSite(UnresolvedOperation Operation, IReadOnlyList
In); + +/// +/// An entry point or unreached method, by id, with where it is declared. +/// +internal sealed record Section(string Id, SourceLocation? Declaration); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/PermissionAnalyzer.Tool.csproj b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/PermissionAnalyzer.Tool.csproj new file mode 100644 index 00000000..04860b02 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/PermissionAnalyzer.Tool.csproj @@ -0,0 +1,34 @@ + + + Exe + XrmMockup.PermissionAnalyzer.Tool + XrmMockup.PermissionAnalyzer.Tool + + true + + + + true + xrmmockup-permissions + ./nupkg + XrmMockup.PermissionAnalyzer + + README.md + Development build. See CHANGELOG.md for release history. + $([System.IO.File]::ReadAllText('$(PermissionsReleaseNotesPath)')) + CLI tool that works out which Dataverse privileges your code needs, by static analysis + + + + + + + + + + + + + + + diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Program.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Program.cs new file mode 100644 index 00000000..d0155edf --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/Program.cs @@ -0,0 +1,18 @@ +using System.CommandLine; +using System.CommandLine.Invocation; +using XrmMockup.PermissionAnalyzer.Tool; +using XrmMockup.PermissionAnalyzer.Tool.Commands; + +var options = new AnalysisOptions(); +var rootCommand = new RootCommand("XrmMockup Permission Analyzer - Work out which Dataverse privileges your code needs, by static analysis, and check them against security roles"); +options.AddTo(rootCommand); +rootCommand.SetAction((parseResult, cancellationToken) => AnalysisRunner.RunAsync(options.Read(parseResult), cancellationToken)); + +var parseResult = rootCommand.Parse(args); +// The errors alone, without the whole help after them, so they stand out in a build log +if (parseResult.Action is ParseErrorAction parseError) parseError.ShowHelp = false; +var exitCode = await parseResult.InvokeAsync(); +if (parseResult.Errors.Count > 0) Console.Error.WriteLine("Run with --help to see the options."); + +// Exit code 1 is reserved for "privileges missing", so invalid arguments exit like any other error +return parseResult.Errors.Count > 0 ? ExitCodes.Error : exitCode; diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/README.md b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/README.md new file mode 100644 index 00000000..d2c9ea10 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/README.md @@ -0,0 +1,781 @@ +# XrmMockup Permission Analyzer + +A .NET CLI tool that works out which Dataverse table privileges your code needs, by static analysis. +It finds your entry points (plugin steps, custom APIs, code activities and Azure Functions), follows +the calls from each one through your code without running any of it, and lists the privilege each +`IOrganizationService` call needs on each table, together with the identity it runs as. It can then check +those privileges against your security roles. It is a companion to +[XrmMockup](https://github.com/delegateas/XrmMockup) and reads the security roles that +`xrmmockup-metadata` downloads. + +> **Preview.** This release lists the privileges each entry point needs and checks them against +> security roles, including plugin cascades and the execute privileges of custom APIs. + +## Installation + +```bash +dotnet tool install --global XrmMockup.PermissionAnalyzer +``` + +Or locally in your repository: + +```bash +dotnet new tool-manifest # if you don't have a manifest yet +dotnet tool install XrmMockup.PermissionAnalyzer +``` + +While only release candidates are published, add `--prerelease` to either command. + +## Quick start + +From the folder with your solution and `appsettings.json`: + +```bash +xrmmockup-permissions +``` + +Example output: + +``` +Caller needs: + account Read + contact Create + +1 entry point, 0 unreached methods, 3 tables, 3 table privileges (3 requirements counted per entry point and method), 1 unresolved +Not shown: entry points, sources and what runs as SYSTEM. --detail compact adds the entry points, normal the sources, detailed everything +``` + +The output lists the privileges each identity needs (see [Runs as](#runs-as)), a line per table +with its privileges in the order the role editor shows them; SYSTEM needs no role, so it isn't +listed. The last line but one counts distinct table privileges, and separately each requirement +once per entry point or unreached method that needs it. + +`--detail compact` adds the entry points that need the privileges, and `--detail normal` lists +each entry point's requirements with where the call is: + +``` +plugin:Contoso.Plugins.AccountPostPlugin:Update:account:PostOperation src/Plugins/AccountPostPlugin.cs:14 + account Read Caller src/Plugins/AccountPostPlugin.cs:20 + contact Create Caller src/Services/ContactService.cs:31 + task Create System src/Plugins/AccountPostPlugin.cs:44 + ? Update [Write] as Caller: entity comes from InputParameters["Target"] src/Plugins/AccountPostPlugin.cs:40 + +Privileges per table + account Read + contact Create + task Create + +1 entry point, 0 unreached methods, 3 tables, 3 table privileges (3 requirements counted per entry point and method), 1 unresolved +Not shown: every source and call path. --detail full adds them +``` + +At `normal`, each entry point lists its requirements with the identity they run as and where the +call is, up to three locations. With `--detail full`, every location is listed, and a call +in another method shows the call path from the entry point after it, such as +`(AccountPostPlugin.ctor (lambda, line 16) → ContactService.CreateFor)`. See +[Detail and filters](#detail-and-filters) for what each level shows. + +- Lines starting with `?` are calls whose table can't be determined statically, shown from + `--detail normal`; below it they are only counted. They are listed with + the reason instead of being dropped, so the result never hides a call. +- Lines starting with `~` are assumptions the analysis had to make, such as the identity of a + service passed in from outside. They are listed from `--detail detailed`. +- `Not reached from any entry point` lists methods that make service calls but that no entry point + calls. Add them with `--entry` or `EntryPoints` if something outside the solution calls them. + +## Usage + +```bash +xrmmockup-permissions [scope] [--role ] [--fail-on-missing | --strict] [options] +``` + +Lists the privileges each entry point needs and, when there are roles to check against, whether the +roles grant them. With `--fail-on-missing` it exits with `1` when they don't, so a build can fail on it. + +| Option | Alias | Description | +|--------|-------|-------------| +| `--solution` | `-s` | Solution (`.sln`/`.slnx`) or project (`.csproj`) to analyze. A project is analyzed together with the projects it references; methods in those that the project doesn't reach aren't listed as unreached, since a shared library also has code for other apps | +| `--metadata` | `-m` | XrmMockup metadata folder with `SecurityRoles/`. Default: `MetadataDirectory`, then `XrmMockup:Metadata:OutputDirectory`, then `./Metadata` next to the configuration file when it exists | +| `--exclude` | `-x` | Leave out projects matching a pattern (see [Excluding projects](#excluding-projects)). Repeatable | +| `--plugin-solution` | | A solution or project with plugin code that the analyzed code fires but doesn't include, used for plugin cascades only (see [Plugin code in another solution](#plugin-code-in-another-solution)). Repeatable | +| `--config` | `-c` | Configuration file; `appsettings.{DOTNET_ENVIRONMENT}.json` in the same folder applies over it (see [Configuration](#configuration)). Default: `appsettings.json` in the current directory, when it exists | +| `--format` | `-f` | `text` (default), `json`, `markdown` or `sarif` (see [Output](#output)) | +| `--output` | `-o` | Write to a file instead of standard output | +| `--detail` | `-d` | How much of the text report to show (text only): `minimal` (default), `compact`, `normal`, `detailed` or `full` (see [Detail and filters](#detail-and-filters)) | +| `--table` | | Only report requirements on these tables. Comma-separated or repeatable | +| `--privilege` | | Only report these privileges, such as `Write` or `prvBulkDelete`. Comma-separated or repeatable | +| `--runs-as` | | Only report requirements of these identities, such as `ApplicationUser`. Comma-separated or repeatable | +| `--basis` | | Only report requirements with these bases, such as `filter-unknown`. Comma-separated or repeatable | +| `--plugin` | | Only one plugin, or one of its steps: `[:[:]]`, such as `AccountPostPlugin:Update` | +| `--custom-api` | | Only one custom API, by unique name | +| `--function` | | Only one Azure Function, by function name, or as `/` when several apps have one of that name | +| `--entry` | | Analyze a method as an entry point, such as `Contoso.Sync.Importer.Run`, and show only that. Repeatable | +| `--operation` | | Only a user operation on a table and the plugin steps it fires: `"
"`, such as `"Update account"` (see [User operations](#user-operations)) | +| `--attributes` | | The columns the `--operation` sets, such as `name,statecode`. Comma-separated or repeatable | +| `--role` | `-r` | Check the requirements against these roles (see [Checking against roles](#checking-against-roles)). Repeatable; roles combine. Replaces `Principals` | +| `--caller-role` | | Roles of the user that app code acts for through `CallerId`. Repeatable | +| `--no-roles` | | Only list what the code needs, without checking it against `Principals` and `Users` in `appsettings.json` | +| `--fail-on-missing` | | Exit with `1` when the roles don't grant a privilege the code needs (see [Failing a build](#failing-a-build)) | +| `--strict` | | Like `--fail-on-missing`, and also fail on what couldn't be checked | + +Use at most one of `--plugin`, `--custom-api`, `--function`, `--entry` and `--operation`. Without any, every entry +point is listed. A scope that matches nothing is an error. Type names may be simple or full and are +matched case-insensitively. + +Without roles to check against (no `--role` or `--caller-role`, and nothing analyzed matches `Principals` +or `Users`), or with `--no-roles`, the output has no role data, so it only changes when the code or the +metadata changes. That is the output to commit and diff. + +### Checking against roles + +The requirements are checked against `--role` and `--caller-role`, else against the roles mapped in +`Principals` and `Users` in `appsettings.json`. + +```bash +xrmmockup-permissions --role "Salesperson" --plugin AccountPostPlugin +xrmmockup-permissions --role "Salesperson" --role "Marketing" +xrmmockup-permissions --function ProcessOrder --role "Integration App" --caller-role "Salesperson" +xrmmockup-permissions --operation "Update account" --attributes statecode --role "Salesperson" +xrmmockup-permissions # roles from Principals and Users in appsettings.json +``` + +Example output: + +``` +Missing from Salesperson (--role), for Caller: + contact Create + +1 entry point, 0 unreached methods, 3 tables, 3 table privileges (3 requirements counted per entry point and method), 1 unresolved +Result: 1 granted, 1 missing, 1 as SYSTEM +Not checked: 1 unresolved operation (1 with an unknown table or request) +Not shown: entry points, sources and requirements with nothing to fix. --detail compact adds the entry points, normal the sources, detailed everything +``` + +Each block is the privileges a set of roles lacks, merged over every entry point and identity that +uses it, so it reads as the changes to make to the roles. Requirements whose identity has no roles get +a block of their own, with how to give it some. With `--detail normal`, the requirements that need +attention are listed per entry point, with where each call is: + +``` +plugin:Contoso.Plugins.AccountPostPlugin:Update:account:PostOperation src/Plugins/AccountPostPlugin.cs:14 + roles for Caller: Salesperson (--role) + ✘ contact Create Caller missing src/Services/ContactService.cs:31 + ? Update [Write] as Caller: entity comes from InputParameters["Target"] src/Plugins/AccountPostPlugin.cs:40 + +1 entry point, 0 unreached methods, 3 tables, 3 table privileges (3 requirements counted per entry point and method), 1 unresolved +Result: 1 granted, 1 missing, 1 as SYSTEM +Missing privileges: + ✘ contact Create Caller Salesperson (--role) in plugin:Contoso.Plugins.AccountPostPlugin:Update:account:PostOperation +Not checked: 1 unresolved operation (1 with an unknown table or request) +Not shown: 2 requirements with nothing to fix. --detail detailed lists them, full also adds every source and call path +``` + +With `--detail detailed`, the requirements the roles +grant and those running as SYSTEM are listed too: + +``` +plugin:Contoso.Plugins.AccountPostPlugin:Update:account:PostOperation src/Plugins/AccountPostPlugin.cs:14 + roles for Caller: Salesperson (--role) + ✔ account Read Caller BusinessUnit src/Plugins/AccountPostPlugin.cs:20 + ✘ contact Create Caller missing src/Services/ContactService.cs:31 + · task Create System SYSTEM src/Plugins/AccountPostPlugin.cs:44 + ? Update [Write] as Caller: entity comes from InputParameters["Target"] src/Plugins/AccountPostPlugin.cs:40 +... +``` + +Each requirement is checked against the roles of the identity it runs as: + +| Runs as | Checked against | +|---------|-----------------| +| `Caller` | `--role` | +| `ApplicationUser` | `--role`, else the entry point's function app in `Principals` | +| `User` | The user's roles in `Users` | +| `ImpersonatedCaller` | `--caller-role`: the call runs with the privileges of the user in `CallerId` | +| `System` | Nothing; SYSTEM needs no role | + +- Repeated roles combine as they do in Dataverse: a privilege is granted when any of them grants it, + at the highest depth any of them grants. +- Any depth counts. The granted depth (`User`, `BusinessUnit`, `ParentChildBusinessUnit` or + `Organization`) is shown but doesn't affect the result. +- Requirements with an `(assumed)` identity are checked like the rest. +- `✔` is granted (or on a table no role governs, which XrmMockup doesn't check), `✘` is missing, `-` is + [suppressed](#configuration), and `·` is not checked, unverifiable or runs as SYSTEM. Each entry point first lists the + roles each identity was checked against, or why it wasn't checked. +- Role names are matched exactly, then ignoring case. An unknown name is an error that suggests the + closest names. +- `Missing privileges` lists each missing privilege once, with the identity, the roles that don't + grant it and every entry point or unreached method that needs it. With `--fail-on-missing`, the error names them too. +- `Not checked` lists what the result doesn't cover: unresolved operations (split into requests + without a rule, custom API calls, fired workflows, and operations with an unknown table or request), requirements whose identity + has no roles, unverifiable privileges, and entry points or methods whose analysis stopped at its limit of 10,000 calls + (their requirements may be incomplete). It is left out when everything was checked. When nothing is + missing but something wasn't checked, `--fail-on-missing` exits with `0` and logs a warning; `--strict` makes it fail. +- Some privileges aren't tied to a table, such as `prvActOnBehalfOfAnotherUser` or the execute + privilege of a custom API. They are listed with their name in the table column and `global` as the + privilege, and under `Privileges not tied to a table`. +- Setting `CallerId` needs `prvActOnBehalfOfAnotherUser` on the identity that sets it, usually the + application user, for every operation that acts for the user in `CallerId`. +- Privileges not tied to a table are checked against the roles' global privileges, which + `xrmmockup-metadata` downloads in releases after v1.2.0. Roles from older metadata don't have them, + so these privileges are `unverifiable` until you regenerate the metadata. + +### Failing a build + +Without `--fail-on-missing` or `--strict`, the exit code is `0` whatever the roles lack, so the report can +be read without failing anything. In CI, pass `--fail-on-missing`: + +```bash +xrmmockup-permissions --function ProcessOrder --role "Integration App" --fail-on-missing +``` + +| Code | Meaning | +|------|---------| +| `0` | Success. With `--fail-on-missing`: every checked privilege is granted, suppressed or on a table no role governs | +| `1` | With `--fail-on-missing`: some privilege is missing. With `--strict`, also when an operation is unresolved, an identity has no roles to check against, a privilege is unverifiable, or an analysis stopped at the call limit | +| `2` | Error: invalid options, missing files, an unknown role, or, with `--fail-on-missing`, no roles at all (no `--role`, `--caller-role`, and nothing analyzed matches `Principals` or `Users`) | + +As a pull request check, run the tool on the pull request's code but take `Metadata/` and +`appsettings.json` from the base branch, for example with +`git checkout origin/main -- Metadata appsettings.json` before the run. Otherwise the change being +checked can grant itself what it needs, by editing a role in `Metadata/`, adding a `Suppress` entry, +or mapping a function to another role in `Principals`. Review changes to those files on their own. + +### Trust + +The analysis doesn't run the code it reads, but loading a project is a design-time build: MSBuild +evaluates the project files and runs the targets that build needs, which can include the project's +and its packages' own targets and tasks such as `Exec`, and Roslyn runs their source generators. +Only analyze code you would build. In particular, don't run it on code from a fork in a workflow that +has secrets or a write token, such as one triggered by `pull_request_target`; `pull_request` gives +fork pull requests neither. + +## Entry points + +| Kind | Found from | +|------|------------| +| Plugin step | `RegisterPluginStep`, `RegisterStep` (lambda or `nameof(TService.Method)`) in [XrmPluginCore](https://github.com/delegateas/XrmPluginCore) plugin constructors | +| Plugin step (metadata) | Plugin steps in `Metadata/Metadata.xml`, for `IPlugin` classes that register no steps in code. Without metadata, such a class is one entry point for its `Execute` | +| Custom API | `RegisterCustomAPI` and `RegisterAPI` | +| Code activity | Subclasses of `CodeActivity` | +| Azure Function | Methods with `[Function]` (isolated worker) or `[FunctionName]` (in-process) | +| Method | `--entry` and the `EntryPoints` setting | +| Operation | `--operation` | + +Entry point ids look like `plugin:Contoso.AccountPostPlugin:Update:account:PostOperation` (the table +is `any` for steps on every table), `custom-api:ctx_DoThing`, `activity:Contoso.MyActivity`, +`function:Contoso.Functions/ProcessOrder` (the app's assembly and the function's name), +`method:Contoso.Sync.Importer.Run(IOrganizationService)` and +`operation:Update account(name,statecode)`. + +From each entry point, the tool follows calls into the rest of the solution, including across +projects. Services and tables passed as arguments, stored in fields or set through constructors are +tracked into the called methods. Interface calls go to the implementation registered with dependency +injection (`AddScoped()` and similar, including XrmPluginCore's +`OnBeforeBuildServiceProvider`). Without a registration they go to every implementation in the +solution, and the requirement is marked `all-implementations`. + +## Runs as + +Dataverse checks privileges against the user a service runs as, so each requirement has one: + +| Runs as | When | +|---------|------| +| `Caller` | The user who triggered the plugin, custom API or workflow: `OrganizationService`, `CreateOrganizationService(context.UserId)` | +| `User` | A specific user: `CreateOrganizationService()`, `SetUserContext(...)` on a step, or the step's impersonating user from metadata | +| `ApplicationUser` | Azure Functions and other app code: `ServiceClient`, injected `IOrganizationService` | +| `ImpersonatedCaller` | App code that sets `CallerId` | +| `System` | `OrganizationAdminService`, `CreateOrganizationService(null)`. No role privilege is needed | + +When the identity can't be determined, for example for a service passed in from outside the +analyzed code, the requirement is marked `(assumed)` and the assumption is listed with `~`. + +## What is analyzed + +Calls on `IOrganizationService`, `IOrganizationServiceAsync`/`Async2` and their implementations +(for example `ServiceClient`), including async forms: + +| Call | Privileges | +|------|------------| +| `Create` | Create, and Append and AppendTo for [lookups](#lookups) | +| `CreateAndReturn` | Create, Read, and Append and AppendTo for lookups | +| `Retrieve`, `RetrieveMultiple` | Read on the table and every linked table | +| `Update` | Write, and Append and AppendTo for lookups | +| `Delete` | Delete | +| `Associate`, `Disassociate` | Read, AppendTo on the target; Read, Append on the related records | +| `Execute` | From the rule for the request's message, see [Requests](#requests) | + +Calls on an `OrganizationServiceContext`, including generated contexts such as `new Xrm(service)`: + +| Call | Privileges | +|------|------------| +| `CreateQuery`, and query properties such as `AccountSet` | Read on the table, and on every table a LINQ `join` adds | +| `AddObject` | Create, and Append and AppendTo for lookups | +| `UpdateObject` | Write, and Append and AppendTo for lookups | +| `DeleteObject` | Delete | +| `AddLink`, `DeleteLink` | Read, AppendTo on the source; Read, Append on the target | +| `AddRelatedObject` | Create on the related record, and the privileges of `AddLink` | +| `Execute` | As on the service | + +The privileges of a change are reported where it's queued, not at `SaveChanges`. A context runs as +the service it's created with, also in code inside a context class and when it's kept in a field. +`LoadProperty` reads through a relationship whose table isn't known, and is reported as unresolved. + +The table is found from: + +- early-bound types (`[EntityLogicalName]`), such as `new Account()` +- constant strings, such as `new Entity("account")` or `Account.EntityLogicalName` +- `QueryExpression`, `QueryByAttribute`, `AddLink` and FetchXML (including interpolated strings) +- locals assigned in the same method, including both branches of `?:` and `??` +- loops over the result of `RetrieveMultiple` +- the value a helper method returns, resolved for each call with that call's arguments, such as + `service.Create(Build(flag))` or `RetrieveMultiple(Query())` +- type arguments of generic methods, such as `service.Get(id)` where `Get` uses + `new T().LogicalName` or `Activator.CreateInstance()` +- type arguments of generic types, from the object a method is called on, such as + `new Repository(service).GetRecords()` where `Repository` runs `CreateQuery()`. + This also works for a subclass such as `ContactRepository : Repository`, for overrides and + for calls through a generic interface such as `IRepository` +- the record `Retrieve` returns, which is of the table it asks for +- an early-bound lookup property, such as `order.CustomerId.LogicalName`, from the lookup's targets in + the entity metadata, as for [lookups](#lookups) +- `PrimaryEntityName` of the execution context in a plugin step, which is the step's table + +### Requests + +A request passed to `Execute` is checked against the rule for its message. Requests are followed like +tables: through locals, parameters, helper methods, object initializers, `Parameters["…"]`, and +collections built with `Add`, `AddRange` or collection expressions, including batching with `Chunk` or +`foreach`. Built-in rules cover: + +| Request | Privileges | +|---------|------------| +| `Create`, `Update`, `Delete`, `Retrieve`, `RetrieveMultiple`, `Associate`, `Disassociate` | As the matching call above | +| `Upsert` | Create and Write on `Target` | +| `CreateMultiple`, `UpdateMultiple`, `UpsertMultiple`, `DeleteMultiple` | As the single request, on each table in `Targets` | +| `ExecuteMultiple`, `ExecuteTransaction` | The privileges of every request in `Requests` | +| `Assign` | Assign, Write | +| `SetState` | Write on `EntityMoniker` | +| `GrantAccess`, `ModifyAccess` | Share, and each right in `PrincipalAccess.AccessMask` | +| `RevokeAccess` | Share | +| `Merge` | Read, Write; `prvMerge` | +| `QualifyLead` | Write on the lead; Create on account, contact and opportunity when asked to create them | +| `SendEmail` | Read, Write on email, with the assumption that it is sent as the caller (sending as another user needs `prvSendAsUser`) | +| `CloseIncident`, `WinOpportunity`, `LoseOpportunity`, `WinQuote`, `CloseQuote` | Create on the close activity, Write on the closed record | +| `ReviseQuote` | Read, Create on quote | +| `InitializeFileBlocksUpload` / `InitializeFileBlocksDownload` | Write / Read on `Target` | +| `BulkDelete` | `prvBulkDelete` | +| `ImportSolution`, `ImportSolutionAsync` / `ExportSolution`, `ExportSolutionAsync` | `prvImportCustomization` / `prvExportCustomization` | +| `PublishXml`, `PublishAllXml` | `prvPublishCustomization` | +| `ExecuteWorkflow` | `prvWorkflowExecution` | +| `DeleteRecordChangeHistory` / `DeleteAuditData` | `prvDeleteRecordChangeHistory` / `prvDeleteAuditPartitions` | +| `RetrieveAuditDetails`, `RetrieveAttributeChangeHistory`, `RetrieveRecordChangeHistory` | `prvReadRecordAuditHistory`, `prvReadAuditSummary` | +| Block transfers, metadata requests, `WhoAmI`, `RetrieveVersion`, `RetrievePrincipalAccess` and similar | None | + +Privileges named with `prv` are looked up in `PrivilegeCatalog.xml`: one not tied to a table is a +[privilege not tied to a table](#checking-against-roles), one tied to tables is the table privilege it grants on each, +and a name the catalog doesn't have is reported as unresolved. Without a catalog they are taken as +privileges not tied to a table. + +Some request parameters and columns need a privilege of their own: + +| Set | Needs | +|-----|-------| +| `BypassCustomPluginExecution` | `prvBypassCustomPlugins` | +| `BypassBusinessLogicExecution`, `BypassBusinessLogicExecutionStepIds` | `prvBypassCustomBusinessLogic` | +| `overriddencreatedon` on a record that is created | `prvOverrideCreatedOnCreatedBy` | + +A bypass parameter set to a constant `false` or empty value needs nothing. The bypassed plugin steps +don't run, see [plugin cascades](#plugin-cascades). + +A request without a rule is reported as unresolved. When its message is a custom API (one found in +the code, in `PrivilegeCatalog.xml`, a plugin step message in the metadata, or a name with a publisher +prefix such as `ctx_Approve`), it is reported as a custom API call. Add a rule for your own messages +in the [`Rules` setting](#request-rules). + +### Custom APIs + +Calling a custom API needs its execute privilege, if it has one. It is read from the registration in +the code, else from `PrivilegeCatalog.xml`, which `xrmmockup-metadata` writes with every privilege and +custom API in the environment: + +| Registration | Requirement | +|--------------|-------------| +| `.WithExecutePrivilege(Privilege.Read)` | Read on `account` (basis `execute-privilege`) | +| `.WithExecutePrivilege("ctx_Order", Privilege.Write)` | Write on `ctx_order` | +| `.WithExecutePrivilegeName("prvReadctx_Order")` | The table privilege the catalog has for the name, or the name itself when it isn't tied to a table | +| An execute privilege in the catalog only | The same, for a custom API whose code isn't analyzed | + +A privilege name is only looked up in the catalog, never guessed from its spelling. A name without a +catalog, a name the catalog doesn't have, a name computed at runtime, and a privilege whose access +right isn't a table privilege are reported as unresolved. + +The caller of a custom API needs the privilege, and so does the custom API's own entry point, under +`Caller`. When the custom API is implemented in the analyzed code, its code runs as a +[cascade](#plugin-cascades). A custom API that is only in the catalog is reported as unresolved, +because its code isn't analyzed. + +### Lookups + +A lookup set on a record that is created or updated, directly or through a request such as `Upsert` or +`CreateMultiple`, needs Append on the record's table and AppendTo on the table the lookup refers to. +Lookups are found where the code sets them: early-bound properties (`order.CustomerId = …`), indexers +(`entity["parentcustomerid"] = …`) and `Attributes.Add`, on new records and on records passed in from +callers. `ownerid` and lookups set to `null` need nothing. + +The referenced table comes from the `EntityReference` value, like any other table. When it can't be +resolved, the lookup's targets in the entity metadata (`*Metadata.xml` in the metadata folder) are used: +the only target of a simple lookup, or every target of a polymorphic one such as a customer lookup, with +basis `all-lookup-targets`. Without metadata such a lookup is reported as unresolved. + +The analysis only sees lookups set in the code. A record retrieved and written back unchanged, or one +from a source it can't follow, adds no Append or AppendTo. + +### Plugin cascades + +An operation also runs the plugin steps registered for its message and table, and those steps need +their privileges in the same request. Each entry point therefore includes the requirements of every +step its operations fire, and of the steps those fire in turn, listed after `fires:` under the entry +point. Steps come from code registrations and from the plugin steps in the metadata: + +- A step runs as the identity of the operation that fired it, such as the application user of an + Azure Function or the user it acts for through `CallerId`, unless the step impersonates a user. +- `Create`, `Update`, `Delete`, `Retrieve`, `RetrieveMultiple`, `Associate` and `Disassociate` fire their + own message. A request fires its message on its `Target` table, and the messages it runs as: + `Upsert` also fires `Create` and `Update`, and `CreateMultiple` also fires `Create`. A request that + closes a record, such as `WinOpportunity` or `CloseIncident`, fires on the record, not on the close + activity it creates, and `WinOpportunity` and `WinQuote` fire `Win` steps, `LoseOpportunity` and + `CloseQuote` fire `Lose` steps, as in XrmMockup. +- A step without a table fires for every table. An operation on a table that can't be resolved fires + only those: the steps on a table are reported as unresolved ("may fire any of 12 Update steps"), + because including every step of the message would include most of the solution and tell nothing. +- An operation on a polymorphic lookup's targets fires the steps of each target, with basis + `all-lookup-targets`. +- An Update step with filtered attributes, from `.AddFilteredAttributes(…)` or the metadata, fires + only for an update that sets one of them. The columns set are read from early-bound properties, + indexers and `Attributes.Add` on the entity, or on the `Target` of a request, and followed into + helpers it is passed to. When they can't all be determined, such as for a retrieved entity, the + plugin's `Target`, a column name computed at runtime, or an entity passed to a method that can + set more, the step fires with basis `filter-unknown`. +- A call to a custom API implemented in the analyzed code runs that code. +- A request with `BypassCustomPluginExecution` set to `true` doesn't run synchronous steps, and one with + `BypassBusinessLogicExecution` doesn't run the synchronous (`CustomSync`) or asynchronous + (`CustomAsync`) steps it names. A step's mode comes from `.SetExecutionMode(…)` or the metadata. + Steps are still run when the value is set at runtime, and for `BypassBusinessLogicExecutionStepIds`, + because the analysis doesn't know step ids. A custom API's own code always runs. +- A metadata step whose plugin code isn't loaded is reported as unresolved, so missing plugin code is + never treated as needing nothing. Load it with `--plugin-solution` when it's in another solution. +- The workflows in `Metadata/Workflows` that run automatically fire like steps: on create, on delete, + or on an update that sets one of their columns. Their steps aren't analyzed, so each one an + operation fires is reported as unresolved ("fires real-time workflow 'Set credit limit', whose steps + aren't analyzed"), and `--strict` fails on it. A real-time workflow runs as the caller or its owner, + as set on it, and a background workflow as its owner. Bypass parameters skip them like steps. +- Each step is expanded once per identity, so steps that fire each other don't loop. + +The source path of a cascaded requirement runs from the entry point through the operation (such as +`Create contact`) and the step id into the step's code. The JSON output lists a step's filter as +`filteredAttributes` on its trigger. + +#### Plugin code in another solution + +A function app or integration rarely references the plugin projects, so the steps it fires have no +code in its solution. Add the solutions or projects with the plugin code with `--plugin-solution`, or +`PluginSolutions` in the configuration: + +```bash +xrmmockup-permissions -s ./src/Contoso.Functions/Contoso.Functions.csproj -m ./tests/Metadata \ + --plugin-solution ../Contoso.Plugins/Contoso.Plugins.sln +``` + +Their code is used for the steps the analyzed code fires, and their files are shown relative to the +analyzed solution, such as `../Contoso.Plugins/AccountPlugin.cs:12`. Their own entry points, and +their methods that no entry point reaches, aren't listed, unless a scope such as `--plugin` selects +one. `ExcludeProjects` applies to them as well, with path patterns relative to their own solution. + +### User operations + +`--operation "
"` answers "what does a user need to do this", such as updating an +account in an app. The operation runs as `Caller` and needs the privileges of its request rule (see +[Request rules](#request-rules)) on the table, plus those of every plugin step it fires: + +```bash +xrmmockup-permissions --operation "Update account" --attributes name,statecode +xrmmockup-permissions --operation "Create contact" --attributes parentcustomerid --role "Salesperson" +``` + +- The message may be any message with a rule, such as `Create`, `Update`, `Delete`, `Assign` or + `Upsert`, which fires the steps of `Create` and `Update` too. A message without a rule, such as a + custom API, is reported as unresolved, but still fires the steps registered on it. +- `--attributes` are the columns the operation sets. They decide which Update steps filtered on + columns fire. Without them, those steps fire with basis `filter-unknown`. +- A lookup column among them needs `Append` on the table and `AppendTo` on the tables it can refer + to, from the metadata (`all-lookup-targets` when there are several). +- Request members other than the table, such as `RelatedEntities` of `Associate`, and access rights + granted by `GrantAccess`, aren't known and are reported as unresolved. + +Requirements of the operation itself have the source `--operation`; those of a step it fires have the +step's code, with a path that starts at the operation. + +Calls inside lambdas and local functions count towards the method that contains them. A generic +helper or generic class method that no entry point calls is listed under unreached methods with its +type parameter as the unresolved reason. + +## Configuration + +The tool reads the same `appsettings.json` as `xrmmockup-metadata`. Its settings are under +`XrmMockup:Permissions`. Note that `Solution` (and `-s`) here is the path of a `.sln` or `.csproj` +file, while `XrmMockup:Metadata:Solutions` (and `-s` in `xrmmockup-metadata`) are Dataverse solution +names: + +```json +{ + "XrmMockup": { + "Metadata": { + "OutputDirectory": "./Metadata" + }, + "Permissions": { + "Solution": "./src/Contoso.sln", + "MetadataDirectory": "./tests/Metadata", + "ExcludeProjects": ["*.Tests", "tests/*"], + "PluginSolutions": ["../Contoso.Plugins/Contoso.Plugins.sln"], + "EntryPoints": ["Contoso.Sync.Importer.Run"], + "Principals": { + "Contoso.Functions": { "Roles": ["Integration App"] }, + "Contoso.Functions/ProcessOrder": { "Roles": ["Integration App", "Order Processor"] } + }, + "Users": { + "6a1e5c4d-2b3f-4a5e-8c7d-9e0f1a2b3c4d": { "Name": "svc-plugins", "Roles": ["Plugin Service"] } + }, + "Suppress": [ + { "Table": "ctx_auditlog", "Privilege": "Create", "Reason": "Created by SYSTEM via helper" }, + { "Privilege": "prvActOnBehalfOfAnotherUser", "Reason": "Granted by the integration team" } + ], + "Rules": [ + { "Message": "ctx_Approve", "Target": "Target", "Privileges": ["Write"] } + ] + } + } +} +``` + +| Setting | Description | +|---------|-------------| +| `Solution` | Solution or project to analyze. Without it, the tool uses the single `.sln`/`.slnx` in the current directory | +| `MetadataDirectory` | Metadata folder. Defaults to `XrmMockup:Metadata:OutputDirectory`, then `./Metadata` when it exists | +| `ExcludeProjects` | Projects to leave out, such as test projects. See below | +| `PluginSolutions` | Solutions or projects with plugin code that the analyzed code fires, used for plugin cascades only. `--plugin-solution` adds to these. See [Plugin code in another solution](#plugin-code-in-another-solution) | +| `EntryPoints` | Extra methods to analyze as entry points, by full name, such as code called from outside the solution. `--entry` adds a method to these and also limits the report to the `--entry` methods. A name that matches no method is reported as a warning | +| `Principals` | The application user's roles per function app, by assembly name, or per function as `/` (which wins). Used when `--role` isn't given. A key that matches no analyzed assembly or function is logged as a warning | +| `Users` | The roles of specific users by user id (the `systemuserid`, in any GUID format), such as the impersonating user of a plugin step or the owner of a background workflow. `Name` is shown in the output. A key that isn't a GUID is an error, and one no analyzed operation runs as is logged as a warning | +| `Suppress` | Missing privileges to accept, with the reason. Leave out `Privilege` to accept every privilege on the table, or leave out `Table` to accept a privilege not tied to a table by its name. Suppressed privileges are shown but don't fail `--fail-on-missing` | +| `Rules` | Rules for requests passed to `Execute`, which replace the built-in rule for their message or add one. See below | + +Configured paths are relative to the configuration file. `appsettings.{DOTNET_ENVIRONMENT}.json` and +environment variables (for example `XrmMockup__Permissions__Solution`) override the file, and +command-line options override everything. + +### Request rules + +Each rule names the `Message` (`ctx_Approve`, or a request type such as `AssignRequest`) and what it +needs. A message is matched to a rule by its own name first, ignoring case, so a custom API named +`ctx_ApproveRequest` doesn't use the rule for `ctx_Approve`: + +```json +"Rules": [ + { "Message": "ctx_Approve", "Target": "Target", "Privileges": ["Write"] }, + { "Message": "ctx_ApproveMultiple", "Targets": "Targets", "As": ["ctx_Approve"] }, + { "Message": "ctx_Share", "Target": "Target", "Privileges": ["Share", "$Access"] }, + { "Message": "ctx_Close", "Checks": [{ "Table": "task", "Privileges": ["Create"], "When": "CreateTask" }] }, + { "Message": "ctx_Ping" } +] +``` + +| Field | Description | +|-------|-------------| +| `Target`, `Privileges` | The privileges needed on the table of the request member `Target` names. `$Member` adds the rights an `AccessRights` member grants | +| `Checks` | Further checks, each on a request `Member` or a fixed `Table`, with `Privileges` and an optional boolean `When` member that must be set | +| `As` | Messages whose checks the request makes as well | +| `Targets` | A member holding several targets; the `As` rules' checks on `Target` apply to it | +| `Requests` | A member holding requests that run as part of this one | +| `GlobalPrivileges` | Privileges the request needs by name, such as `prvBulkDelete`, looked up in the privilege catalog as above | +| `Assumption` | What the analysis assumes about the request, listed under assumptions wherever it is called | +| `Enforced` | `false` when XrmMockup doesn't make the checks (Dataverse still does) | +| `FiresOn` | The table the request's plugin steps fire on, when it isn't that of its first member check, as for `WinOpportunity`, which creates an `opportunityclose` but fires on `opportunity` | +| `StepMessage` | The message the request's plugin steps are registered on, when it isn't the request's own, as `Win` for `WinOpportunity` | + +A rule with none of these needs no privilege, so its requests are no longer reported. + +### Excluding projects + +Test projects call the organization service too, but those calls aren't what your users need +privileges for. Leave them out with patterns in `ExcludeProjects`, `--exclude`, or both; the +command line adds to the configured patterns: + +```bash +xrmmockup-permissions -x "*.Tests" -x "tests/*" +``` + +- `*` matches any characters and `?` matches one. Matching is case-insensitive. +- A pattern without a slash matches the project name, which is the file name without `.csproj`: `*.Tests`, `Contoso.IntegrationTests`. +- A pattern with a slash matches the project path relative to the solution: `tests/*`. +- A pattern that matches no project is reported as a warning, because it's probably a typo. + +Excluded projects are not compiled, so excluding them also makes the run faster. + +### .NET Framework projects + +Projects that target .NET Framework, such as plugin projects, need its reference assemblies. Windows +has them from the Developer Packs. Elsewhere, the analyzer uses the +`Microsoft.NETFramework.ReferenceAssemblies.net*` packages in the NuGet cache (`NUGET_PACKAGES` or +`~/.nuget/packages`), which a restore of an SDK-style project targeting .NET Framework downloads. +Set `TargetFrameworkRootPath` to use another folder. + +Strong-name signing is ignored, so a key file that isn't checked in doesn't stop the analysis. + +## Security roles + +The metadata folder is also where plugin step registrations are read from (`Metadata.xml`). + +When the metadata folder contains `SecurityRoles/`, the output also lists the required tables that no +role mentions. XrmMockup doesn't check privileges on those tables, so tests pass even when no role +grants them. `--role`, `--caller-role` and the roles in `Principals` and `Users` are looked up in this folder, by name. + +## Output + +### Detail and filters + +On a real solution most requirements are already granted, so the text report starts with only what +to change, and `--detail` shows more: + +| Level | Shows | +|-------|-------| +| `minimal` (default) | Only the privileges to change: a block per set of roles with what it lacks, merged over every entry point and identity, a line per table so a role can be changed one table at a time. Requirements that weren't checked or are unverifiable get blocks of their own. Without roles, a block per identity with every privilege it needs, except SYSTEM. Ends with the counts, `Result` and `Not checked` | +| `compact` | Also, under each block, the entry points and methods that need its privileges, those that need the same ones listed together | +| `normal` | Requirements the roles don't grant (`✘`), that weren't checked or are unverifiable (`·`), and unresolved operations (`?`). An entry point or method with none of these is left out. Without roles nothing is granted, so every requirement is shown, with `Privileges per table`. Up to three source locations per requirement, without call paths | +| `detailed` | Also the requirements that are granted, not governed, suppressed or run as SYSTEM, every entry point and method, assumptions (`~`), the steps each entry point fires and `Privileges per table` | +| `full` | Also every source location with its call path | + +For three functions run by an app user, `compact` shows the changes to make to `Integration App`, +and then what each is for: + +```text +Missing from Integration App (--role), for ApplicationUser: + account Write + annotation Create, Append + contact Read + salesorder Read + + By entry point: + + function:Contoso.Functions/CancelOrder + function:Contoso.Functions/SubmitOrder + annotation Create, Append + contact Read + salesorder Read + + function:Contoso.Functions/ProcessOrder + account Write + +3 entry points, 0 unreached methods, 4 tables, 8 table privileges (15 requirements counted per entry point and method), 0 unresolved +Result: 6 granted, 9 missing +Not shown: sources and requirements with nothing to fix. --detail normal adds the sources, detailed everything +``` + +`minimal` stops before `By entry point`. + +The last line says what the level left out, such as `Not shown: 242 requirements with nothing to fix, +73 assumptions`. The counts, `Result`, `Not checked` and the exit code are always those of the whole +analysis. + +`--table`, `--privilege`, `--runs-as` and `--basis` narrow the report, for example to answer why a +function needs `Write` on `account`: + +```bash +xrmmockup-permissions --function ProcessOrder --role "Integration App" --table account --privilege Write --detail full +``` + +Each takes several values, comma-separated or repeated, and matches any of them ignoring case; +different filters combine. `--runs-as` takes `Caller`, `User`, `ApplicationUser`, `ImpersonatedCaller` +or `System`, and `--basis` takes `direct`, `execute-privilege`, `all-implementations`, +`all-lookup-targets` or `filter-unknown`. A privilege not tied to a table has no table, so `--table` +leaves it out; it matches `--privilege` by name. An unresolved operation has no known table or basis, +so only `--runs-as` and `--privilege` apply to it. `Missing privileges` lists only the privileges that a +requirement matching the filters is missing. Filters apply after analysis: a line such as +`Filtered by --table account: 12 of 270 requirements match` says how much matched, and nothing that is +computed, counted or checked changes. In particular, filters never change the exit code or the error +`--fail-on-missing` and `--strict` log: a privilege the filters hide still fails the run. + +### JSON + +`--format json` writes the same content as an object with `entryPoints` (each with its `id`, `kind`, +`trigger`, `requirements`, `unresolved`, `assumptions` and `triggers`, the ids of the steps it fires), +`unreached` and `notRoleGoverned`. JSON is complete at every `--detail`, with every source and +call path. Filters narrow it like the text: requirements and unresolved operations they don't match +are left out, so are entry points and methods left without any, and `missing` lists only what a matching +requirement is missing. `result` stays the count of the whole analysis. +Requirements carry `table`, `privilege`, `runsAs`, `basis` and their `sources`, each with the call +`path` from the entry point. A privilege not tied to a table has no `table`, and its name as +`privilege`. + +With roles, each requirement also has `coverage` (`status`: `granted`, `not-governed`, `missing`, +`suppressed`, `not-checked`, `system` or `unverifiable`, with `depth` or `reason`), each entry point has `roles` (the +roles per identity, with their `origin`), and the document +has a `result` with the counts, `unresolvedNoRule`, `unresolvedCustomApi` and `unresolvedWorkflow` (the +unresolved operations that are requests without a rule, custom API calls and fired workflows), `truncated` (the +entry points and methods whose analysis stopped at the call limit) and `incomplete` (whether anything wasn't checked), and `missing` lists each missing privilege +with `table` (left out for a privilege not tied to a table), `privilege`, `runsAs`, `roles`, `origin` and `in` (the entry points and methods that need +it). Without roles, none of these are written. + +### Markdown + +`--format markdown` writes the report as GitHub-flavored Markdown, for a pull request comment or a +job summary: a heading with the number of privileges the roles lack (`✘ 6 missing privileges`, each counted once as in `Missing privileges`), the `Result` line and the +`Not checked` line as a warning, then a table per set of roles with what it lacks, as in `minimal`. +The entry points that need each block's privileges, as in `compact`, and the unresolved operations +are folded away in `
`. It ends with the counts. Markdown ignores `--detail`; filters +narrow it like the text. Role names, reasons and ids are escaped and put on one line, so they show as written and can't +add Markdown of their own. + +```yaml +- run: xrmmockup-permissions --fail-on-missing --format markdown --output permissions.md +- run: cat permissions.md >> "$GITHUB_STEP_SUMMARY" + if: always() +``` + +### SARIF + +`--format sarif` writes the findings as [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html), +for GitHub code scanning and editors that show SARIF, so they appear on the line that needs the +privilege. Each call site is a result, merged over the entry points that reach it, which are its +related locations: + +| Rule | Level | Result | +|------|-------|--------| +| `missing-privilege` | error | A privilege the roles lack. A suppressed one has a `suppressions` entry with the reason, so code scanning shows it as dismissed | +| `unresolved-operation` | warning | An operation whose table or request isn't known, except as SYSTEM, which needs no role | +| `not-checked` | note | A privilege of an identity without roles | +| `unverifiable` | note | A privilege not tied to a table that the role metadata predates | + +Without roles, only unresolved operations are results. Filters narrow it; `--detail` doesn't +apply. Each result has `properties` with the `table`, `privilege`, `runsAs`, `roles` and +`entryPoints`. Locations are relative to `%SRCROOT%`, the root of the git repository the solution +is in, so code scanning finds the files; outside a repository they are relative to the solution. + +```yaml +- run: xrmmockup-permissions --fail-on-missing --format sarif --output permissions.sarif +- uses: github/codeql-action/upload-sarif@v4 + if: always() + with: + sarif_file: permissions.sarif +``` + +### Determinism + +Output is deterministic: entry points, methods, tables and source locations are sorted ordinally, paths are +relative to the analyzed solution with forward slashes, and line endings are always `\n`. Running +the tool twice on the same code gives byte-identical output, so it can be committed and diffed in CI. + +For a multi-targeted project, the report combines the requirements of all loaded target frameworks. +A shared call site can resolve to different tables or service identities in each framework, including +through helper arguments, return values, generic types and constructor fields; those alternatives +are retained. Duplicate findings are merged, independent of compilation order. The report does not +attribute requirements to individual target frameworks. diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Tool/ToolLogging.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/ToolLogging.cs new file mode 100644 index 00000000..0221458e --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Tool/ToolLogging.cs @@ -0,0 +1,18 @@ +using Microsoft.Extensions.Logging; +using XrmMockup.Tools.Common.Logging; + +namespace XrmMockup.PermissionAnalyzer.Tool; + +internal static class ToolLogging +{ + /// + /// Logs go to standard error, so a report written to standard output can be piped as is. + /// + public static ILoggerFactory Create() => LoggerFactory.Create(builder => builder + .AddShortCategoryConsole(options => + { + options.StandardError = true; + options.TimestampFormat = "HH:mm:ss "; + }) + .AddFilter("Microsoft", LogLevel.Warning)); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Commands/RuleSetup.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Commands/RuleSetup.cs new file mode 100644 index 00000000..0c2a4fa0 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Commands/RuleSetup.cs @@ -0,0 +1,93 @@ +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Options; + +namespace XrmMockup.PermissionAnalyzer.Tool.Commands; + +/// +/// Turns the configured request rules into s. Mistakes are errors that name the setting. +/// +internal static class RuleSetup +{ + public static IReadOnlyList Create(PermissionsConfiguration configuration) => + configuration.Rules.Select(Rule).ToList(); + + private static RequestRule Rule(RuleConfiguration rule, int index) + { + var setting = $"{PermissionsConfiguration.SectionPath}:Rules:{index}"; + if (string.IsNullOrWhiteSpace(rule.Message)) throw new ToolException($"{setting} has no Message"); + + var checks = new List(); + if (rule.Privileges.Length > 0) + { + if (string.IsNullOrWhiteSpace(rule.Target)) throw new ToolException($"{setting} has Privileges but no Target"); + checks.Add(Check(rule.Privileges, setting) with { Member = rule.Target.Trim() }); + } + checks.AddRange(rule.Checks.Select((check, i) => Check(check, $"{setting}:Checks:{i}"))); + + return new RequestRule(rule.Message.Trim()) + { + Checks = checks, + As = rule.As.Select(a => a.Trim()).ToList(), + Targets = Blank(rule.Targets), + Requests = Blank(rule.Requests), + GlobalPrivileges = GlobalPrivileges(rule.GlobalPrivileges, setting), + Assumption = Blank(rule.Assumption), + Enforced = rule.Enforced ?? true, + FiresOn = Blank(rule.FiresOn)?.ToLowerInvariant(), + StepMessage = Blank(rule.StepMessage), + }; + } + + private static IReadOnlyList GlobalPrivileges(IEnumerable privileges, string setting) + { + var names = privileges.Select(p => p?.Trim() ?? "").ToList(); + if (names.Any(n => n.Length == 0)) throw new ToolException($"{setting} has an empty GlobalPrivileges entry"); + return names.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + } + + private static RuleCheck Check(RuleCheckConfiguration check, string setting) + { + var member = Blank(check.Member); + var table = Blank(check.Table); + if ((member is null) == (table is null)) throw new ToolException($"{setting} needs either a Member or a Table"); + if (check.Privileges.Length == 0) throw new ToolException($"{setting} has no Privileges"); + + return Check(check.Privileges, setting) with { Member = member, Table = table?.ToLowerInvariant(), When = Blank(check.When) }; + } + + private static RuleCheck Check(IEnumerable privileges, string setting) + { + var parsed = new List(); + string? accessMask = null; + foreach (var text in privileges.Select(p => p.Trim())) + { + if (text.StartsWith('$')) + { + if (accessMask is not null) throw new ToolException($"{setting} has more than one $ privilege"); + accessMask = text.Substring(1); + if (accessMask.Length == 0) throw new ToolException($"{setting} has a $ privilege without a member"); + } + else if (ParsePrivilege(text) is { } privilege) + { + if (!parsed.Contains(privilege)) parsed.Add(privilege); + } + else + { + throw new ToolException( + $"{setting} has an unknown privilege '{text}'. Use one of {PrivilegeNames}, " + + "or $Member for the rights a member grants"); + } + } + return new RuleCheck(parsed) { AccessMask = accessMask }; + } + + /// + /// A table privilege by name, ignoring case; null for any other text, numbers included. + /// + internal static Privilege? ParsePrivilege(string text) => + Enum.TryParse(text.Trim(), ignoreCase: true, out var privilege) && Enum.IsDefined(privilege) ? privilege : null; + + internal static string PrivilegeNames { get; } = string.Join(", ", Enum.GetNames()); + + private static string? Blank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/LookupLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/LookupLoader.cs new file mode 100644 index 00000000..f43d7ca4 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/LookupLoader.cs @@ -0,0 +1,26 @@ +using Microsoft.Xrm.Sdk.Metadata; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Metadata; + +/// +/// Turns the entity metadata that reads into lookup columns. +/// +internal static class LookupLoader +{ + /// + /// Every lookup column with the tables it can refer to, sorted by table and column. + /// + internal static IReadOnlyList Convert(IEnumerable entities) => + entities + .Where(e => !string.IsNullOrEmpty(e.LogicalName)) + .SelectMany(e => (e.Attributes ?? []) + .OfType() + .Where(a => !string.IsNullOrEmpty(a.LogicalName) && a.Targets is { Length: > 0 }) + .Select(a => new LookupColumn(e.LogicalName, a.LogicalName, a.Targets.OrderBy(t => t, StringComparer.Ordinal).ToList()))) + .GroupBy(c => (c.Table, c.Column)) + .Select(g => g.First()) + .OrderBy(c => c.Table, StringComparer.Ordinal) + .ThenBy(c => c.Column, StringComparer.Ordinal) + .ToList(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/MetadataFileLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/MetadataFileLoader.cs new file mode 100644 index 00000000..ddda6239 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/MetadataFileLoader.cs @@ -0,0 +1,83 @@ +using System.Runtime.Serialization; +using System.Xml; +using XrmMockup.PermissionAnalyzer.Workspace.Serialization; +using Microsoft.Xrm.Sdk.Metadata; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Metadata; + +/// +/// What the analysis uses of Metadata/Metadata.xml, written by the metadata tool, and of the other +/// *Metadata.xml files that XrmMockup merges into it. +/// +/// The lookup columns, from the entity metadata of every file. +/// The plugin steps, from Metadata.xml. +internal sealed record MetadataFileContents(IReadOnlyList Lookups, IReadOnlyList PluginSteps); + +/// +/// Reads the metadata files in one pass each. A file can be hundreds of megabytes, almost all of it entity metadata, +/// so only the EntityMetadata and Plugins elements are deserialized and the rest is skipped. +/// +internal static class MetadataFileLoader +{ + public const string MetadataFile = "Metadata.xml"; + + // The data contract namespace of the XrmMockup metadata files + internal const string Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup"; + + private const string EntityMetadataElement = "EntityMetadata"; + private const string PluginsElement = "Plugins"; + + /// + /// The lookup columns and plugin steps in the metadata folder. Empty when there's no metadata file. + /// + public static MetadataFileContents Load(string metadataDirectory) + { + if (!Directory.Exists(metadataDirectory)) return new([], []); + + var entitySerializer = new DataContractSerializer(typeof(Dictionary), EntityMetadataElement, Namespace); + var pluginSerializer = new DataContractSerializer(typeof(List), PluginsElement, Namespace); + // As in XrmMockup, the main file goes first and an entity that an earlier file has is ignored + var entities = new Dictionary(); + var plugins = new List(); + var files = Directory.GetFiles(metadataDirectory, "*" + MetadataFile) + .OrderBy(f => Path.GetFileName(f) == MetadataFile ? 0 : 1) + .ThenBy(f => f, StringComparer.Ordinal); + foreach (var file in files) + { + // Plugin steps only come from the main file, as in XrmMockup + var withPlugins = Path.GetFileName(file) == MetadataFile; + using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); + using var reader = XmlReader.Create(stream, new XmlReaderSettings { IgnoreWhitespace = true }); + if (reader.MoveToContent() != XmlNodeType.Element || reader.IsEmptyElement) continue; + + reader.ReadStartElement(); + bool readEntities = false, readPlugins = !withPlugins; + while (!(readEntities && readPlugins) && reader.MoveToContent() == XmlNodeType.Element) + { + if (reader.NamespaceURI != Namespace) + { + reader.Skip(); + } + else if (reader.LocalName == EntityMetadataElement) + { + if (entitySerializer.ReadObject(reader) is Dictionary metadata) + { + foreach (var entity in metadata) entities.TryAdd(entity.Key, entity.Value); + } + readEntities = true; + } + else if (reader.LocalName == PluginsElement && withPlugins) + { + if (pluginSerializer.ReadObject(reader) is List steps) plugins.AddRange(steps); + readPlugins = true; + } + else + { + reader.Skip(); + } + } + } + return new(LookupLoader.Convert(entities.Values), PluginStepLoader.Convert(plugins)); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/PluginStepLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/PluginStepLoader.cs new file mode 100644 index 00000000..8daf23fd --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/PluginStepLoader.cs @@ -0,0 +1,49 @@ +using XrmMockup.PermissionAnalyzer.Workspace.Serialization; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Metadata; + +/// +/// Turns the plugin steps that reads into registrations. +/// +internal static class PluginStepLoader +{ + // The mode of an sdkmessageprocessingstep: 0 is synchronous, 1 asynchronous + private const int AsynchronousMode = 1; + + /// + /// The plugin steps with a plugin type and message, sorted by type, message, table and stage. + /// + internal static IReadOnlyList Convert(IEnumerable plugins) => + plugins + .Where(p => !string.IsNullOrEmpty(p.AssemblyName) && !string.IsNullOrEmpty(p.MessageName)) + .Select(p => new PluginStepRegistration( + p.AssemblyName, + string.IsNullOrEmpty(p.PluginTypeAssemblyName) ? null : p.PluginTypeAssemblyName, + p.MessageName, + string.IsNullOrEmpty(p.PrimaryEntity) || p.PrimaryEntity == "none" ? null : p.PrimaryEntity, + p.Stage, + p.ImpersonatingUserId?.ToString(), + FilteredAttributes(p.FilteredAttributes), + p.Mode == AsynchronousMode)) + .OrderBy(s => s.TypeName, StringComparer.Ordinal) + .ThenBy(s => s.Message, StringComparer.Ordinal) + .ThenBy(s => s.Table, StringComparer.Ordinal) + .ThenBy(s => s.Stage) + .ToList(); + + /// + /// The comma-separated columns a step is filtered on, lowercased and sorted; null for none. + /// + private static IReadOnlyList? FilteredAttributes(string? attributes) + { + var columns = (attributes ?? "") + .Split(',') + .Select(a => a.Trim().ToLowerInvariant()) + .Where(a => a.Length > 0) + .Distinct(StringComparer.Ordinal) + .OrderBy(a => a, StringComparer.Ordinal) + .ToList(); + return columns.Count > 0 ? columns : null; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/PrivilegeCatalogLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/PrivilegeCatalogLoader.cs new file mode 100644 index 00000000..18a79cb3 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/PrivilegeCatalogLoader.cs @@ -0,0 +1,48 @@ +using System.Runtime.Serialization; +using XrmMockup.PermissionAnalyzer.Workspace.Serialization; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Metadata; + +/// +/// Reads Metadata/PrivilegeCatalog.xml, written by the metadata tool: every privilege by name, and the execute +/// privileges of the custom APIs. +/// +internal static class PrivilegeCatalogLoader +{ + public const string FileName = "PrivilegeCatalog.xml"; + + /// + /// The privileges and custom APIs, sorted by name, or null when the metadata folder has no catalog. + /// + public static (IReadOnlyList Privileges, IReadOnlyList CustomApis)? Load(string metadataDirectory) + { + var path = Path.Combine(metadataDirectory, FileName); + if (!File.Exists(path)) return null; + + PrivilegeCatalog catalog; + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + { + catalog = new DataContractSerializer(typeof(PrivilegeCatalog)).ReadObject(stream) as PrivilegeCatalog + ?? throw new ToolException($"Not a privilege catalog: {path}"); + } + return (Convert(catalog.Privileges ?? []), Convert(catalog.CustomApis ?? [])); + } + + internal static IReadOnlyList Convert(IEnumerable privileges) => + privileges + .Where(p => !string.IsNullOrEmpty(p.Name)) + .Select(p => new PrivilegeDefinition( + p.Name, + RoleLoader.ToPrivilege(p.AccessRight), + (p.Tables ?? []).Select(t => t.ToLowerInvariant()).Distinct(StringComparer.Ordinal).OrderBy(t => t, StringComparer.Ordinal).ToList())) + .OrderBy(p => p.Name, StringComparer.Ordinal) + .ToList(); + + internal static IReadOnlyList Convert(IEnumerable customApis) => + customApis + .Where(a => !string.IsNullOrEmpty(a.UniqueName)) + .Select(a => new CustomApiDefinition(a.UniqueName, string.IsNullOrEmpty(a.ExecutePrivilegeName) ? null : a.ExecutePrivilegeName)) + .OrderBy(a => a.UniqueName, StringComparer.Ordinal) + .ToList(); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/RoleLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/RoleLoader.cs new file mode 100644 index 00000000..58e6ddcb --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/RoleLoader.cs @@ -0,0 +1,85 @@ +using System.Runtime.Serialization; +using XrmMockup.PermissionAnalyzer.Workspace.Serialization; +using Microsoft.Crm.Sdk.Messages; +using XrmMockup.PermissionAnalyzer.Core.Model; +using CrmDepth = Microsoft.Crm.Sdk.Messages.PrivilegeDepth; +using PrivilegeDepth = XrmMockup.PermissionAnalyzer.Core.Model.PrivilegeDepth; + +namespace XrmMockup.PermissionAnalyzer.Tool.Metadata; + +/// +/// Reads the security roles in Metadata/SecurityRoles, written by the metadata tool, the same way XrmMockup +/// does. +/// +internal static class RoleLoader +{ + public const string SecurityRolesFolder = "SecurityRoles"; + + /// + /// Every role in the metadata folder, sorted by name. Empty when the folder has no security roles. + /// + public static IReadOnlyList Load(string metadataDirectory) + { + var directory = Path.Combine(metadataDirectory, SecurityRolesFolder); + if (!Directory.Exists(directory)) return []; + + var serializer = new DataContractSerializer(typeof(SecurityRole)); + // Files in name order, so copies of a role with the same name always come in the same order + return Directory.GetFiles(directory, "*.xml") + .Order(StringComparer.Ordinal) + .Select(file => + { + using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); + var role = serializer.ReadObject(stream) as SecurityRole + ?? throw new ToolException($"Not a security role: {file}"); + return Convert(role); + }) + .OrderBy(r => r.Name, StringComparer.Ordinal) + .ToList(); + } + + internal static RoleDefinition Convert(SecurityRole role) + { + var privileges = new SortedDictionary>(StringComparer.Ordinal); + foreach (var (table, rights) in role.Privileges ?? []) + { + var granted = new SortedDictionary(); + foreach (var (right, privilege) in rights) + { + if (ToPrivilege(right) is { } mapped) granted[mapped] = ToDepth(privilege.PrivilegeDepth); + } + privileges[table] = granted; + } + + // Metadata from before global privileges were downloaded has none, which is not the same as granting none + SortedDictionary? globalPrivileges = null; + if (role.GlobalPrivileges is { } globals) + { + globalPrivileges = new SortedDictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (name, privilege) in globals) globalPrivileges[name] = ToDepth(privilege.PrivilegeDepth); + } + return new RoleDefinition(role.Name, privileges, globalPrivileges); + } + + internal static Privilege? ToPrivilege(AccessRights right) => right switch + { + AccessRights.CreateAccess => Privilege.Create, + AccessRights.ReadAccess => Privilege.Read, + AccessRights.WriteAccess => Privilege.Write, + AccessRights.DeleteAccess => Privilege.Delete, + AccessRights.AppendAccess => Privilege.Append, + AccessRights.AppendToAccess => Privilege.AppendTo, + AccessRights.AssignAccess => Privilege.Assign, + AccessRights.ShareAccess => Privilege.Share, + _ => null, + }; + + // XrmMockup treats RecordFilter like Global (Security.HasPermission), so it maps to Organization here too. + private static PrivilegeDepth ToDepth(CrmDepth depth) => depth switch + { + CrmDepth.Basic => PrivilegeDepth.User, + CrmDepth.Local => PrivilegeDepth.BusinessUnit, + CrmDepth.Deep => PrivilegeDepth.ParentChildBusinessUnit, + _ => PrivilegeDepth.Organization, + }; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/WorkflowLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/WorkflowLoader.cs new file mode 100644 index 00000000..bfa3602d --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Metadata/WorkflowLoader.cs @@ -0,0 +1,83 @@ +using System.Runtime.Serialization; +using Microsoft.Xrm.Sdk; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Metadata; + +/// +/// Reads the workflows in Metadata/Workflows, written by the metadata tool, the same way XrmMockup does. Only +/// the workflows that run automatically are kept, since operations can only fire those. +/// +internal static class WorkflowLoader +{ + public const string WorkflowsFolder = "Workflows"; + + // The category of a workflow, as opposed to an action (3) or a business rule + private const int WorkflowCategory = 0; + + // The mode of a workflow: 0 is background, 1 real-time + private const int RealTimeMode = 1; + + // Who a real-time workflow runs as: 0 is its owner, 1 the calling user + private const int CallingUser = 1; + + /// + /// Every workflow in the metadata folder that runs on a table, sorted by name. Empty when the folder has none. + /// + public static IReadOnlyList Load(string metadataDirectory) + { + var directory = Path.Combine(metadataDirectory, WorkflowsFolder); + if (!Directory.Exists(directory)) return []; + + var serializer = new DataContractSerializer(typeof(Entity)); + return Directory.GetFiles(directory, "*.xml") + .Order(StringComparer.Ordinal) + .Select(file => + { + using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read); + return serializer.ReadObject(stream) as Entity + ?? throw new ToolException($"Not a workflow: {file}"); + }) + .Select(Convert) + .OfType() + .OrderBy(w => w.Name, StringComparer.Ordinal) + .ThenBy(w => w.Table, StringComparer.Ordinal) + .ToList(); + } + + /// + /// The workflow describes; null when it isn't a workflow or no operation runs it. + /// + internal static WorkflowRegistration? Convert(Entity entity) + { + if (entity.LogicalName != "workflow" || entity.GetAttributeValue("category")?.Value != WorkflowCategory) return null; + + var table = entity.GetAttributeValue("primaryentity"); + if (string.IsNullOrEmpty(table) || table == "none") return null; + + var onCreate = entity.GetAttributeValue("triggeroncreate") == true; + var onDelete = entity.GetAttributeValue("triggerondelete") == true; + var columns = (entity.GetAttributeValue("triggeronupdateattributelist") ?? "") + .Split(',') + .Select(c => c.Trim().ToLowerInvariant()) + .Where(c => c.Length > 0) + .Distinct(StringComparer.Ordinal) + .OrderBy(c => c, StringComparer.Ordinal) + .ToList(); + if (!onCreate && !onDelete && columns.Count == 0) return null; + + // A background workflow always runs as its owner + var realTime = entity.GetAttributeValue("mode")?.Value == RealTimeMode; + var asCaller = realTime && entity.GetAttributeValue("runas")?.Value == CallingUser; + var owner = asCaller ? null : entity.GetAttributeValue("ownerid")?.Id.ToString(); + + return new WorkflowRegistration( + entity.GetAttributeValue("name") ?? entity.Id.ToString(), + table, + onCreate, + onDelete, + columns.Count > 0 ? columns : null, + realTime, + owner); + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/AnalysisSettings.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/AnalysisSettings.cs new file mode 100644 index 00000000..b8b66425 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/AnalysisSettings.cs @@ -0,0 +1,79 @@ +namespace XrmMockup.PermissionAnalyzer.Tool.Options; + +/// +/// Absolute paths for one run, after command-line options are applied over the configuration. +/// +/// The solution or project to analyze. +/// The XrmMockup metadata folder, or null to analyze without roles. +/// Patterns for projects to leave out: the configured ones, then the command line's. +/// +/// Solutions or projects with plugin code to load for cascades only: the configured ones, then the command line's. +/// +internal sealed record AnalysisSettings(string Target, string? MetadataDirectory, IReadOnlyList ExcludeProjects, IReadOnlyList PluginSolutions) +{ + private const string DefaultMetadataDirectory = "./Metadata"; + + /// + /// Command-line paths are relative to the current directory; configured paths to the configuration file. + /// + public static AnalysisSettings Resolve( + string? solution, + string? metadata, + LoadedConfiguration configuration, + IReadOnlyList? exclude = null, + IReadOnlyList? pluginSolutions = null) + { + var excludeProjects = configuration.Permissions.ExcludeProjects.Concat(exclude ?? []).ToList(); + var currentDirectory = Directory.GetCurrentDirectory(); + + var target = solution is { } cliTarget ? Path.GetFullPath(cliTarget, currentDirectory) + : configuration.Permissions.Solution is { } configuredTarget ? Path.GetFullPath(configuredTarget, configuration.Directory) + : FindSolution(currentDirectory); + if (!File.Exists(target)) throw new ToolException($"Solution or project not found: {target}"); + + // The analyzed solution is loaded once, as itself + var plugins = configuration.Permissions.PluginSolutions.Select(p => Path.GetFullPath(p, configuration.Directory)) + .Concat((pluginSolutions ?? []).Select(p => Path.GetFullPath(p, currentDirectory))) + .Distinct(StringComparer.Ordinal) + .Where(p => !string.Equals(p, target, StringComparison.Ordinal)) + .ToList(); + foreach (var plugin in plugins) + { + if (!File.Exists(plugin)) throw new ToolException($"Plugin solution or project not found: {plugin}"); + } + + string? metadataDirectory; + if (metadata is not null) + { + metadataDirectory = Path.GetFullPath(metadata, currentDirectory); + } + else if ((configuration.Permissions.MetadataDirectory ?? configuration.MetadataOutputDirectory) is { } configured) + { + metadataDirectory = Path.GetFullPath(configured, configuration.Directory); + } + else + { + // Nothing configured: use the metadata tool's default folder if it's there + var fallback = Path.GetFullPath(DefaultMetadataDirectory, configuration.Directory); + return new AnalysisSettings(target, Directory.Exists(fallback) ? fallback : null, excludeProjects, plugins); + } + + if (!Directory.Exists(metadataDirectory)) throw new ToolException($"Metadata folder not found: {metadataDirectory}"); + return new AnalysisSettings(target, metadataDirectory, excludeProjects, plugins); + } + + private static string FindSolution(string directory) + { + var solutions = Directory.GetFiles(directory, "*.sln") + .Concat(Directory.GetFiles(directory, "*.slnx")) + .OrderBy(f => f, StringComparer.Ordinal) + .ToList(); + + return solutions.Count switch + { + 1 => solutions[0], + 0 => throw new ToolException($"No solution found in {directory}. Use --solution to give a solution or project."), + _ => throw new ToolException($"Several solutions found in {directory}. Use --solution to pick one."), + }; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/ConfigReader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/ConfigReader.cs new file mode 100644 index 00000000..cbca4666 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/ConfigReader.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Configuration; + +namespace XrmMockup.PermissionAnalyzer.Tool.Options; + +/// +/// Reads configuration the same way as the metadata tool: appsettings.json, then +/// appsettings.{DOTNET_ENVIRONMENT}.json, then environment variables. Command-line options are applied on top +/// by the caller. +/// +internal static class ConfigReader +{ + public const string ConfigFileBase = "appsettings"; + public const string MetadataOutputDirectoryKey = "XrmMockup:Metadata:OutputDirectory"; + + /// + /// Reads the configuration next to , or in the current directory when it's + /// null. Relative paths in the configuration are relative to . + /// + public static LoadedConfiguration Read(string? configPath) + { + string directory; + string fileName; + if (configPath is null) + { + directory = Directory.GetCurrentDirectory(); + fileName = $"{ConfigFileBase}.json"; + } + else + { + var fullPath = Path.GetFullPath(configPath); + if (!File.Exists(fullPath)) throw new ToolException($"Configuration file not found: {fullPath}"); + directory = Path.GetDirectoryName(fullPath)!; + fileName = Path.GetFileName(fullPath); + } + + var environment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"; + var configuration = new ConfigurationBuilder() + .SetBasePath(directory) + .AddJsonFile(fileName, optional: configPath is null) + .AddJsonFile($"{ConfigFileBase}.{environment}.json", optional: true) + .AddEnvironmentVariables() + .Build(); + + var permissions = configuration.GetSection(PermissionsConfiguration.SectionPath).Get() + ?? new PermissionsConfiguration(); + + return new LoadedConfiguration(directory, permissions, configuration[MetadataOutputDirectoryKey]); + } +} + +/// The folder that relative paths in the configuration are relative to. +/// The XrmMockup:Permissions section. +/// The metadata tool's output folder, when configured. +internal sealed record LoadedConfiguration(string Directory, PermissionsConfiguration Permissions, string? MetadataOutputDirectory); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/PermissionsConfiguration.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/PermissionsConfiguration.cs new file mode 100644 index 00000000..79dc8450 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Options/PermissionsConfiguration.cs @@ -0,0 +1,180 @@ +namespace XrmMockup.PermissionAnalyzer.Tool.Options; + +/// +/// Configuration for permission analysis from appsettings.json. +/// +public record PermissionsConfiguration +{ + /// + /// The configuration section path. + /// + public const string SectionPath = "XrmMockup:Permissions"; + + /// + /// Solution or project to analyze, relative to the configuration file. + /// + public string? Solution { get; init; } + + /// + /// XrmMockup metadata folder, relative to the configuration file. When not set, the metadata + /// tool's XrmMockup:Metadata:OutputDirectory is used. + /// + public string? MetadataDirectory { get; init; } + + /// + /// Projects to leave out, such as test projects. Wildcard patterns matched against the project name + /// (*.Tests), or against the path relative to the solution when they contain a slash (tests/*). + /// + public string[] ExcludeProjects { get; init; } = []; + + /// + /// Solutions or projects with the plugin code of the environment, relative to the configuration file, for code that + /// doesn't include it, such as an Azure Function app. Their plugin steps and custom APIs run when the analyzed code + /// fires them, but their own entry points aren't reported. + /// + public string[] PluginSolutions { get; init; } = []; + + /// + /// Methods to analyze as entry points besides the discovered ones, such as Contoso.Sync.Importer.Run. + /// + public string[] EntryPoints { get; init; } = []; + + /// + /// Roles of the application user of app code, such as an Azure Function app, by assembly name + /// (Contoso.Functions) or by assembly and function name (Contoso.Functions/ProcessOrder), which wins. + /// + public Dictionary Principals { get; init; } = []; + + /// + /// Roles of specific users, such as the impersonating user of a plugin step, by user id. + /// + public Dictionary Users { get; init; } = []; + + /// + /// Missing privileges that are accepted. They are reported as suppressed and don't fail --fail-on-missing. + /// + public SuppressionConfiguration[] Suppress { get; init; } = []; + + /// + /// Rules for requests passed to Execute, which replace the built-in rule for their message or add one. + /// + public RuleConfiguration[] Rules { get; init; } = []; +} + +public record PrincipalConfiguration +{ + public string[] Roles { get; init; } = []; +} + +public record UserConfiguration +{ + /// + /// A name for the user in the output, such as svc-plugins. + /// + public string? Name { get; init; } + + public string[] Roles { get; init; } = []; +} + +public record SuppressionConfiguration +{ + /// + /// Table logical name. Leave it out to suppress a privilege not tied to a table, named in . + /// + public string? Table { get; init; } + + /// + /// The privilege, such as Create. Every privilege on the table when not set. Without a table, the name of + /// a privilege not tied to a table, such as prvActOnBehalfOfAnotherUser. + /// + public string? Privilege { get; init; } + + public string? Reason { get; init; } +} + +public record RuleConfiguration +{ + /// + /// The message, such as Assign, or the request type name, such as AssignRequest. + /// + public string? Message { get; init; } + + /// + /// The member that holds the target of , such as Target. + /// + public string? Target { get; init; } + + /// + /// The privileges needed on . $Member, such as $PrincipalAccess.AccessMask, + /// adds the rights that member grants. + /// + public string[] Privileges { get; init; } = []; + + /// + /// Further checks, on other members or on fixed tables. + /// + public RuleCheckConfiguration[] Checks { get; init; } = []; + + /// + /// Messages whose checks this request makes as well, such as Create and Update for Upsert. + /// + public string[] As { get; init; } = []; + + /// + /// The member that holds several targets, which the checks of on Target apply to. + /// + public string? Targets { get; init; } + + /// + /// The member that holds requests run as part of this one. + /// + public string? Requests { get; init; } + + /// + /// Privileges the request needs by name, such as prvBulkDelete, looked up in the privilege catalog. + /// + public string[] GlobalPrivileges { get; init; } = []; + + /// + /// What the analysis assumes about the request, reported with every call to it. + /// + public string? Assumption { get; init; } + + /// + /// Whether XrmMockup makes the checks. true when not set. + /// + public bool? Enforced { get; init; } + + /// + /// The table the request's plugin steps fire on, when it isn't that of its first member check. + /// + public string? FiresOn { get; init; } + + /// + /// The message the request's plugin steps are registered on, when it isn't the request's own. + /// + public string? StepMessage { get; init; } +} + +public record RuleCheckConfiguration +{ + /// + /// The request member that refers to the table, such as Target. + /// + public string? Member { get; init; } + + /// + /// A fixed table logical name, when no is set. + /// + public string? Table { get; init; } + + /// + /// The privileges, as for . + /// + public string[] Privileges { get; init; } = []; + + /// + /// A boolean member that must be set for the check to apply. + /// + public string? When { get; init; } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/PermissionAnalysisLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/PermissionAnalysisLoader.cs new file mode 100644 index 00000000..6edc02a0 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/PermissionAnalysisLoader.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Logging.Abstractions; +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Commands; +using XrmMockup.PermissionAnalyzer.Tool.Metadata; +using XrmMockup.PermissionAnalyzer.Tool.Options; + +namespace XrmMockup.PermissionAnalyzer.Workspace; + +/// Opt-in MSBuild/Roslyn frontend. The workspace is disposed after source summaries are extracted. +public static class PermissionAnalysisLoader +{ + public static async Task LoadAsync(string projectOrSolutionPath, CancellationToken cancellationToken = default) + { + var directory = Path.GetDirectoryName(Path.GetFullPath(projectOrSolutionPath))!; + var configPath = Path.Combine(directory, "appsettings.json"); + var configuration = File.Exists(configPath) ? ConfigReader.Read(configPath) + : new LoadedConfiguration(directory, new PermissionsConfiguration(), null); + var settings = AnalysisSettings.Resolve(projectOrSolutionPath, null, configuration); + var contents = settings.MetadataDirectory is { } metadataDirectory ? MetadataFileLoader.Load(metadataDirectory) : null; + var builder = new ManifestBuilder(directory, RuleSetup.Create(configuration.Permissions), contents?.Lookups); + builder.AddEntryMethods(configuration.Permissions.EntryPoints); + if (settings.MetadataDirectory is { } metadata) + { + builder.AddWorkflows(WorkflowLoader.Load(metadata)); + if (PrivilegeCatalogLoader.Load(metadata) is var (privileges, apis)) builder.AddPrivilegeCatalog(privileges, apis); + } + var incomplete = await SourceLoader.AddAsync(builder, settings, NullLoggerFactory.Instance, cancellationToken, collectIncompleteSource: true); + return new LoadedAnalysis(builder, incomplete); + } + + private sealed class LoadedAnalysis(ManifestBuilder source, IReadOnlyList incomplete) : PermissionAnalysis + { + public override Manifest Analyze(PermissionScope scope, PermissionMetadata metadata) + { + if (scope is null) throw new ArgumentNullException(nameof(scope)); + if (metadata is null) throw new ArgumentNullException(nameof(metadata)); + var builder = source.WithMetadata(metadata); + EntryPointSelector selector; + if (scope.PluginType is not null) selector = EntryPointSelector.TypedPlugin(scope); + else + { + builder.AddOperation(scope.Message!, scope.Table!, scope.Columns); + selector = EntryPointSelector.Operation(scope.Message!, scope.Table!); + } + var manifest = builder.Build(metadata.RoleGovernedTables, selector); + if (manifest.EntryPoints.Count == 0) throw new ArgumentException($"No registered entry point matches {scope}.", nameof(scope)); + if (incomplete.Count == 0) return manifest; + return new Manifest(manifest.EntryPoints.Select(e => new EntryPoint(e.Id, e.Kind, e.Type, e.Assembly, + e.Trigger, e.ImpersonatingUserId, e.Declaration, e.Requirements, e.Unresolved.Concat(incomplete).ToList(), + e.Assumptions, e.Triggers, e.GlobalRequirements, e.Truncated)).ToList(), [], manifest.NotRoleGoverned); + } + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/PermissionAnalyzer.Workspace.csproj b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/PermissionAnalyzer.Workspace.csproj new file mode 100644 index 00000000..9e572c39 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/PermissionAnalyzer.Workspace.csproj @@ -0,0 +1,28 @@ + + + XrmMockup.PermissionAnalyzer.Workspace + + false + Opt-in MSBuild and Roslyn source loading for XrmMockup static permission checks. + + true + + + + + + + + + + + + + + + + + + + + diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Serialization/MetadataContracts.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Serialization/MetadataContracts.cs new file mode 100644 index 00000000..4f466922 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Serialization/MetadataContracts.cs @@ -0,0 +1,93 @@ +// Private wire contracts retain the metadata generator's DataContract names without exporting +// duplicate DG.Tools.XrmMockup types into SDK consumers that also reference Core. +#nullable disable +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Microsoft.Crm.Sdk.Messages; +using Microsoft.Xrm.Sdk; +using Microsoft.Xrm.Sdk.Metadata; +namespace XrmMockup.PermissionAnalyzer.Workspace.Serialization; + +[DataContract(Name = "MetadataSkeleton", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class MetadataSkeleton +{ + [DataMember] public SortedDictionary EntityMetadata; + [DataMember] public List Currencies; + [DataMember] public Entity BaseOrganization; + [DataMember] public Entity RootBusinessUnit; + [DataMember] public List Plugins; + [DataMember] public OptionSetMetadataBase[] OptionSets; + [DataMember] public Dictionary> DefaultStateStatus; +} + +[DataContract(Name = "MetaPlugin", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class MetaPlugin +{ + [DataMember] public string FilteredAttributes; + [DataMember] public int Mode; + [DataMember] public string Name; + [DataMember] public int Rank; + [DataMember] public int Stage; + [DataMember] public string MessageName; + [DataMember] public string AssemblyName; + [DataMember] public string PluginTypeAssemblyName; + [DataMember] public string PrimaryEntity; + [DataMember] public bool AsyncAutoDelete; + [DataMember] public List Images; + [DataMember] public Guid? ImpersonatingUserId; +} + +[DataContract(Name = "MetaImage", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class MetaImage +{ + [DataMember] public string Attributes; + [DataMember] public string EntityAlias; + [DataMember] public string Name; + [DataMember] public int ImageType; +} + +[DataContract(Name = "RolePrivilege", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class RolePrivilege +{ + [DataMember] public bool CanBeGlobal; + [DataMember] public bool CanBeDeep; + [DataMember] public bool CanBeLocal; + [DataMember] public bool CanBeBasic; + [DataMember] public AccessRights AccessRight; + [DataMember] public PrivilegeDepth PrivilegeDepth; +} + +[DataContract(Name = "SecurityRole", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class SecurityRole +{ + [DataMember] public Dictionary> Privileges; + [DataMember] public Dictionary GlobalPrivileges; + [DataMember] public string Name; + [DataMember] public EntityReference BusinessUnitId; + [DataMember] public Guid RoleId; + [DataMember] public Guid RoleTemplateId; +} + +[DataContract(Name = "PrivilegeCatalog", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class PrivilegeCatalog +{ + [DataMember] public List Privileges; + [DataMember] public List CustomApis; +} + +[DataContract(Name = "MetaPrivilege", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class MetaPrivilege +{ + [DataMember] public string Name; + [DataMember] public Guid PrivilegeId; + [DataMember] public AccessRights AccessRight; + [DataMember] public List Tables; +} + +[DataContract(Name = "MetaCustomApi", Namespace = "http://schemas.datacontract.org/2004/07/DG.Tools.XrmMockup")] +internal sealed class MetaCustomApi +{ + [DataMember] public string UniqueName; + [DataMember] public string ExecutePrivilegeName; +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/SourceLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/SourceLoader.cs new file mode 100644 index 00000000..79706ef1 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/SourceLoader.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Logging; +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmMockup.PermissionAnalyzer.Tool.Options; +using XrmMockup.PermissionAnalyzer.Tool.Workspace; + +namespace XrmMockup.PermissionAnalyzer.Workspace; + +/// The shared source-loading orchestration for the CLI and SDK. +internal static class SourceLoader +{ + public static async Task> AddAsync(ManifestBuilder builder, AnalysisSettings settings, ILoggerFactory loggerFactory, CancellationToken cancellationToken, bool collectIncompleteSource = false) + { + var root = Path.GetDirectoryName(settings.Target)!; + var filter = new ProjectFilter(root, settings.ExcludeProjects); + using var loader = new CodeLoader(loggerFactory.CreateLogger(), collectIncompleteSource); + await loader.AddAsync(settings.Target, builder, filter, cancellationToken); + foreach (var plugins in settings.PluginSolutions) + await loader.AddAsync(plugins, builder, filter, cancellationToken, pluginCode: true); + var logger = loggerFactory.CreateLogger(typeof(SourceLoader)); + foreach (var pattern in filter.Unused) logger.LogWarning("Exclude pattern '{Pattern}' matches no project", pattern); + foreach (var unmatched in builder.UnmatchedEntryMethods()) logger.LogWarning("No method in the solution matches entry point {Method}", unmatched); + return loader.IncompleteSource; + } +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/ToolException.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/ToolException.cs new file mode 100644 index 00000000..7096a1e2 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/ToolException.cs @@ -0,0 +1,6 @@ +namespace XrmMockup.PermissionAnalyzer.Tool; + +/// +/// An error in the input, such as a missing file. Reported without a stack trace. +/// +internal sealed class ToolException(string message) : Exception(message); diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/CodeLoader.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/CodeLoader.cs new file mode 100644 index 00000000..4507ffb9 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/CodeLoader.cs @@ -0,0 +1,233 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.MSBuild; +using Microsoft.Extensions.Logging; +using XrmMockup.PermissionAnalyzer.Core.Analysis; +using XrmMockup.PermissionAnalyzer.Core.Model; + +namespace XrmMockup.PermissionAnalyzer.Tool.Workspace; + +/// +/// Loads a solution or project with MSBuild and adds every C# project to a , or with +/// pluginCode, as plugin code from another solution (). The projects +/// that a single project references are added as referenced code (). +/// The projects must be restored, as for a build. Strong-name signing is turned off, because it only affects the +/// output and its key file is often not on the machine. +/// +/// Every path is loaded into one workspace, so a project that several of them reference, such as a shared library of +/// the plugin solutions, is loaded once and added once: by the first path that has it, whose kind of code is never +/// weaker than a later one's. +/// +/// +internal sealed class CodeLoader(ILogger logger, bool collectIncompleteSource = false) : IDisposable +{ + internal List IncompleteSource { get; } = []; + + // MSBuild reports warnings such as NuGet audit results as failures too, so they're only shown when a project + // turns out not to load, below + private readonly List _failures = []; + + // What became of each project, by file and name (which has the target framework) + private readonly Dictionary<(string File, string Name), Outcome> _seen = []; + + private enum Outcome { Added, Skipped } + + private MSBuildWorkspace? _workspace; + private IDisposable? _failureHandler; + + public void Dispose() + { + _failureHandler?.Dispose(); + _workspace?.Dispose(); + } + + private MSBuildWorkspace Workspace() + { + if (_workspace is not null) return _workspace; + + var properties = FrameworkReferences.Properties(); + if (properties.TryGetValue(FrameworkReferences.Property, out var frameworkRoot)) + { + logger.LogDebug(".NET Framework reference assemblies from {Root}", frameworkRoot); + } + _workspace = MSBuildWorkspace.Create(properties); + _failureHandler = _workspace.RegisterWorkspaceFailedHandler(e => + { + logger.LogDebug("{Message}", e.Diagnostic.Message); + lock (_failures) _failures.Add(e.Diagnostic.Message); + }); + return _workspace; + } + + public async Task AddAsync(string path, ManifestBuilder builder, ProjectFilter filter, CancellationToken cancellationToken, bool pluginCode = false) + { + var solutionDirectory = Path.GetDirectoryName(Path.GetFullPath(path))!; + var workspace = Workspace(); + + logger.LogInformation("Loading {Path}", path); + IEnumerable projects; + var referenced = new HashSet(); + if (IsSolution(path)) + { + projects = (await workspace.OpenSolutionAsync(path, cancellationToken: cancellationToken)).Projects; + } + else + { + // Opening a project reuses the projects it references that the workspace already has + var fullPath = Path.GetFullPath(path); + if (!workspace.CurrentSolution.Projects.Any(p => string.Equals(p.FilePath, fullPath, StringComparison.OrdinalIgnoreCase))) + { + await workspace.OpenProjectAsync(path, cancellationToken: cancellationToken); + } + // A project with several target frameworks loads as one project per framework. The projects it + // references are analyzed too, because entry points in this project call into them, such as + // function apps whose Dataverse calls are in a shared library. Code in them that the project doesn't + // reach isn't reported as unreached, since other apps that share the library may call it + var solution = workspace.CurrentSolution; + var roots = solution.Projects.Where(p => string.Equals(p.FilePath, fullPath, StringComparison.OrdinalIgnoreCase)).ToList(); + projects = WithReferences(solution, roots).ToList(); + referenced.UnionWith(projects.Select(p => p.Id).Except(roots.Select(p => p.Id))); + } + + var analyzed = 0; + var excluded = new HashSet(StringComparer.Ordinal); + string Problems(Project project) + { + lock (_failures) + { + var messages = _failures.Where(f => project.FilePath is { } file && f.Contains(file)).Distinct().Take(3); + return string.Concat(messages.Select(m => Environment.NewLine + " " + m)); + } + } + + // Sorted, so log output and duplicate merging don't depend on load order + foreach (var project in projects.OrderBy(p => p.FilePath, StringComparer.Ordinal).ThenBy(p => p.Name, StringComparer.Ordinal)) + { + // Checked before compiling, which is most of the time spent per project + if (filter.Excludes(project.FilePath, solutionDirectory) is { } pattern) + { + // Once per project file, not per target framework + if (excluded.Add(project.FilePath!)) logger.LogInformation("Skipping {Project}: excluded by '{Pattern}'", Path.GetFileNameWithoutExtension(project.FilePath), pattern); + continue; + } + + var key = (project.FilePath ?? "", project.Name); + if (_seen.TryGetValue(key, out var outcome)) + { + logger.LogDebug("{Project} was already loaded", project.Name); + if (outcome == Outcome.Added) analyzed++; + continue; + } + + if (project.Language != LanguageNames.CSharp) + { + logger.LogInformation("Skipping {Project}: only C# is analyzed", project.Name); + _seen[key] = Outcome.Skipped; + continue; + } + + // Logged before compiling, which is most of the time spent per project, so a slow project shows + logger.LogInformation(pluginCode ? "Analyzing {Project} for plugin cascades" : "Analyzing {Project}", project.Name); + var compilation = await project.GetCompilationAsync(cancellationToken) + ?? throw new ToolException($"Could not compile {project.Name}"); + compilation = compilation.WithOptions(compilation.Options + .WithCryptoKeyFile(null) + .WithCryptoKeyContainer(null) + .WithDelaySign(null) + .WithPublicSign(false)); + + var problems = Problems(project); + if (compilation.GetSpecialType(SpecialType.System_Object).TypeKind == TypeKind.Error) + { + // Not even the framework resolved, so nothing in the project can be analyzed + var hint = problems.Contains("reference assemblies for .NETFramework", StringComparison.Ordinal) + ? " Its .NET Framework reference assemblies weren't found: restore a project that references the matching " + + "Microsoft.NETFramework.ReferenceAssemblies.net* package (such as net462), which puts them in the NuGet cache, " + + $"or set {FrameworkReferences.Property} to a folder with them." + : " Restore or build it on this machine first."; + throw new ToolException($"Could not load {project.Name}: its references didn't resolve.{hint}{problems}"); + } + + if (collectIncompleteSource) + { + foreach (var error in compilation.GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Error)) + { + var span = error.Location.GetLineSpan(); + var file = string.IsNullOrEmpty(span.Path) ? project.FilePath ?? project.Name : span.Path; + var location = new SourceLocation(Path.GetRelativePath(solutionDirectory, file).Replace('\\', '/'), span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1); + IncompleteSource.Add(new UnresolvedOperation("source compilation", [], error.ToString(), RunsAs.Caller, new RequirementSource(location, []))); + } + } + + var added = pluginCode ? builder.AddPluginCode(compilation, cancellationToken) + : referenced.Contains(project.Id) ? builder.AddReferencedCode(compilation, cancellationToken) + : builder.Add(compilation, cancellationToken); + _seen[key] = added ? Outcome.Added : Outcome.Skipped; + if (!added) + { + if (problems.Length == 0) + { + logger.LogInformation("Skipping {Project}: it doesn't reference the Dataverse SDK", project.Name); + } + else + { + // An unrestored project loses its package references, the Dataverse SDK among them + logger.LogWarning("Skipping {Project}: the Dataverse SDK isn't among its resolved references. Restore or build it on this machine if it should be. MSBuild reported:{Problems}", project.Name, problems); + } + continue; + } + analyzed++; + + // Calls the compiler can't bind are invisible to the analysis, so say how much is affected. Getting every + // diagnostic binds all the method bodies again, so it's only done when the analysis found code that + // didn't bind, or the cheaper syntax and declaration checks find errors + if (builder.LastAddedHasUnboundCode || HasErrors(compilation.GetParseDiagnostics(cancellationToken)) || HasErrors(compilation.GetDeclarationDiagnostics(cancellationToken))) + { + var errors = compilation.GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Error).ToList(); + if (errors.Count > 0) + { + var first = string.Concat(errors.Take(3).Select(e => Environment.NewLine + " " + e)); + logger.LogWarning( + "{Project} has {Count} compile errors; operations in code that doesn't compile may be missed. Restore and build the project first. The first:{Errors}", + project.Name, + errors.Count, + first); + } + } + } + + if (analyzed == 0 && excluded.Count > 0) + { + throw new ToolException($"No project in {path} is left to analyze: {excluded.Count} excluded, the rest don't reference the Dataverse SDK"); + } + + if (analyzed == 0) + { + throw new ToolException($"No project in {path} references the Dataverse SDK, so there is nothing to analyze. If one should, restore or build it on this machine first: until then its package references don't resolve."); + } + } + + /// + /// The given projects and every project they reference, directly or not. + /// + private static IEnumerable WithReferences(Solution solution, IEnumerable roots) + { + var found = new Dictionary(); + var pending = new Stack(roots); + while (pending.Count > 0) + { + var project = pending.Pop(); + if (found.ContainsKey(project.Id)) continue; + found.Add(project.Id, project); + foreach (var reference in project.ProjectReferences) + { + if (solution.GetProject(reference.ProjectId) is { } referenced) pending.Push(referenced); + } + } + return found.Values; + } + + private static bool HasErrors(IEnumerable diagnostics) => diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); + + private static bool IsSolution(string path) => + path.EndsWith(".sln", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".slnx", StringComparison.OrdinalIgnoreCase); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/FrameworkReferences.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/FrameworkReferences.cs new file mode 100644 index 00000000..0b33066c --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/FrameworkReferences.cs @@ -0,0 +1,83 @@ +using System.Runtime.InteropServices; + +namespace XrmMockup.PermissionAnalyzer.Tool.Workspace; + +/// +/// The .NET Framework reference assemblies for projects that target .NET Framework without referencing the +/// Microsoft.NETFramework.ReferenceAssemblies package, such as old-style plugin projects. Windows has them +/// from the Developer Packs; elsewhere they come from the Microsoft.NETFramework.ReferenceAssemblies.net* +/// packages in the NuGet cache, whose framework folders are linked into one root for TargetFrameworkRootPath. +/// +internal static class FrameworkReferences +{ + public const string Property = "TargetFrameworkRootPath"; + + private const string PackagePrefix = "microsoft.netframework.referenceassemblies.net"; + + /// + /// The MSBuild properties that make the reference assemblies found, or none when they don't need to be set. + /// + public static Dictionary Properties() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || Environment.GetEnvironmentVariable(Property) is { Length: > 0 }) return new Dictionary(); + return Root(PackagesDirectory()) is { } root ? new Dictionary { [Property] = root } : new Dictionary(); + } + + /// + /// A folder with every .NETFramework/v* version found in the packages under , + /// from the latest version of each package, or null when there are none. + /// + internal static string? Root(string packages, string? output = null) + { + if (!Directory.Exists(packages)) return null; + + var frameworks = new SortedDictionary(StringComparer.OrdinalIgnoreCase); + var directories = Directory.GetDirectories(packages) + .Where(d => Path.GetFileName(d).StartsWith(PackagePrefix, StringComparison.OrdinalIgnoreCase)) + .OrderBy(d => d, StringComparer.Ordinal); + foreach (var package in directories) + { + var latest = Directory.GetDirectories(package) + .Select(d => (Path: d, Version: Version.TryParse(Path.GetFileName(d), out var version) ? version : null)) + .Where(v => v.Version is not null) + .OrderByDescending(v => v.Version) + .Select(v => Path.Combine(v.Path, "build", ".NETFramework")) + .FirstOrDefault(Directory.Exists); + if (latest is null) continue; + + foreach (var framework in Directory.GetDirectories(latest)) + { + frameworks.TryAdd(Path.GetFileName(framework), framework); + } + } + if (frameworks.Count == 0) return null; + + var root = output ?? Path.Combine(Path.GetTempPath(), "xrmmockup-permissions", "framework-references"); + var target = Path.Combine(root, ".NETFramework"); + try + { + Directory.CreateDirectory(target); + foreach (var (name, path) in frameworks) + { + var link = Path.Combine(target, name); + var info = new DirectoryInfo(link); + if (info is { Exists: true, LinkTarget: { } existing } && existing == path) continue; + // File.Delete also removes a link whose target is gone, such as a package version cleared from the cache + if (info.LinkTarget is not null) File.Delete(link); + else if (info.Exists) Directory.Delete(link); + Directory.CreateSymbolicLink(link, path); + } + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + // Projects then fail to load with a message that says what is missing + return null; + } + return root; + } + + private static string PackagesDirectory() => + Environment.GetEnvironmentVariable("NUGET_PACKAGES") is { Length: > 0 } packages + ? packages + : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages"); +} diff --git a/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/ProjectFilter.cs b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/ProjectFilter.cs new file mode 100644 index 00000000..83a95a11 --- /dev/null +++ b/src/PermissionAnalyzer/PermissionAnalyzer.Workspace/Workspace/ProjectFilter.cs @@ -0,0 +1,59 @@ +using System.Text.RegularExpressions; + +namespace XrmMockup.PermissionAnalyzer.Tool.Workspace; + +/// +/// Decides which projects to leave out of the analysis. A pattern uses * and ? wildcards and is +/// case-insensitive. Without a slash it matches the project file name without extension, e.g. *.Tests; +/// with one it matches the project path relative to the analyzed solution, e.g. tests/*. +/// +internal sealed class ProjectFilter +{ + private readonly string _rootDirectory; + private readonly IReadOnlyList<(string Pattern, Regex Regex, bool IsPath)> _patterns; + private readonly HashSet _used = new(StringComparer.Ordinal); + + public ProjectFilter(string rootDirectory, IEnumerable patterns) + { + _rootDirectory = rootDirectory; + _patterns = patterns + .Select(p => p.Trim().Replace('\\', '/')) + .Where(p => p.Length > 0) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(p => (p, ToRegex(p), p.Contains('/'))) + .ToList(); + } + + public IReadOnlyList Patterns => _patterns.Select(p => p.Pattern).ToList(); + + /// + /// The first pattern that excludes the project at , or null to analyze it. + /// Path patterns match relative to , the directory of the solution the project + /// is loaded from, which is the analyzed one by default. + /// + public string? Excludes(string? projectPath, string? solutionDirectory = null) + { + if (projectPath is null) return null; + + var name = Path.GetFileNameWithoutExtension(projectPath); + var relative = Path.GetRelativePath(solutionDirectory ?? _rootDirectory, projectPath).Replace('\\', '/'); + foreach (var (pattern, regex, isPath) in _patterns) + { + if (regex.IsMatch(isPath ? relative : name)) + { + _used.Add(pattern); + return pattern; + } + } + return null; + } + + /// + /// Patterns that haven't excluded any project so far, which are likely typos. + /// + public IEnumerable Unused => _patterns.Select(p => p.Pattern).Where(p => !_used.Contains(p)); + + private static Regex ToRegex(string pattern) => + new("^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); +} diff --git a/src/ToolsCommon/Logging/ShortCategoryConsoleExtensions.cs b/src/ToolsCommon/Logging/ShortCategoryConsoleExtensions.cs new file mode 100644 index 00000000..4d0ff6f2 --- /dev/null +++ b/src/ToolsCommon/Logging/ShortCategoryConsoleExtensions.cs @@ -0,0 +1,23 @@ +using Microsoft.Extensions.Logging; + +namespace XrmMockup.Tools.Common.Logging; + +public static class ShortCategoryConsoleExtensions +{ + /// + /// Adds a console logger that writes with . With + /// set, every line goes to standard error. + /// + public static ILoggingBuilder AddShortCategoryConsole(this ILoggingBuilder builder, Action? configure = null) + { + var options = new ShortCategoryConsoleFormatterOptions(); + configure?.Invoke(options); + return builder + .AddConsole(console => + { + console.FormatterName = ShortCategoryConsoleFormatter.FormatterName; + if (options.StandardError) console.LogToStandardErrorThreshold = LogLevel.Trace; + }) + .AddConsoleFormatter(configure ?? (_ => { })); + } +} diff --git a/src/MetadataGen/MetadataGenerator.Tool/Logging/ShortCategoryConsoleFormatter.cs b/src/ToolsCommon/Logging/ShortCategoryConsoleFormatter.cs similarity index 87% rename from src/MetadataGen/MetadataGenerator.Tool/Logging/ShortCategoryConsoleFormatter.cs rename to src/ToolsCommon/Logging/ShortCategoryConsoleFormatter.cs index 9d473a39..d8bd742d 100644 --- a/src/MetadataGen/MetadataGenerator.Tool/Logging/ShortCategoryConsoleFormatter.cs +++ b/src/ToolsCommon/Logging/ShortCategoryConsoleFormatter.cs @@ -3,18 +3,19 @@ using Microsoft.Extensions.Logging.Console; using Microsoft.Extensions.Options; -namespace XrmMockup.MetadataGenerator.Tool.Logging; +namespace XrmMockup.Tools.Common.Logging; /// -/// A console formatter that shows only the short class name instead of the full namespace. +/// A console formatter that shows only the short class name instead of the full namespace. Register it with +/// . /// public sealed class ShortCategoryConsoleFormatter : ConsoleFormatter { public const string FormatterName = "shortCategory"; - private readonly IOptionsMonitor _options; + private readonly IOptionsMonitor _options; - public ShortCategoryConsoleFormatter(IOptionsMonitor options) + public ShortCategoryConsoleFormatter(IOptionsMonitor options) : base(FormatterName) { _options = options; @@ -44,8 +45,9 @@ public override void Write( // Write log level with color using ANSI codes var logLevelString = GetLogLevelString(logEntry.LogLevel); + var redirected = options.StandardError ? Console.IsErrorRedirected : Console.IsOutputRedirected; var useColor = options.ColorBehavior == LoggerColorBehavior.Enabled || - (options.ColorBehavior == LoggerColorBehavior.Default && !Console.IsOutputRedirected); + (options.ColorBehavior == LoggerColorBehavior.Default && !redirected); if (useColor) { diff --git a/src/ToolsCommon/Logging/ShortCategoryConsoleFormatterOptions.cs b/src/ToolsCommon/Logging/ShortCategoryConsoleFormatterOptions.cs new file mode 100644 index 00000000..84ce1dd2 --- /dev/null +++ b/src/ToolsCommon/Logging/ShortCategoryConsoleFormatterOptions.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.Logging.Console; + +namespace XrmMockup.Tools.Common.Logging; + +/// +/// Options for . +/// +public sealed class ShortCategoryConsoleFormatterOptions : SimpleConsoleFormatterOptions +{ + /// + /// Whether every log line goes to standard error, which then decides whether colors are used by default. + /// + public bool StandardError { get; set; } +} diff --git a/src/ToolsCommon/ToolsCommon.csproj b/src/ToolsCommon/ToolsCommon.csproj new file mode 100644 index 00000000..fea4eae8 --- /dev/null +++ b/src/ToolsCommon/ToolsCommon.csproj @@ -0,0 +1,14 @@ + + + net10.0 + enable + enable + XrmMockup.Tools.Common + XrmMockup.Tools.Common + + false + + + + + diff --git a/src/XrmMockup365/Core.cs b/src/XrmMockup365/Core.cs index bd2939d1..ca2b85d3 100644 --- a/src/XrmMockup365/Core.cs +++ b/src/XrmMockup365/Core.cs @@ -32,7 +32,7 @@ namespace DG.Tools.XrmMockup /// /// Class for handling all requests to the database /// - internal class Core : IXrmMockupExtension, ICoreOperations + internal partial class Core : IXrmMockupExtension, ICoreOperations { public TimeSpan TimeOffset { get; private set; } public MockupServiceProviderAndFactory ServiceFactory { get; private set; } diff --git a/src/XrmMockup365/Internal/ValueConverter.cs b/src/XrmMockup365/Internal/ValueConverter.cs index 07a3a1c5..583caa36 100644 --- a/src/XrmMockup365/Internal/ValueConverter.cs +++ b/src/XrmMockup365/Internal/ValueConverter.cs @@ -73,7 +73,7 @@ public static object ConvertTo(object value, Type targetType) { return dateTimeValue.ToUniversalTime(); } - + // Can we convert from the value's type converter to the target type? var valueConverter = System.ComponentModel.TypeDescriptor.GetConverter(valueType); if (valueConverter.CanConvertTo(targetType)) diff --git a/src/XrmMockup365/PermissionAnalysis.Packaging.targets b/src/XrmMockup365/PermissionAnalysis.Packaging.targets new file mode 100644 index 00000000..b620438b --- /dev/null +++ b/src/XrmMockup365/PermissionAnalysis.Packaging.targets @@ -0,0 +1,60 @@ + + + <_PermissionWorkspaceProject>$(MSBuildThisFileDirectory)../PermissionAnalyzer/PermissionAnalyzer.Workspace/PermissionAnalyzer.Workspace.csproj + <_PermissionWorkspaceOutput>$(MSBuildThisFileDirectory)../PermissionAnalyzer/PermissionAnalyzer.Workspace/bin/$(Configuration)/net10.0/ + $(TargetsForTfmSpecificBuildOutput);IncludePermissionContractsInPackage + $(TargetsForTfmSpecificDebugSymbolsInPackage);IncludePermissionContractSymbols + $(TargetsForTfmSpecificContentInPackage);IncludePermissionSdkPayload + + + + + + + + $(TargetDir)XrmMockup.PermissionAnalyzer.Abstractions.dll + XrmMockup.PermissionAnalyzer.Abstractions.dll + + + + + + <_TargetPathsToSymbols Include="$(TargetDir)XrmMockup.PermissionAnalyzer.Abstractions.pdb" Condition="Exists('$(TargetDir)XrmMockup.PermissionAnalyzer.Abstractions.pdb')" /> + + + + + + + + <_PermissionPackageFile Include="$(_PermissionWorkspaceOutput)**/*" /> + + tools/permission-analysis/%(_PermissionPackageFile.RecursiveDir)%(_PermissionPackageFile.Filename)%(_PermissionPackageFile.Extension) + None + + + + + + + <_XrmMockupPermissionAnalysisSourcePath>$(_PermissionWorkspaceOutput) + + + + + <_PermissionSourceFile Include="$(_PermissionWorkspaceOutput)**/*" /> + + XrmMockup.PermissionAnalysis/%(_PermissionSourceFile.RecursiveDir)%(_PermissionSourceFile.Filename)%(_PermissionSourceFile.Extension) + PreserveNewest + PreserveNewest + false + + + + diff --git a/src/XrmMockup365/PermissionAnalysisBootstrap.cs b/src/XrmMockup365/PermissionAnalysisBootstrap.cs new file mode 100644 index 00000000..fb06e510 --- /dev/null +++ b/src/XrmMockup365/PermissionAnalysisBootstrap.cs @@ -0,0 +1,76 @@ +#if NET10_0_OR_GREATER +using System; +using System.IO; +using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Runtime.Loader; +using System.Threading; +using System.Threading.Tasks; +using XrmMockup.PermissionAnalyzer; + +namespace DG.Tools.XrmMockup +{ + /// Loads only the shared SDK library payload, never either product's CLI executable. + internal static class PermissionAnalysisBootstrap + { + private static readonly Lazy Loader = new Lazy(LoadWorkspaceType); + + public static Task LoadAsync(string projectOrSolutionPath, CancellationToken cancellationToken) + { + try + { + return (Task)Loader.Value.GetMethod("LoadAsync", new[] { typeof(string), typeof(CancellationToken) }) + .Invoke(null, new object[] { projectOrSolutionPath, cancellationToken }); + } + catch (TargetInvocationException ex) when (ex.InnerException != null) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + throw; + } + } + + private static Type LoadWorkspaceType() + { + var path = Path.Combine(AppContext.BaseDirectory, "XrmMockup.PermissionAnalysis", "XrmMockup.PermissionAnalyzer.Workspace.dll"); + if (!File.Exists(path)) + throw new InvalidOperationException("Enable permission source loading by setting true in the .NET 10 test project. No dotnet tool installation is required."); + var context = new PermissionLibraryContext(path); + return context.LoadFromAssemblyPath(path).GetType("XrmMockup.PermissionAnalyzer.Workspace.PermissionAnalysisLoader", throwOnError: true); + } + + // Isolate the SDK's Roslyn/MSBuild dependencies from the host's workflow dependencies. + // The public contracts alone are shared, so manifests/scopes cross this boundary without + // casts between two copies of the same assembly's types. + private sealed class PermissionLibraryContext : AssemblyLoadContext + { + private readonly AssemblyDependencyResolver resolver; + private readonly string directory; + + public PermissionLibraryContext(string workspacePath) : base("XrmMockup.PermissionAnalysis", isCollectible: false) + { + resolver = new AssemblyDependencyResolver(workspacePath); + directory = Path.GetDirectoryName(workspacePath); + } + + protected override Assembly Load(AssemblyName name) + { + var contracts = typeof(PermissionAnalysis).Assembly; + if (name.Name == contracts.GetName().Name) return contracts; + var path = resolver.ResolveAssemblyToPath(name); + if (path == null) + { + var candidate = Path.Combine(directory, name.Name + ".dll"); + if (File.Exists(candidate)) path = candidate; + } + return path == null ? null : LoadFromAssemblyPath(path); + } + + protected override IntPtr LoadUnmanagedDll(string name) + { + var path = resolver.ResolveUnmanagedDllToPath(name); + return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(path); + } + } + } +} +#endif diff --git a/src/XrmMockup365/PermissionChecks.cs b/src/XrmMockup365/PermissionChecks.cs new file mode 100644 index 00000000..c665dc40 --- /dev/null +++ b/src/XrmMockup365/PermissionChecks.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.Crm.Sdk.Messages; +using Microsoft.Xrm.Sdk; +using Microsoft.Xrm.Sdk.Metadata; +using XrmMockup.PermissionAnalyzer; +using XrmMockup.PermissionAnalyzer.Core.Coverage; +using XrmMockup.PermissionAnalyzer.Core.Model; +using AnalysisDepth = XrmMockup.PermissionAnalyzer.Core.Model.PrivilegeDepth; +using CrmDepth = Microsoft.Crm.Sdk.Messages.PrivilegeDepth; + +namespace DG.Tools.XrmMockup +{ + public abstract partial class XrmMockupBase + { + /// Checks static privileges for combined role IDs. Does not execute requests or prove record-level access. + public PermissionCheckResult CheckPermissions(PermissionAnalysis analysis, PermissionScope scope, params Guid[] securityRoles) + { + return Core.CheckPermissions(analysis, scope, securityRoles); + } + + /// Checks the user's current direct and team-derived roles, without executing requests. + public PermissionCheckResult CheckPermissions(PermissionAnalysis analysis, PermissionScope scope, EntityReference user) + { + return Core.CheckPermissions(analysis, scope, user); + } + } + + internal partial class Core + { + public PermissionCheckResult CheckPermissions(PermissionAnalysis analysis, PermissionScope scope, params Guid[] securityRoles) + { + if (securityRoles == null) throw new ArgumentNullException(nameof(securityRoles)); + if (securityRoles.Length == 0) throw new ArgumentException("Supply at least one security role ID.", nameof(securityRoles)); + var current = security.GetSecurityRoles().ToDictionary(r => r.RoleId); + var roles = securityRoles.Distinct().Select(id => current.TryGetValue(id, out var role) ? role + : throw new ArgumentException($"Unknown security role ID: {id}.", nameof(securityRoles))).ToList(); + return CheckPermissions(analysis, scope, roles, "explicit security role IDs"); + } + + public PermissionCheckResult CheckPermissions(PermissionAnalysis analysis, PermissionScope scope, EntityReference user) + { + if (user == null) throw new ArgumentNullException(nameof(user)); + if (user.LogicalName != "systemuser" || user.Id == Guid.Empty || !security.HasLocalUser(user.Id)) + throw new ArgumentException($"Invalid local system user: {user.LogicalName} {user.Id}.", nameof(user)); + return CheckPermissions(analysis, scope, security.GetPermissionCheckRoles(user.Id), $"user {user.Id} (direct and team roles)"); + } + + private PermissionCheckResult CheckPermissions(PermissionAnalysis analysis, PermissionScope scope, IEnumerable roles, string origin) + { + if (analysis == null) throw new ArgumentNullException(nameof(analysis)); + if (scope == null) throw new ArgumentNullException(nameof(scope)); + var allRoles = security.GetSecurityRoles(); + var steps = (metadata.Plugins ?? new List()).Concat(settings.IPluginMetadata ?? new MetaPlugin[0]); + var context = new PermissionMetadata + { + Workflows = workflowManager.PermissionCheckWorkflows.Select(PermissionWorkflow).Where(w => w != null).ToList(), + RoleGovernedTables = allRoles.SelectMany(r => (r.Privileges ?? new Dictionary>()).Keys).Distinct().ToList(), + Lookups = metadata.EntityMetadata.Values.SelectMany(e => (e.Attributes ?? new AttributeMetadata[0]).OfType() + .Where(a => a.Targets != null && a.Targets.Length > 0).Select(a => new LookupColumn(e.LogicalName, a.LogicalName, a.Targets))).ToList(), + PluginSteps = steps.Where(p => !string.IsNullOrEmpty(p.AssemblyName) && !string.IsNullOrEmpty(p.MessageName)) + .Select(p => new PluginStepRegistration(p.AssemblyName, p.PluginTypeAssemblyName, p.MessageName, + string.IsNullOrEmpty(p.PrimaryEntity) || p.PrimaryEntity == "none" ? null : p.PrimaryEntity, + p.Stage, p.ImpersonatingUserId?.ToString(), string.IsNullOrWhiteSpace(p.FilteredAttributes) ? null : p.FilteredAttributes.Split(',').Select(a => a.Trim().ToLowerInvariant()).Where(a => a.Length > 0).ToList(), p.Mode == 1)).ToList() + }; + var manifest = analysis.Analyze(scope, context); + if (manifest.EntryPoints.Count == 0) throw new ArgumentException($"No registered entry point matches {scope}.", nameof(scope)); + var users = new Dictionary(StringComparer.OrdinalIgnoreCase); + // Never substitute the primary caller's roles for a separately impersonated identity. + foreach (var identity in manifest.AllRequirements.Select(r => r.RunsAs).Concat(manifest.AllGlobalRequirements.Select(r => r.RunsAs))) + { + if (identity.Kind == RunsAsKind.User && Guid.TryParse(identity.UserId, out var id) && security.HasLocalUser(id)) + users[identity.UserId] = RoleSet.Combine(security.GetPermissionCheckRoles(id).Select(PermissionRole), $"user {id} (direct and team roles)"); + } + var primaryRoles = RoleSet.Combine(roles.Select(PermissionRole), origin); + var coverage = CoverageEvaluator.EvaluateForPermissionCheck(manifest, new CoverageOptions(primaryRoles, users)); + return new PermissionCheckResult(manifest, coverage, primaryRoles); + } + + private static WorkflowRegistration PermissionWorkflow(Entity entity) + { + var table = entity.GetAttributeValue("primaryentity"); + if (string.IsNullOrEmpty(table) || table == "none") return null; + var create = entity.GetAttributeValue("triggeroncreate") == true; + var delete = entity.GetAttributeValue("triggerondelete") == true; + var columns = (entity.GetAttributeValue("triggeronupdateattributelist") ?? "").Split(',') + .Select(c => c.Trim().ToLowerInvariant()).Where(c => c.Length > 0).Distinct().OrderBy(c => c, StringComparer.Ordinal).ToList(); + if (!create && !delete && columns.Count == 0) return null; + var realTime = entity.GetAttributeValue("mode")?.Value == 1; + var asCaller = realTime && entity.GetAttributeValue("runas")?.Value == 1; + return new WorkflowRegistration(entity.GetAttributeValue("name") ?? entity.Id.ToString(), table, + create, delete, columns.Count == 0 ? null : columns, realTime, + asCaller ? null : entity.GetAttributeValue("ownerid")?.Id.ToString()); + } + + private static RoleDefinition PermissionRole(SecurityRole role) + { + var privileges = new Dictionary>(); + foreach (var table in role.Privileges ?? new Dictionary>()) + { + var rights = new Dictionary(); + foreach (var right in table.Value) + { + Privilege? mapped = null; + switch (right.Key) + { + case AccessRights.CreateAccess: mapped = Privilege.Create; break; + case AccessRights.ReadAccess: mapped = Privilege.Read; break; + case AccessRights.WriteAccess: mapped = Privilege.Write; break; + case AccessRights.DeleteAccess: mapped = Privilege.Delete; break; + case AccessRights.AppendAccess: mapped = Privilege.Append; break; + case AccessRights.AppendToAccess: mapped = Privilege.AppendTo; break; + case AccessRights.AssignAccess: mapped = Privilege.Assign; break; + case AccessRights.ShareAccess: mapped = Privilege.Share; break; + } + if (mapped.HasValue) rights[mapped.Value] = PermissionDepth(right.Value.PrivilegeDepth); + } + privileges[table.Key.ToLowerInvariant()] = rights; + } + var globals = role.GlobalPrivileges == null ? null : role.GlobalPrivileges.ToDictionary(p => p.Key, p => PermissionDepth(p.Value.PrivilegeDepth)); + return new RoleDefinition(role.Name, privileges, globals); + } + + private static AnalysisDepth PermissionDepth(CrmDepth depth) + { + switch (depth) + { + case CrmDepth.Basic: return AnalysisDepth.User; + case CrmDepth.Local: return AnalysisDepth.BusinessUnit; + case CrmDepth.Deep: return AnalysisDepth.ParentChildBusinessUnit; + default: return AnalysisDepth.Organization; + } + } + } +} diff --git a/src/XrmMockup365/PermissionSelector.cs b/src/XrmMockup365/PermissionSelector.cs new file mode 100644 index 00000000..5cc214f6 --- /dev/null +++ b/src/XrmMockup365/PermissionSelector.cs @@ -0,0 +1,55 @@ +using System; +using System.Linq.Expressions; +using System.Reflection; +using Microsoft.Xrm.Sdk; +using Microsoft.Xrm.Sdk.Client; +using XrmPluginCore.Enums; +using XrmMockup.PermissionAnalyzer; + +namespace DG.Tools.XrmMockup +{ + /// Typed static permission scopes. Uses SDK logical-name attributes, never CLR member names. + public static class PermissionSelector + { + public static PermissionScope Plugin(EventOperation? operation = null, ExecutionStage? stage = null) where TPlugin : IPlugin + { + if (operation.HasValue && !Enum.IsDefined(typeof(EventOperation), operation.Value)) throw new ArgumentOutOfRangeException(nameof(operation)); + return Plugin(operation.HasValue ? operation.Value.ToString() : null, stage); + } + + /// Selects steps for a custom SDK message, or all messages when omitted. + public static PermissionScope Plugin(string message, ExecutionStage? stage = null) where TPlugin : IPlugin + { + if (stage.HasValue && !Enum.IsDefined(typeof(ExecutionStage), stage.Value)) throw new ArgumentOutOfRangeException(nameof(stage)); + var type = typeof(TPlugin); + return PermissionScope.ForPlugin(type.FullName, type.Assembly.GetName().Name, message, stage.HasValue ? stage.Value.ToString() : null); + } + + public static PermissionScope Operation(EventOperation operation, params Expression>[] attributes) where TEntity : Entity + { + if (!Enum.IsDefined(typeof(EventOperation), operation)) throw new ArgumentOutOfRangeException(nameof(operation)); + return Operation(operation.ToString(), attributes); + } + + public static PermissionScope Operation(string message, params Expression>[] attributes) where TEntity : Entity + { + var logicalName = typeof(TEntity).GetCustomAttribute(); + if (logicalName == null) throw new ArgumentException("The entity type must have an SDK EntityLogicalName attribute.", nameof(TEntity)); + if (attributes == null) throw new ArgumentNullException(nameof(attributes)); + var columns = new string[attributes.Length]; + for (var i = 0; i < attributes.Length; i++) + { + var expression = attributes[i]; + if (expression == null) throw new ArgumentException("An attribute expression cannot be null.", nameof(attributes)); + Expression body = expression.Body; + if (body is UnaryExpression unary && (unary.NodeType == ExpressionType.Convert || unary.NodeType == ExpressionType.ConvertChecked)) body = unary.Operand; + if (!(body is MemberExpression member) || member.Expression != expression.Parameters[0] || !(member.Member is PropertyInfo property)) + throw new ArgumentException("Select a direct SDK entity property, such as account => account.Name.", nameof(attributes)); + var attribute = property.GetCustomAttribute(); + if (attribute == null) throw new ArgumentException("The selected property must have an SDK AttributeLogicalName attribute.", nameof(attributes)); + columns[i] = attribute.LogicalName; + } + return PermissionScope.ForOperation(message, logicalName.LogicalName, columns.Length == 0 ? null : columns); + } + } +} diff --git a/src/XrmMockup365/Security.cs b/src/XrmMockup365/Security.cs index cd0dfd1b..0147a09d 100644 --- a/src/XrmMockup365/Security.cs +++ b/src/XrmMockup365/Security.cs @@ -432,6 +432,38 @@ internal HashSet GetSecurityRoles(EntityReference caller) return securityRoles; } + // Permission analysis reads local rows only: no requests, online retrieval, related-entity + // expansion or privilege-cache mutation (GetSecurityRoles(caller) can expand related entities). + internal bool HasLocalUser(Guid userId) => PermissionCheckRows("systemuser").Any(u => u.Id == userId); + + private IEnumerable PermissionCheckRows(string table) => db.HasTable(table) + ? db[table].ToList() : Enumerable.Empty(); + + internal IReadOnlyList GetPermissionCheckRoles(Guid userId) + { + var result = new HashSet(PermissionCheckPrincipalRoles("systemuser", userId, "systemuserroles_association")); + var teams = PermissionCheckRows("teammembership").Where(m => m.GetColumn("systemuserid") == userId) + .Select(m => m.GetColumn("teamid")).Distinct(); + foreach (var team in teams) result.UnionWith(PermissionCheckPrincipalRoles("team", team, "teamroles_association")); + return result.ToList(); + } + + private IEnumerable PermissionCheckPrincipalRoles(string principal, Guid id, string schema) + { + if (!Metadata.EntityMetadata.TryGetValue(principal, out var entity)) yield break; + var relation = (entity.ManyToManyRelationships ?? new ManyToManyRelationshipMetadata[0]).FirstOrDefault(r => r.SchemaName == schema); + if (relation == null) yield break; + var principalAttribute = relation.Entity1LogicalName == principal ? relation.Entity1IntersectAttribute : relation.Entity2IntersectAttribute; + var roleAttribute = relation.Entity1LogicalName == "role" ? relation.Entity1IntersectAttribute : relation.Entity2IntersectAttribute; + foreach (var row in PermissionCheckRows(relation.IntersectEntityName).Where(r => r.GetColumn(principalAttribute) == id)) + { + var assignedRole = row.GetColumn(roleAttribute); + if (!SecurityRoleMapping.TryGetValue(assignedRole, out var roleId) || !SecurityRoles.TryGetValue(roleId, out var role)) + throw new ArgumentException($"Unknown assigned security role ID: {assignedRole}."); + yield return role; + } + } + private bool IsMemberOfTeam(EntityReference team, EntityReference user) { return Core.GetDbTable(LogicalNames.TeamMembership) diff --git a/src/XrmMockup365/Workflow/WorkflowManager.cs b/src/XrmMockup365/Workflow/WorkflowManager.cs index 7e3bb121..d384e91f 100644 --- a/src/XrmMockup365/Workflow/WorkflowManager.cs +++ b/src/XrmMockup365/Workflow/WorkflowManager.cs @@ -38,6 +38,8 @@ internal class WorkflowManager { private ConcurrentQueue pendingAsyncWorkflows; + internal IEnumerable PermissionCheckWorkflows => synchronousWorkflows.Concat(asynchronousWorkflows); + internal int SynchronousWorkflowCount => synchronousWorkflows.Count; internal int AsynchronousWorkflowCount => asynchronousWorkflows.Count; internal int ActionsCount => actions.Count; diff --git a/src/XrmMockup365/XrmMockup365.csproj b/src/XrmMockup365/XrmMockup365.csproj index 9edee76b..a1628238 100644 --- a/src/XrmMockup365/XrmMockup365.csproj +++ b/src/XrmMockup365/XrmMockup365.csproj @@ -74,10 +74,15 @@ + + + + <_Parameter1>XrmMockup365Test + \ No newline at end of file diff --git a/src/XrmMockup365/buildTransitive/XrmMockup365.targets b/src/XrmMockup365/buildTransitive/XrmMockup365.targets new file mode 100644 index 00000000..a2089294 --- /dev/null +++ b/src/XrmMockup365/buildTransitive/XrmMockup365.targets @@ -0,0 +1,20 @@ + + + + <_XrmMockupPermissionAnalysisPackagePath>$(MSBuildThisFileDirectory)../tools/permission-analysis/ + + + + <_XrmMockupPermissionLibraryFile Include="$(_XrmMockupPermissionAnalysisPackagePath)**/*" /> + + XrmMockup.PermissionAnalysis/%(_XrmMockupPermissionLibraryFile.RecursiveDir)%(_XrmMockupPermissionLibraryFile.Filename)%(_XrmMockupPermissionLibraryFile.Extension) + PreserveNewest + PreserveNewest + false + + + + diff --git a/tests/XrmMockup365Test/TestPrivileges/TestPermissionAnalysis.cs b/tests/XrmMockup365Test/TestPrivileges/TestPermissionAnalysis.cs new file mode 100644 index 00000000..f37c1095 --- /dev/null +++ b/tests/XrmMockup365Test/TestPrivileges/TestPermissionAnalysis.cs @@ -0,0 +1,178 @@ +#if DATAVERSE_SERVICE_CLIENT +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; +using Microsoft.Crm.Sdk.Messages; +using Microsoft.Xrm.Sdk; +using DG.Tools.XrmMockup; +using DG.XrmFramework.BusinessDomain.ServiceContext; +using DG.Some.Namespace; +using XrmMockup.PermissionAnalyzer; +using XrmMockup.PermissionAnalyzer.Core.Model; +using XrmPluginCore.Enums; +using Xunit; +using RolePrivilege = DG.Tools.XrmMockup.RolePrivilege; +using AppContext = System.AppContext; +using Operation = XrmPluginCore.Enums.EventOperation; +using Stage = XrmPluginCore.Enums.ExecutionStage; + +namespace DG.XrmMockupTest +{ + public class TestPermissionAnalysis : UnitTestBase + { + private static readonly Lazy> Analysis = new Lazy>(() => + PermissionAnalysis.LoadAsync(Path.GetFullPath(Path.Combine(FindRoot(), "tests/TestPluginAssembly365/TestPluginAssembly365.csproj")))); + + public TestPermissionAnalysis(XrmMockupFixture fixture) : base(fixture) { } + + private static string FindRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "XrmMockup.slnx"))) directory = directory.Parent; + return directory?.FullName ?? throw new DirectoryNotFoundException("Repository root not found"); + } + + [Fact] + public async System.Threading.Tasks.Task LoadsReusableSourceAndSelectsTypedPluginWithoutExecutingIt() + { + var analysis = await Analysis.Value; + Assert.Equal("XrmMockup.PermissionAnalysis", System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(analysis.GetType().Assembly).Name); + Assert.DoesNotContain(System.Runtime.Loader.AssemblyLoadContext.Default.Assemblies, + a => a.GetName().Name == "XrmMockup.PermissionAnalyzer.Workspace"); + var result = crm.CheckPermissions(analysis, PermissionSelector.Plugin(Operation.Create, Stage.PostOperation), SecurityRoles.XrmMockupTestAccessTeam); + Assert.True(result.Passed); + Assert.Equal("DG.Some.Namespace.AccountTagPlugin", Assert.Single(result.Manifest.EntryPoints).Type); + result.ThrowIfFailed(); + Assert.Throws(() => crm.CheckPermissions(analysis, PermissionSelector.Plugin(Operation.Delete), SecurityRoles.XrmMockupTestAccessTeam)); + } + + [Fact] + public async System.Threading.Tasks.Task CreateWithoutPluginsStillChecksDirectPrivilegeAndRoleChanges() + { + var analysis = await Analysis.Value; + // Business unit has no registered source plugins, but Create is still required. + var scope = PermissionSelector.Operation(Operation.Create); + var role = crm.CloneSecurityRole("XrmMockup Test Access Team"); + role.Privileges["businessunit"] = new Dictionary(); + crm.AddSecurityRole(role); + var first = crm.CheckPermissions(analysis, scope, role.RoleId); + Assert.False(first.Passed); + Assert.Contains(first.Manifest.AllRequirements, r => r.Table == "businessunit" && r.Privilege == XrmMockup.PermissionAnalyzer.Core.Model.Privilege.Create); + role.Privileges["businessunit"][AccessRights.CreateAccess] = new RolePrivilege { PrivilegeDepth = Microsoft.Crm.Sdk.Messages.PrivilegeDepth.Basic, AccessRight = AccessRights.CreateAccess }; + Assert.True(crm.CheckPermissions(analysis, scope, role.RoleId).Passed); + Assert.False(first.Passed); // Old results remain snapshots. + } + + [Fact] + public async System.Threading.Tasks.Task CombinedRolesAndCurrentUserTeamAssignments() + { + var analysis = await Analysis.Value; + var scope = PermissionSelector.Operation(Operation.Create); + var denied = crm.CloneSecurityRole("XrmMockup Test Access Team"); + denied.Privileges["businessunit"] = new Dictionary(); + crm.AddSecurityRole(denied); + var allowed = denied.Clone(); + allowed.Privileges["businessunit"][AccessRights.CreateAccess] = new RolePrivilege { PrivilegeDepth = Microsoft.Crm.Sdk.Messages.PrivilegeDepth.Basic, AccessRight = AccessRights.CreateAccess }; + crm.AddSecurityRole(allowed); + Assert.False(crm.CheckPermissions(analysis, scope, denied.RoleId).Passed); + Assert.True(crm.CheckPermissions(analysis, scope, denied.RoleId, allowed.RoleId).Passed); + var user = crm.CreateUser(orgAdminService, crm.RootBusinessUnit, denied.RoleId); + Assert.False(crm.CheckPermissions(analysis, scope, user.ToEntityReference()).Passed); + var team = crm.CreateTeam(orgAdminService, new Team { BusinessUnitId = crm.RootBusinessUnit }, allowed.RoleId); + orgAdminService.Execute(new AddMembersTeamRequest { TeamId = team.Id, MemberIds = new[] { user.Id } }); + Assert.True(crm.CheckPermissions(analysis, scope, user.ToEntityReference()).Passed); + orgAdminService.Execute(new RemoveMembersTeamRequest { TeamId = team.Id, MemberIds = new[] { user.Id } }); + Assert.False(crm.CheckPermissions(analysis, scope, user.ToEntityReference()).Passed); + crm.AddSecurityRolesToPrinciple(user.ToEntityReference(), allowed.RoleId); + Assert.True(crm.CheckPermissions(analysis, scope, user.ToEntityReference()).Passed); + } + + [Fact] + public async System.Threading.Tasks.Task ChecksDoNotChangeMockupState() + { + var analysis = await Analysis.Value; + var user = crm.CreateUser(orgAdminService, crm.RootBusinessUnit, SecurityRoles.XrmMockupTestAccessTeam); + var core = (Core)typeof(XrmMockupBase).GetField("Core", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(crm); + var before = core.TakeJsonSnapshot(); + crm.CheckPermissions(analysis, PermissionSelector.Operation(Operation.Create), user.ToEntityReference()); + crm.CheckPermissions(analysis, PermissionSelector.Plugin(), SecurityRoles.XrmMockupTestAccessTeam); + Assert.Equal(before, core.TakeJsonSnapshot()); + } + + [Fact] + public async System.Threading.Tasks.Task NewlyRegisteredWorkflowMakesAnalysisIncompleteWithoutExecutingIt() + { + var analysis = await Analysis.Value; + var scope = PermissionSelector.Operation(Operation.Create); + var core = (Core)typeof(XrmMockupBase).GetField("Core", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(crm); + Assert.True(crm.CheckPermissions(analysis, scope, SecurityRoles.SystemAdministrator).Passed); + core.AddWorkflow(new Entity("workflow", Guid.NewGuid()) + { + ["name"] = "Static workflow boundary", + ["category"] = new OptionSetValue(0), + ["mode"] = new OptionSetValue(0), + ["primaryentity"] = "businessunit", + ["triggeroncreate"] = true + }); + var result = crm.CheckPermissions(analysis, scope, SecurityRoles.SystemAdministrator); + Assert.False(result.Passed); + Assert.Contains(result.Manifest.EntryPoints.SelectMany(e => e.Unresolved), u => u.Reason.Contains("Static workflow boundary")); + Assert.Throws(result.ThrowIfFailed); + } + + [Fact] + public void ImpersonatedUsersUseTheirOwnRolesAndUnknownIdentitiesFail() + { + var denied = crm.CloneSecurityRole("XrmMockup Test Access Team"); + denied.Privileges["businessunit"] = new Dictionary(); + crm.AddSecurityRole(denied); + var user = crm.CreateUser(orgAdminService, crm.RootBusinessUnit, denied.RoleId); + var scope = PermissionSelector.Operation(Operation.Create); + var analysis = new IdentityAnalysis(user.Id); + var result = crm.CheckPermissions(analysis, scope, SecurityRoles.SystemAdministrator); + Assert.False(result.Passed); // The primary administrator cannot cover the impersonated user. + var error = Assert.Throws(result.ThrowIfFailed); + Assert.Contains(user.Id.ToString(), error.Message); + Assert.Contains(denied.Name, error.Message); + crm.AddSecurityRolesToPrinciple(user.ToEntityReference(), SecurityRoles.SystemAdministrator); + Assert.True(crm.CheckPermissions(analysis, scope, denied.RoleId).Passed); + var unknown = crm.CheckPermissions(new IdentityAnalysis(Guid.NewGuid()), scope, SecurityRoles.SystemAdministrator); + Assert.False(unknown.Passed); + Assert.True(unknown.Coverage.Summary.NotChecked > 0); + } + + private sealed class IdentityAnalysis : PermissionAnalysis + { + private readonly Guid user; + public IdentityAnalysis(Guid user) { this.user = user; } + public override Manifest Analyze(PermissionScope scope, PermissionMetadata metadata) + { + var requirement = new Requirement("businessunit", XrmMockup.PermissionAnalyzer.Core.Model.Privilege.Create, + RunsAs.User(user.ToString()), RequirementBasis.Direct, + new[] { new RequirementSource(new SourceLocation("Impersonation.cs", 1, 1), new string[0]) }); + return new Manifest(new[] { new EntryPoint("operation:Create businessunit", EntryPointKind.Operation, "", null, + null, null, null, new[] { requirement }, new UnresolvedOperation[0], new Assumption[0]) }, new MethodManifest[0]); + } + } + + [Fact] + public async System.Threading.Tasks.Task ValidationAndSdkAttributeSelectors() + { + var analysis = await Analysis.Value; + var scope = PermissionSelector.Operation(Operation.Update, a => a.Name, a => a.PrimaryContactId); + Assert.Equal("account", scope.Table); + Assert.Equal(new[] { "name", "primarycontactid" }, scope.Columns); + Assert.Throws(() => PermissionSelector.Operation(Operation.Update, a => a.Name.Length)); + Assert.Throws(() => crm.CheckPermissions(analysis, scope, new Guid[0])); + Assert.Throws(() => crm.CheckPermissions(analysis, scope, Guid.NewGuid())); + Assert.Throws(() => crm.CheckPermissions(analysis, scope, new EntityReference("systemuser", Guid.NewGuid()))); + Assert.Throws(() => crm.CheckPermissions(analysis, scope, crm.RootBusinessUnit)); + var result = crm.CheckPermissions(analysis, PermissionSelector.Operation("not_a_known_message"), SecurityRoles.XrmMockupTestAccessTeam); + Assert.False(result.Passed); + Assert.Throws(result.ThrowIfFailed); + } + } +} +#endif diff --git a/tests/XrmMockup365Test/XrmMockup365Test.csproj b/tests/XrmMockup365Test/XrmMockup365Test.csproj index c7898eda..885b6ac0 100644 --- a/tests/XrmMockup365Test/XrmMockup365Test.csproj +++ b/tests/XrmMockup365Test/XrmMockup365Test.csproj @@ -21,6 +21,7 @@ $(DefineConstants);DATAVERSE_SERVICE_CLIENT + true @@ -36,7 +37,7 @@ - + @@ -45,6 +46,9 @@ + +