Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions demos/analytics-using-managedcleanroom/README-API.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Big Data Analytics — REST API (`az rest` + `Invoke-RestMethod`)

For reusable wrappers covering this guide's ARM and frontend operations, see
[Fast Setup Scripts](scripts/README-SCRIPTS.md) and the
[frontend script reference](scripts/frontend/README.md).

This guide uses **`az rest`** for ARM collaboration operations and
**`Invoke-RestMethod`** for frontend service operations, with the same helper
scripts for Azure resource provisioning.
Expand Down
4 changes: 4 additions & 0 deletions demos/analytics-using-managedcleanroom/README-CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and frontend operations, with helper scripts for Azure resource provisioning.
For the REST API variant using `Invoke-RestMethod` and `az rest`, see
[README-API.md](README-API.md).

For the same workflow through reusable PowerShell/Bicep helpers, including
IP tags, query `ScaleSku`, service dry runs, cancellation, and SPN participants,
see [Fast Setup Scripts](scripts/README-SCRIPTS.md).

---

## Scenario
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
For CPK (Client-Provided Keys):
1. Generate a random AES-256 DEK (Data Encryption Key)
2. Upload data with azcopy --cpk-by-value (Azure Storage encrypts server-side)
3. Save DEK binary file for Phase B (KEK creation in 08-publish-dataset.ps1)
3. Save DEK binary file for Phase B (KEK creation in 08-prepare-dataset-keys.ps1)

Both modes generate datastore metadata for the dataset publish step.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@

Prerequisites:
- 04-prepare-resources.ps1 must have been run.
- 06-setup-identity.ps1 must have been run (OIDC issuer configured).
- 06-setup-oidc-storage.ps1 must have been run and its issuer registered.

.PARAMETER resourceGroup
Azure resource group containing the resources.

.PARAMETER collaborationName
Name of the collaboration resource.
.PARAMETER collaborationId
Frontend UUID of the collaboration.

.PARAMETER contractId
Contract identifier used to compute the federation subject (default: analytics).
Contract identifier used to compute the federation subject (default: Analytics).

.PARAMETER userId
User identifier used to compute the federation subject.
Expand Down Expand Up @@ -75,7 +75,7 @@ $PSNativeCommandUseErrorActionPreference = $true
# Read issuer URL.
$issuerUrlFile = Join-Path $outDir $resourceGroup "issuer-url.txt"
if (-not (Test-Path $issuerUrlFile)) {
Write-Host "ERROR: '$issuerUrlFile' not found. Run 06-setup-identity.ps1 first." -ForegroundColor Red
Write-Host "ERROR: '$issuerUrlFile' not found. Run 06-setup-oidc-storage.ps1 first." -ForegroundColor Red
exit 1
}
$issuerUrl = (Get-Content $issuerUrlFile -Raw).Trim()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@

.PARAMETER TokenFile
Token file for frontend authentication. If omitted, uses CLEANROOM_FRONTEND_TOKEN,
then MANAGEDCLEANROOM_ACCESS_TOKEN, then the current Azure CLI ARM access token.
then MANAGEDCLEANROOM_ACCESS_TOKEN, then the per-persona temp token file,
then the current Azure CLI ARM access token.
#>
param(
[Parameter(Mandatory)]
Expand Down Expand Up @@ -119,6 +120,10 @@ function Get-SkrPolicy {
$token = $env:CLEANROOM_FRONTEND_TOKEN.Trim()
} elseif ($env:MANAGEDCLEANROOM_ACCESS_TOKEN) {
$token = $env:MANAGEDCLEANROOM_ACCESS_TOKEN.Trim()
} elseif (Test-Path -LiteralPath (
Join-Path ([IO.Path]::GetTempPath()) "msal-idtoken-$persona.txt") -PathType Leaf) {
$token = (Get-Content -LiteralPath (
Join-Path ([IO.Path]::GetTempPath()) "msal-idtoken-$persona.txt") -Raw).Trim()
} else {
try {
$token = az account get-access-token --resource "https://management.azure.com/" `
Expand Down
204 changes: 179 additions & 25 deletions demos/analytics-using-managedcleanroom/scripts/README-SCRIPTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ Choose one scenario:

## Phase 1 — Owner creates the collaboration (control plane)

> **Destructive clean setup:** If the named collaboration already exists, this
> script deletes it, waits until ARM reports it absent, and creates a fresh one.
> It does not reuse or resume the old collaboration. Its existing datasets,
> queries, governance state, and managed infrastructure are not retained.
> A deletion error or timeout stops setup before creation.
> Use `-DryRun` to preview, or `manage-collaboration.ps1` for actions that should
> keep an existing collaboration.

```powershell
$collabName = "collab1"
$deployParams = @{
Expand All @@ -50,6 +58,27 @@ $deployParams = @{

This is Bicep (declarative collaboration resource) + the ARM *action* steps
(`enableWorkload`, `addCollaborator`). Runtime ~35 min. See [scripts/bicep/](bicep/).
ARM uses `2026-09-30-preview`; frontend calls use `2026-03-01-preview`.
The only currently supported sizing is `Standard_D4ds_v5` with **3 nodes**.
Both the script and Bicep reject larger configurations until support is expanded.
Quota and regional capacity remain prerequisites, not guarantees made by these scripts.

### Timeouts

`-TimeoutMinutes` defaults to **60 minutes per lifecycle operation**, not for the
entire script. Delete, create, enable/readiness, and each collaborator addition
have separate budgets. A complete clean setup can therefore take over an hour.
The budget starts before submitting each operation; creation uses
`az deployment group create --no-wait` and polls both deployment and collaboration
state, so it does not hide a blocking creation wait before starting the timer.
Recovery tracks the ARM operation URL, not `provisioningState`, which may remain
`Succeeded` while recovery is still in progress.

The polling deadline is checked between Azure CLI requests; it is not a hard
process-kill timeout on an individual network request. On timeout, Azure work
may still be running: inspect its status before retrying. Fast setup stops before
creation if deletion fails or times out. Query monitoring has its own independent
60-minute default and does not cancel or resubmit a query on timeout.

### Optional target resource configuration

Expand All @@ -73,19 +102,29 @@ including the case-sensitive `iPTagConfiguration` spelling, not CLI shorthand
such as `i-p-tag-configuration`.

The script merges this object with `aksSku` and `nodePoolSize`. If those fields
also appear in the object, the object values take precedence; SKU validation
and the node-count range of 3-10 still apply. With the object omitted, existing
also appear in the object, the object values take precedence; they must still
be `Standard_D4ds_v5` and `3`. With the object omitted, existing
behavior is unchanged (`Standard_D4ds_v5`, 3 nodes by default).

`-DryRun` prints the effective configuration without deploying; it still reads
the current Azure CLI account. Remove `-DryRun` to create the collaboration.
`-DryRun` prints the effective configuration without deploying; it reads the
current Azure CLI account unless `-Subscription` is supplied. Remove `-DryRun`
to create the collaboration.
The script passes the object through a temporary JSON file, which is removed
even if deployment fails. Direct Bicep deployments can also supply the optional
`targetResourceConfiguration` object parameter.

These settings apply when creating a new collaboration. An existing
collaboration is skipped, not updated. `-DeleteExistingCollab` deletes and
recreates the collaboration; it is not an in-place configuration change.
These settings apply to the freshly created collaboration, including when
replacing an existing one. The script always performs delete -> wait for absence
-> create -> enable Analytics -> wait for health -> add additional collaborators.
If no collaboration exists, it goes directly to creation.
`-DeleteExistingCollab` remains accepted for compatibility but is already true
by default; explicitly passing `-DeleteExistingCollab:$false` is rejected.
After recreation, repeat Phases 2 onward using the new frontend collaboration UUID.

For creation-time collaborators, pass `-Collaborators @("<email>")`.
`-AdditionalCollaborators` adds participants after the new collaboration is ready.
To add participants without deleting an existing collaboration, use the
standalone management commands below instead of rerunning fast setup.

---

Expand All @@ -101,7 +140,9 @@ $PSNativeCommandUseErrorActionPreference = $true
$persona = "woodgrove" # or "northwind"
$personaRg = "cr-e2e-$persona-rg"
$collabName = "collab1" # name chosen by the owner in Phase 1
$suffix = "-v1" # use a new suffix for a new dataset iteration
$EncryptionMode = "SSE" # SSE or CPK
$iteration = 1 # increase for each new dataset iteration
$suffix = if ($EncryptionMode -eq "CPK") { "-cpk-v$iteration" } else { "-v$iteration" }

. .\scripts\frontend\Invoke-Frontend.ps1
$fe = Get-FrontendContext -Persona $persona
Expand All @@ -126,7 +167,8 @@ already active (including the owner).
```powershell
.\scripts\04-prepare-resources.ps1 -resourceGroup $personaRg -persona $persona -location westus
.\demos\generate-data.ps1 -persona $persona
.\scripts\05-prepare-data.ps1 -resourceGroup $personaRg -variant sse -persona $persona `
$variant = $EncryptionMode.ToLowerInvariant()
.\scripts\05-prepare-data.ps1 -resourceGroup $personaRg -variant $variant -persona $persona `
-dataDir ".\generated\datasource\$persona\csv" -datasetSuffix $suffix
.\scripts\frontend\05-fetch-jwks.ps1 -Persona $persona -CollaborationId $collabId `
-outDir "generated\$personaRg"
Expand All @@ -143,7 +185,7 @@ $oidcParams = @{
.\scripts\frontend\05-set-issuer-url.ps1 -Persona $persona -CollaborationId $collabId `
-outDir "generated\$personaRg"
.\scripts\07-grant-access.ps1 -resourceGroup $personaRg -collaborationId $collabId `
-contractId "Analytics" -userId $personaOid -EncryptionMode SSE
-contractId "Analytics" -userId $personaOid -EncryptionMode $EncryptionMode

if ($persona -eq "woodgrove") {
.\scripts\08-build-dataset-body.ps1 -resourceGroup $personaRg -persona $persona `
Expand All @@ -153,9 +195,12 @@ if ($persona -eq "woodgrove") {
}
```

For CPK encryption instead, follow the CPK upload, access, and key-preparation
steps in [README-API.md](../README-API.md). Use a distinct dataset suffix for
each iteration and a separate output directory for each query run.
For CPK, install AzCopy first. The upload helper generates the DEKs and uploads
with Azure Storage CPK encryption; do not manually encrypt the input files.
Access setup grants the workload its Key Vault permissions.
Prepare the KEKs **after publishing** in Phase 4, not before.
Use a distinct dataset suffix for each iteration and a separate output directory
for each query run. See README-API.md Appendix C for the key-release architecture.

---

Expand All @@ -171,8 +216,18 @@ if ($persona -eq "woodgrove") {
.\scripts\frontend\06-publish-dataset.ps1 -Persona $persona -CollaborationId $collabId `
-DocumentId "woodgrove-output-csv$suffix" -BodyFile "generated\publish\woodgrove-output-dataset.json"
}

if ($EncryptionMode -eq "CPK") {
.\scripts\08-prepare-dataset-keys.ps1 -resourceGroup $personaRg -persona $persona `
-collaborationId $collabId -frontendEndpoint $fe.Frontend
}
```

Key preparation uses the explicit `-TokenFile` when supplied, then the frontend
environment tokens, then the per-persona temp token file. If you used a custom
token-file location for other steps, pass that same file here.
Publish all datasets before retrieving their SKR policies.

---

## Phase 5 — Owner builds and publishes the chosen query
Expand Down Expand Up @@ -238,13 +293,13 @@ $queryInfo = Invoke-Frontend -Context $fe -Path "$collabId/analytics/queries/$qu
if ($queryInfo.state -ne "Accepted") { throw "Wait for the required query approvals before running." }

# Run + wait for completion + print run history/audit
.\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId `
-QueryName $queryName -ScaleSku small
$scaleSku = "small"
$jobId = .\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId `
-QueryName $queryName -ScaleSku $scaleSku -TimeoutMinutes 60

# Copy the job ID printed by the orchestrator; isolate this run's output.
$jobId = "<job-id-printed-above>"
# The orchestrator returns the job ID; isolate this run's output.
.\scripts\11-download-output.ps1 -resourceGroup $personaRg -datasetSuffix $suffix `
-JobId $jobId -OutputDir ".\generated\output\SSE-$jobId"
-JobId $jobId -OutputDir ".\generated\output\$EncryptionMode-$jobId"
```

Re-run an accepted query by repeating Phase 7 — no re-setup needed.
Expand All @@ -253,6 +308,12 @@ Both `run-query.ps1` and `09-run-query.ps1` accept `-ScaleSku small` (default),
`medium`, or `large`; this controls the Spark execution profile, not the AKS
node-pool SKU. They also accept `-StartDate` / `-EndDate`. Check the quota and
profile details in README-API.md Step 09 before selecting a larger profile.
`large` remains preview-only, not production-ready. For date filtering:

```powershell
$jobId = .\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId `
-QueryName $queryName -ScaleSku medium -StartDate "2025-09-01" -EndDate "2025-09-02"
```

A failed or submission-failed run causes the monitor and orchestrator to throw.
If submission returns no job ID, check run history before retrying rather than
Expand All @@ -274,16 +335,109 @@ assuming no run was scheduled.

### Local request previews versus service dry runs

Only the frontend step/orchestrator scripts and
`scripts/bicep/deploy-managed-cleanroom.ps1` support `-DryRun`. Their switch
prints planned requests instead of sending them; the ARM wrappers still read
the current Azure CLI account. Resource provisioning, upload, OIDC storage,
The frontend step/orchestrator scripts, Bicep deployment/management wrappers,
and `common/add-app-collaborator.ps1` support `-DryRun`. Their switch prints
planned requests instead of sending them; ARM wrappers read the current Azure
CLI account unless `-Subscription` is supplied. Resource provisioning, upload, OIDC storage,
access, body-building, key-preparation, download and Grafana helpers do **not**
support this switch. Body builders write local files even though they do not
call the service.

A local preview does not validate authentication, dataset contents, approval
state or effective `skuSettings`; the run helpers return only a `<job-id>`
placeholder. For an actual service-side dry run, use the
`dryRun: true` request body in README-API.md Step 09; that sends a frontend
request but does not execute the Spark query.
placeholder. For an actual service-side dry run, both query runners accept `-ServiceDryRun`:

```powershell
$preview = .\scripts\frontend\run-query.ps1 -Persona woodgrove -CollaborationId $collabId `
-QueryName $queryName -ScaleSku medium -ServiceDryRun
$preview.skuSettings | ConvertTo-Json -Depth 10
```

This sends `dryRun: true` but does not publish, execute, monitor, or fetch results.
It cannot be combined with `-DryRun` or the orchestrator's `-BodyFile`.

## Inspect, diagnose, cancel, and change consent

```powershell
$readArgs = @{ Persona = $persona; CollaborationId = $collabId }
.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Collaborators
.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Datasets
.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Dataset `
-DocumentId "$persona-input-csv$suffix"
.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Queries
.\scripts\frontend\get-frontend-data.ps1 @readArgs -Resource Query -QueryName $queryName

# One detailed snapshot, even for a stuck/failed run:
$result = .\scripts\frontend\10-monitor-query.ps1 @readArgs -JobId $jobId -Once
$result.events | Format-Table type, reason, message, count -Wrap
$result.status.applicationState | ConvertTo-Json -Depth 5

# Cancel only a persistent failure/unwanted run, not a single early FailedMount.
.\scripts\frontend\09-cancel-query.ps1 @readArgs -QueryName $queryName -JobId $jobId

# Enable or disable consent without republishing.
.\scripts\frontend\06-set-consent.ps1 @readArgs `
-DocumentId "$persona-input-csv$suffix" -ConsentAction disable
```

The reader also supports `Collaborations` (`-ActiveOnly`), `Invitations`
(`-PendingOnly`), `OidcKeys`, `Run`, `RunHistory`, and `AuditEvents`.
Polling prints new/updated events, stops on failure/cancellation, and times out
after 60 minutes by default. A timeout **does not cancel or resubmit** the run.
The quota/capacity/network troubleshooting tables in the main guides still apply;
a generic executor failure alone does not establish a capacity problem.

## Manage an existing collaboration and retrieve diagnostics

These are ARM operations, using the selected Azure subscription or an explicit
`-Subscription`. Mutations wait by default; `-NoWait` submits only.

```powershell
$armArgs = @{ ResourceGroup = $collabRg; CollaborationName = $collabName }
$collab = .\scripts\bicep\manage-collaboration.ps1 @armArgs -Action Show
$collab.properties.health | ConvertTo-Json -Depth 10
.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action EnableWorkload
.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action AddCollaborator `
-Collaborators @("<northwind-email>")

.\scripts\frontend\12-get-readonly-kubeconfig.ps1 @armArgs -OutFile ".\readonly.kubeconfig"
.\scripts\12-open-grafana-dashboard.ps1 -KubeConfigPath ".\readonly.kubeconfig"
```

Use recovery only as a last resort; deletion permanently removes the collaboration
and its associated resources. Neither is an automatic response to a query failure:

```powershell
.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action Recover -ForceRecover
# Delete only (does NOT recreate):
.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action Delete
```

## SPN participants

Acquire the SPN token with `common/get-sp-token-sni.ps1` as described in the main
guides and extract its JWT `oid` for the FIC subject. ARM operations use the
current Azure CLI login; setting a frontend token does not change that login.
For collaborator registration, use all three identity fields:

```powershell
$app = @{
userIdentifier = "<app-client-id>"
objectId = "<enterprise-application-object-id>"
tenantId = "<tenant-id>"
}
.\scripts\bicep\manage-collaboration.ps1 @armArgs -Action AddCollaborator -Collaborators @($app)
# The same object is accepted by deploy-managed-cleanroom.ps1:
# -Collaborators @($app) at creation, or -AdditionalCollaborators @($app).
```

`common/add-app-collaborator.ps1` also accepts `-AppClientId`, `-ObjectId` and
`-TenantId`. SPNs auto-activate and need no invitation acceptance.

## Offline validation

These target-configuration tests mock Azure CLI; they do not deploy or run queries:

```powershell
.\scripts\bicep\tests\test-target-resource-configuration.ps1
```
Loading
Loading