@aidalinfo/m365-mcp 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,7 +76,7 @@ Outlook / calendar connectors: these identities are dedicated to this server.
76
76
  | Licence | Tools (or parts) | Without it |
77
77
  |---|---|---|
78
78
  | **Entra ID P1** (Business Premium, E3/E5, standalone) | `m365_user_activity`, `m365_user_auth_methods` tenant view, `m365_conditional_access` policies, `m365_audit_signins`; in the snapshot: last sign-in and the tenant MFA report | `unsupported_by_tenant` (the snapshot falls back to the admins' own methods for MFA and marks inactivity as *not evaluated*) |
79
- | **Entra ID P2** | `m365_directory_roles view=eligible` (PIM) | `unsupported_by_tenant` |
79
+ | **Entra ID P2** | `m365_directory_roles view=eligible` (PIM) | `unsupported_by_tenant` (see *PIM control unavailable* below) |
80
80
  | **Intune** (Business Premium, EMS) | `m365_intune_devices` | `unsupported_by_tenant` |
81
81
 
82
82
  The tools stay registered on every tenant. `m365_capabilities` reads the tenant's service plans
@@ -127,14 +127,26 @@ A refused or unavailable API never looks like an empty list — the tool answers
127
127
  | Code | Meaning |
128
128
  |---|---|
129
129
  | `permission_missing` | 403 — the application lacks the Graph permission (or admin consent), see `m365_capabilities` |
130
+ | `rbac_denied` | Exchange accepted the token but its own role model refused: the identity's Exchange role group does not hold the cmdlet / parameter, or Exchange knows no role for the application. Fix the role group — never a broader admin role (README → Exchange mailbox audit) |
130
131
  | `unsupported_by_tenant` | The tenant cannot serve this (no Entra P1 for sign-ins, no Teams licence…) |
131
132
  | `license_unavailable` | No free unit, SKU not enabled, or a licence prerequisite (usage location, plan dependency) |
132
133
  | `not_found` / `ambiguous_target` | Nothing matches / several objects match a name — pass the id |
133
134
  | `conflict` | Already exists, concurrent change, precondition failed |
134
135
  | `throttled` / `transient` | 429 after the bounded retries (with `Retry-After`) / 5xx, timeout, network |
136
+ | `service_error` | Microsoft answered a 4xx that only carries one of its own internal exceptions (e.g. `UnknownError` / `CultureNotFoundException` on the PIM API). The result is **unknown**: it proves neither a missing licence, nor a missing permission, nor an empty list |
135
137
  | `auth_failed` / `tenant_mismatch` / `forbidden_permission` | Token refused / token for another tenant or app / token carries a permission refused by policy |
136
138
  | `refused` / `confirmation_invalid` | A guard refused the write / the confirmation token is expired, reused, or the state changed |
137
139
 
140
+ **PIM control unavailable.** `m365_directory_roles view=eligible` concludes to a missing Entra ID P2
141
+ licence only when Graph says so or refuses while the subscribed SKUs carry no `AAD_PREMIUM_P2` plan. The
142
+ PIM back end has also been seen answering HTTP 400 `UnknownError` / `CultureNotFoundException` ("Culture
143
+ is not supported … `*` is an invalid culture identifier"): that is reported as `service_error` with the
144
+ status, Graph's code and the request ids. It says nothing about the licence, the eligible roles or the
145
+ application's rights — report the PIM control as *not performed*, never as "no eligible role", and do
146
+ not add permissions or roles to work around it. Node's `fetch` sends `Accept-Language: *` when no
147
+ language is set, so the server names `Accept-Language: en-US` on this PIM request only (no other Graph
148
+ call, no retry); whether `*` was the cause on the affected tenant has not been confirmed there.
149
+
138
150
  Each error carries Microsoft's `request-id` (quote it to Microsoft support) and the
139
151
  `client-request-id` the server sent. The raw Graph body is never returned.
140
152
 
@@ -309,15 +321,15 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
309
321
  | `m365_group_info` | `GET /groups/{id}`<br>`GET /groups/{id}/members/$count`<br>`GET /groups/{id}/owners` | `GroupMember.Read.All` | `Group.Read.All`, `Directory.Read.All` | — | — | — |
310
322
  | `m365_group_members` | `GET /groups/{id}/members` | `GroupMember.Read.All` + `User.Read.All` | `Directory.Read.All` | — | — | — |
311
323
  | `m365_teams` | `GET /teams` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | — | — | — |
312
- | `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `TeamSettings.ReadWrite.All`, `Directory.Read.All` | `TeamSettings.Read.Group` | — | — |
324
+ | `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | `TeamSettings.Read.Group` | — | — |
313
325
  | `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` | — | — |
314
- | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `TeamMember.ReadWrite.All`, `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
315
- | `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `ChannelMember.ReadWrite.All`, `Directory.Read.All` | `ChannelMember.Read.Group` | — | — |
326
+ | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
327
+ | `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `Directory.Read.All` | `ChannelMember.Read.Group` | — | — |
316
328
  | `m365_usage_reports` | `GET /reports/getMailboxUsageDetail(period='D7')`<br>`GET /reports/getOneDriveUsageAccountDetail(period=…)`<br>`GET /reports/getSharePointSiteUsageDetail(period=…)`<br>`GET /reports/getOffice365ActiveUserDetail(period=…)` | `Reports.Read.All` | — | — | mailbox type (recipientType / withMailboxType) — or the exchange feature of the audit identity: `MailboxSettings.Read` | — |
317
329
  | `m365_service_health` | `GET /admin/serviceAnnouncement/healthOverviews`<br>`GET /admin/serviceAnnouncement/issues`<br>`GET /admin/serviceAnnouncement/messages` | `ServiceHealth.Read.All` | — | — | view=messages (message center): `ServiceMessage.Read.All` | — |
318
- | `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
319
- | `m365_site_info` | `GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root`<br>`GET /sites/{id}/drives` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
320
- | `m365_sharing_links` | `GET /drives/{driveId}/root:/{path}:`<br>`GET /drives/{driveId}/items/{itemId}/children`<br>`GET /drives/{driveId}/items/{itemId}/permissions` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Files.Read.All` | — | — | — |
330
+ | `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | — | — | — | — |
331
+ | `m365_site_info` | `GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root`<br>`GET /sites/{id}/drives` | `Sites.Read.All` | — | — | — | — |
332
+ | `m365_sharing_links` | `GET /drives/{driveId}/root:/{path}:`<br>`GET /drives/{driveId}/items/{itemId}/children`<br>`GET /drives/{driveId}/items/{itemId}/permissions` | `Sites.Read.All` | `Files.Read.All` | — | — | — |
321
333
  | `m365_directory_roles` | `GET /roleManagement/directory/roleAssignments?$expand=principal`<br>`GET /roleManagement/directory/roleDefinitions`<br>`GET /roleManagement/directory/roleEligibilityScheduleInstances (view=eligible)` | `RoleManagement.Read.Directory` | `RoleManagement.Read.All`, `Directory.Read.All` | — | view=eligible (PIM): `RoleManagement.Read.Directory` (Entra ID P2) | — |
322
334
  | `m365_user_auth_methods` | `GET /users/{id}/authentication/methods`<br>`GET /reports/authenticationMethods/userRegistrationDetails (tenant view)` | `UserAuthenticationMethod.Read.All` | — | — | tenant view (without user): `AuditLog.Read.All` (Entra ID P1) | — |
323
335
  | `m365_user_activity` | `GET /users?$select=…,signInActivity` | `AuditLog.Read.All` + `User.Read.All` | — | — | — | Entra ID P1 |
@@ -400,14 +412,37 @@ grants and application deletion stay out of scope. Scalar PATCH operations re-re
400
412
  the request and preserve unrelated fields. This implementation does not claim atomic concurrency
401
413
  control: a narrow residual last-writer-wins window remains and is documented explicitly.
402
414
 
403
- ### Refused by default
415
+ ### Read identity: read permissions only
416
+
417
+ The token provider **refuses** (`forbidden_permission`) a read-identity token carrying any
418
+ permission that is not a read, before any Graph call. One classification (`classifyPermission` in
419
+ `src/permissions.ts`) is shared by the token provider and `m365_capabilities`:
420
+
421
+ - **read** — `<Resource>.Read` or `<Resource>.ReadBasic`, optionally followed by plain scope segments
422
+ (`User.Read.All`, `RoleManagement.Read.Directory`, `MailboxSettings.Read`). Every permission of the
423
+ read matrix above has this shape and is accepted;
424
+ - **write** — a segment after the resource names a write verb (`ReadWrite`, `FullControl`,
425
+ `EnableDisable`, `Create`, `Manage`, `Send`, `Invite`, `Selected`…): `User.ReadWrite.All`,
426
+ `GroupMember.ReadWrite.All`, `LicenseAssignment.ReadWrite.All`, `User.EnableDisableAccount.All`,
427
+ `Sites.FullControl.All`, `Sites.ReadWrite.All`, the broad permissions below…;
428
+ - **unknown** — any other shape (`Calls.JoinGroupCall.All`…): **fail-closed**, treated as a write.
429
+
430
+ The error names every refused permission (writes and unrecognised ones separately), never a token
431
+ or a secret. `M365_ALLOW_BROAD_PERMISSIONS` **does not apply** to the read identity, and there is no
432
+ compatibility switch: remove the permission from the read Entra app (the server never changes Entra
433
+ permissions or consents itself) and give writes to the separate write identity (`M365_WRITE_CLIENT_ID`,
434
+ `M365_MODE=full`). Since 0.5.3 the read tools no longer list write permissions (`Sites.ReadWrite.All`,
435
+ `Sites.FullControl.All`, `TeamSettings.ReadWrite.All`, `TeamMember.ReadWrite.All`,
436
+ `ChannelMember.ReadWrite.All`) as "also accepted".
404
437
 
405
- The token provider **refuses** a token carrying any of: `Directory.ReadWrite.All`,
438
+ ### Refused by default (write identity)
439
+
440
+ The token provider **refuses** a write-identity token carrying any of: `Directory.ReadWrite.All`,
406
441
  `RoleManagement.ReadWrite.Directory`, `Application.ReadWrite.All`, `AppRoleAssignment.ReadWrite.All`,
407
442
  `Policy.ReadWrite.ConditionalAccess`, `UserAuthenticationMethod.ReadWrite.All` (`forbidden_permission`).
408
- `M365_ALLOW_BROAD_PERMISSIONS=true` lifts this knowingly — do not. Never give a technical user the
409
- Global Administrator role for this server: it uses application permissions only.
410
- `m365_capabilities` also warns when the **read** identity holds any write permission.
443
+ `M365_ALLOW_BROAD_PERMISSIONS=true` lifts this knowingly for the write identity only — do not. It
444
+ never lifts the read-identity check above, nor the exact allowlist of the entra identity. Never give
445
+ a technical user the Global Administrator role for this server: it uses application permissions only.
411
446
 
412
447
  Every token is also checked for `tid` = `M365_TENANT_ID`, `appid` = the configured client id and
413
448
  `aud` = Microsoft Graph (`tenant_mismatch` / `auth_failed` otherwise). `M365_TENANT_ID` must be a
@@ -421,7 +456,7 @@ Without `M365_AUDIT_APP_CLIENT_ID` none of these tools exists.
421
456
 
422
457
  | Tool | Feature | API | Permission on that API | What |
423
458
  |---|---|---|---|---|
424
- | `m365_mailbox_permissions` | exchange | Exchange Online `InvokeCommand` | `Exchange.ManageAsApp` + **read-only** Exchange role | Full Access, Send As, Send on behalf of a mailbox, or of every shared mailbox |
459
+ | `m365_mailbox_permissions` | exchange | Exchange Online `InvokeCommand` | `Exchange.ManageAsApp` + **read-only** Exchange role | Full Access, Send As, Send on behalf of a mailbox, or of every shared mailbox — explicit grants only; a right Exchange refused to read is `NOT EVALUATED`, never "none" |
425
460
  | `m365_activity_collect` | activity | Office 365 Management Activity | `ActivityFeed.Read` | Collects the unified audit log (SharePoint/OneDrive, Exchange, Entra, Teams) into a local store |
426
461
  | `m365_activity_search` | activity | (local store) | `ActivityFeed.Read` | "Who deleted / shared / downloaded this file? who changed these rights?" over up to 180 days |
427
462
  | `m365_site_permissions` | sharepoint | SharePoint REST `/_api` | `Sites.Selected` + per-site `fullcontrol` | Site admins, Owners / Members / Visitors and their members, Everyone claims, external users, libraries with broken inheritance |
@@ -455,17 +490,11 @@ or the smoke script): history builds up to the retention. Unified audit must be
455
490
  1. **Create** the Entra app `m365-mcp-audit` (single tenant), **certificate** credential (or federation).
456
491
  Give it **no Microsoft Graph permission**.
457
492
  2. **exchange**: *API permissions → APIs my organization uses → Office 365 Exchange Online →
458
- Application → `Exchange.ManageAsApp`*, admin consent. Then a read-only role, preferably a custom
459
- role group (least privilege), in Exchange Online PowerShell:
460
- ```powershell
461
- New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-audit
462
- New-RoleGroup -Name "m365-mcp-audit (read)" -Roles "View-Only Recipients"
463
- Add-RoleGroupMember -Identity "m365-mcp-audit (read)" -Member <enterprise-app-object-id>
464
- ```
465
- Check that the role covers the three cmdlets (`Get-ManagementRoleEntry "View-Only Recipients\Get-RecipientPermission"`);
466
- if one is missing, add the view-only role that holds it — never a role with `Add-*`/`Set-*`.
467
- Alternative: Entra role **Global Reader** on the service principal (read-only, but broader).
468
- Never Exchange Administrator.
493
+ Application → `Exchange.ManageAsApp`*, admin consent. Then a **view-only** Exchange role group
494
+ holding exactly the three `Get-*` cmdlets the server sends, and no Entra directory role — the full
495
+ procedure, its checks and the acceptance are in [Exchange mailbox audit](#exchange-mailbox-audit-only-read-only).
496
+ Never Exchange Administrator, Organization Management or Global Administrator; Global Reader is
497
+ accepted but broader than needed (`m365_capabilities` warns).
469
498
  3. **activity**: *Office 365 Management APIs → Application → `ActivityFeed.Read`* only (not
470
499
  `ActivityFeed.ReadDlp`), admin consent. Check that auditing is on (Purview → Audit). Start the
471
500
  subscriptions once: `M365_ACTIVITY_START_SUBSCRIPTIONS=true` + `m365_activity_collect
@@ -483,6 +512,150 @@ or the smoke script): history builds up to the retention. Unified audit must be
483
512
  7. **Revoke**: remove the feature from `M365_AUDIT_APP_FEATURES` (tools disappear), or disable the
484
513
  enterprise app in Entra (no token anywhere), and remove the role group / site grants.
485
514
 
515
+ ## Exchange mailbox audit only (read-only)
516
+
517
+ Who can use a shared mailbox — **Full Access, Send As, Send on behalf** — for a connection that stays
518
+ in `M365_MODE=readonly` (the Athéna connection, #152). This path adds exactly one tool,
519
+ `m365_mailbox_permissions`, and the shared-mailbox rights of `m365_access_review_snapshot`. It never
520
+ enables `exchange-delegation`, a write family, the `activity` or `sharepoint` features, `Mail.Read`,
521
+ `full_access_as_app`, `Sites.FullControl.All`, nor an Entra administrator role, and it reads no
522
+ message content.
523
+
524
+ **Nothing here authorises a change.** Creating the identity, the admin consent, the Exchange role
525
+ group and the acceptance run on a test mailbox each need their own explicit approval; this section
526
+ only says how to do them and how to check them.
527
+
528
+ ### What the server guarantees (unit-tested, no tenant needed)
529
+
530
+ - Readonly + `M365_AUDIT_APP_FEATURES=exchange`: the readonly tools plus `m365_mailbox_permissions`,
531
+ nothing else — `M365_WRITE_*` / `M365_EXCHANGE_*` present in the environment are not even read.
532
+ - The audit identity only ever sends `Get-Mailbox (Identity, RecipientTypeDetails, ResultSize)`,
533
+ `Get-MailboxPermission (Identity)`, `Get-RecipientPermission (Identity, AccessRights=SendAs)`, with
534
+ validated values; any other cmdlet or parameter is refused before a token is even requested.
535
+ - Its Exchange token must hold exactly `Exchange.ManageAsApp` (an extra role ⇒ `forbidden_permission`)
536
+ and no write-capable directory role (`wids`); it never gets a Graph token.
537
+ - Listing the tools and `m365_capabilities` make **no Exchange call**; a call refused by the server
538
+ (invalid mailbox, cmdlet outside the list) sends nothing to Microsoft. Only the read itself does.
539
+ - An absence of collection is never an empty list: see *Reading the answers* below.
540
+
541
+ ### 1. Prepare the identity (under a separate approval)
542
+
543
+ 1. Entra: the single-tenant app `m365-mcp-audit`, **certificate** credential (or workload identity
544
+ federation — a client secret is a startup error), **no Microsoft Graph permission**.
545
+ 2. *API permissions → APIs my organization uses → Office 365 Exchange Online → Application →
546
+ `Exchange.ManageAsApp`*, then admin consent. Assign **no** Entra directory role.
547
+ 3. Exchange Online PowerShell, as an Exchange administrator — a custom role reduced to the three
548
+ `Get-*` cmdlets, in a dedicated role group:
549
+ ```powershell
550
+ New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-audit
551
+ New-ManagementRole -Parent "Mail Recipients" -Name "m365-mcp mailbox audit (read)"
552
+ $keep = "Get-Mailbox","Get-MailboxPermission","Get-RecipientPermission"
553
+ Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Where-Object { $_.Name -notin $keep } | Remove-ManagementRoleEntry -Confirm:$false
554
+ New-RoleGroup -Name "m365-mcp-audit (read)" -Roles "m365-mcp mailbox audit (read)"
555
+ Add-RoleGroupMember -Identity "m365-mcp-audit (read)" -Member <enterprise-app-object-id>
556
+ ```
557
+ The parent only provides the cmdlets: the custom role keeps the three `Get-*` entries, so the
558
+ identity cannot change anything even if the server were bypassed. Do not remove parameters below
559
+ what the server sends (list above).
560
+
561
+ ### 2. Verify the principal and the RBAC (read-only cmdlets)
562
+
563
+ ```powershell
564
+ Get-ServicePrincipal -Identity <appId> | Format-List DisplayName,AppId,ObjectId # registered in Exchange
565
+ Get-RoleGroupMember "m365-mcp-audit (read)" # the application is a member
566
+ (Get-RoleGroup "m365-mcp-audit (read)").Roles # only the custom role
567
+ Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Format-Table Name,Parameters # exactly the three cmdlets
568
+ Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Where-Object { $_.Name -notlike "Get-*" } # must return nothing
569
+ ```
570
+
571
+ Expected: the three entries, with at least `Identity, RecipientTypeDetails, ResultSize` on
572
+ `Get-Mailbox`, `Identity` on `Get-MailboxPermission`, `Identity, AccessRights` on
573
+ `Get-RecipientPermission`; the application in no other role group, and with no Entra directory role.
574
+ Then `m365_capabilities` must show `Mode: readonly`, `Exchange delegation family: disabled`,
575
+ `Exchange mailbox audit (read-only): enabled — the server sends only …` and `m365_mailbox_permissions`
576
+ `granted` (the token holds exactly `Exchange.ManageAsApp`).
577
+
578
+ **On `rbac_denied`**, add only the missing `Get-*` entry to the custom role
579
+ (`Add-ManagementRoleEntry "m365-mcp mailbox audit (read)\<cmdlet>"`). Never answer it with Exchange
580
+ Administrator, Organization Management, Global Administrator, Global Reader, `full_access_as_app` or
581
+ `Mail.Read`: the error is precise enough to fix the role group.
582
+
583
+ ### 3. Configure the connection
584
+
585
+ ```bash
586
+ M365_MODE=readonly
587
+ M365_AUDIT_APP_CLIENT_ID=<appId>
588
+ M365_AUDIT_APP_CERT_PATH=/etc/m365-mcp/audit.pem # or M365_AUDIT_APP_FEDERATED_TOKEN_FILE
589
+ M365_AUDIT_APP_FEATURES=exchange # exchange only: no activity, no sharepoint
590
+ M365_EXCHANGE_ORGANIZATION=<tenant>.onmicrosoft.com # else read from Graph
591
+ ```
592
+
593
+ No `M365_WRITE_*`, `M365_EXCHANGE_CLIENT_ID` (that is the delegation identity), `M365_ACTIVITY_*` or
594
+ `M365_SHAREPOINT_*`. Only this connection's environment changes: the read identity, the other
595
+ connections and the snapshots already in `M365_SNAPSHOT_DIR` are untouched (same schema; a snapshot
596
+ taken without the exchange feature is compared as *not evaluated*, never as "rights removed").
597
+
598
+ ### 4. Acceptance on the authorised test mailbox (under the approval)
599
+
600
+ 1. Prerequisite: a **test shared mailbox** named in the approval, holding at least one explicit
601
+ grant of each right (Full Access, Send As, Send on behalf) — set up by an administrator, not by
602
+ this server.
603
+ 2. The administrator's reference, in Exchange Online PowerShell:
604
+ ```powershell
605
+ $m = Get-Mailbox -Identity <test-mailbox>
606
+ [pscustomobject]@{
607
+ mailbox = [string]$m.PrimarySmtpAddress
608
+ fullAccess = @(Get-MailboxPermission -Identity $m.Identity | Where-Object { -not $_.IsInherited -and -not $_.Deny -and $_.AccessRights -match 'FullAccess' -and [string]$_.User -notmatch '^(NT AUTHORITY\\|S-1-5-)' } | ForEach-Object { [string]$_.User })
609
+ sendAs = @(Get-RecipientPermission -Identity $m.Identity -AccessRights SendAs | Where-Object { -not $_.IsInherited -and $_.AccessControlType -eq 'Allow' -and [string]$_.Trustee -notmatch '^(NT AUTHORITY\\|S-1-5-)' } | ForEach-Object { [string]$_.Trustee })
610
+ sendOnBehalf = @($m.GrantSendOnBehalfTo | ForEach-Object { [string]$_ })
611
+ } | ConvertTo-Json | Set-Content -Encoding utf8 reference.json
612
+ ```
613
+ 3. The server, through the compiled MCP over stdio — only that mailbox is read:
614
+ ```bash
615
+ M365_SMOKE_MAILBOX=<test-mailbox> M365_SMOKE_EXCHANGE_REFERENCE=./reference.json node smoke.mjs --exchange-audit
616
+ ```
617
+ It refuses to start unless `M365_AUDIT_APP_FEATURES=exchange` exactly, forces `M365_MODE=readonly`
618
+ and passes no write / entra / delegation identity to the server. It checks: no `[WRITE]`, activity,
619
+ SharePoint or delegation tool; mode readonly and delegation family disabled in `m365_capabilities`;
620
+ the exact token role; the three rights read (none `NOT EVALUATED`) with one grant each; the same
621
+ trustees as the reference, right by right (case-insensitive). It ends with the secret / JWT leak check.
622
+ 4. Keep the report with the acceptance records (it names the test mailbox's trustees). A difference
623
+ in trustee **format** (display name vs UPN, alias) is a finding to record, not a reason to widen a role.
624
+
625
+ ### Reading the answers
626
+
627
+ | You see | Meaning | Next step |
628
+ |---|---|---|
629
+ | No `m365_mailbox_permissions`; `m365_capabilities`: *Exchange mailbox audit (read-only): not configured*; review: *Not covered by this configuration — mailboxAccess* | Identity / feature not configured | Steps 1–3, if approved |
630
+ | `auth_failed: … could not get a exchange token` | The token endpoint refused the credential (certificate, federation, consent) | Check the credential and the consent |
631
+ | `permission_missing … needs exactly Exchange.ManageAsApp on exchange` | The app lacks `Exchange.ManageAsApp` (or its consent) — no Exchange call was made | Step 1.2 |
632
+ | `forbidden_permission` | The token carries another role, or a write-capable directory role | Remove it |
633
+ | `auth_failed (exchange HTTP 401 …)` | Exchange refused a valid token: consent not propagated, or principal not registered | Wait, then `New-ServicePrincipal` (step 1.3) |
634
+ | `rbac_denied … Exchange knows no role for this application` | Principal registered without role group | `Add-RoleGroupMember` (step 1.3) |
635
+ | `rbac_denied … does not let this identity run <cmdlet> (<parameters>)` | The role group lacks that cmdlet or parameter | Add that `Get-*` entry only (step 2) |
636
+ | `not_found … Exchange has no object "<x>"` | No such mailbox (or outside the role's read scope) | Check the address |
637
+ | `- Send As: ⚠ NOT EVALUATED — <reason>` and `⚠ INCOMPLETE` | That right could not be read; the others were | Its holders are **unknown** — never report "nobody" |
638
+ | `- Full Access: none (no explicit grant)` | Read: Exchange returned no explicit grant | See the limits below |
639
+ | `⚠ Mailbox list truncated: … ResultSize 1000` | Connector limit: Exchange stopped at 1000 mailboxes | Mailboxes beyond it are not reviewed |
640
+ | `⚠ Permission list truncated (server page budget)` / `⚠ truncated` | Pagination budget (20 pages) reached | That right is partial |
641
+ | Review: *not evaluated — section(s) mailboxAccess failed / not configured*, or *⚠ partial — …* | Section not read, or read in part | The signal / change is not concluded |
642
+
643
+ ### Limits (stated in every answer)
644
+
645
+ Explicit grants only. Inherited entries, `Deny` entries and system principals (`NT AUTHORITY\…`,
646
+ `S-1-5-…`) are not listed — they are counted under *Not shown*. A trustee that is a group gives access
647
+ to its members, who are not expanded. Effective (transitive) rights are therefore **not** evaluated:
648
+ this is no exhaustive proof of who can open a mailbox — a separate piece of work if needed. Send on
649
+ behalf comes from the `GrantSendOnBehalfTo` property of `Get-Mailbox`; if Exchange does not return it,
650
+ the right is `NOT EVALUATED`. The review reads at most 300 shared mailboxes (flagged when cut).
651
+
652
+ ### Rollback
653
+
654
+ Remove `exchange` from `M365_AUDIT_APP_FEATURES` (or the whole `M365_AUDIT_APP_*` block) and restart:
655
+ the tool disappears and the review says *not configured*. Tenant side, under approval:
656
+ `Remove-RoleGroupMember` / `Remove-RoleGroup "m365-mcp-audit (read)"`, `Remove-ManagementRole`,
657
+ `Remove-ServicePrincipal`, then disable or delete the enterprise app.
658
+
486
659
  ## Environment
487
660
 
488
661
  | Variable | Default | Meaning |
@@ -511,7 +684,7 @@ or the smoke script): history builds up to the retention. Unified audit must be
511
684
  | `M365_SHAREPOINT_HOST` | — | Required by `sharepoint`: `<tenant>.sharepoint.com`, the only host its token goes to |
512
685
  | `M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL` | `false` | Accept `Sites.FullControl.All` instead of `Sites.Selected` — discouraged |
513
686
  | `M365_SNAPSHOT_DIR` | — | Absolute directory where `m365_access_review_snapshot` writes its dated JSON files (`0600`) and finds the previous ones; unset ⇒ the review is answered but not saved, and `compareWith` is refused |
514
- | `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept tokens with the refused permissions above |
687
+ | `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept write-identity tokens with the refused permissions above (never the read identity) |
515
688
 
516
689
  Exactly one credential per identity: several ⇒ startup error. Tokens are cached **in memory only**
517
690
  (renewed 5 min before expiry) — there is no MSAL / token cache on disk. The Graph base URL is not
@@ -637,6 +810,7 @@ Copy `.env.example` to `.env`, fill it, build (`npm run build`), then:
637
810
  node smoke.mjs # read identity: capabilities, then one bounded call per read tool
638
811
  node smoke.mjs --review # same, plus one full m365_access_review_snapshot
639
812
  node smoke.mjs --write # write identity, on dedicated acceptance objects only
813
+ node smoke.mjs --exchange-audit # Exchange mailbox audit acceptance: one authorised test mailbox, readonly
640
814
  ```
641
815
 
642
816
  In read mode, `unsupported_by_tenant` is accepted for the tools needing Entra ID P1/P2 or Intune
@@ -645,6 +819,10 @@ In read mode, `unsupported_by_tenant` is accepted for the tools needing Entra ID
645
819
  `M365_SMOKE_TEAM` adds the channel members of its first private channel, `M365_SMOKE_FOLDER` a
646
820
  `m365_sharing_links` call on that folder of the first listed site.
647
821
 
822
+ `--exchange-audit` is the acceptance of the [Exchange mailbox audit](#exchange-mailbox-audit-only-read-only):
823
+ readonly, `M365_AUDIT_APP_FEATURES=exchange` only, it reads `M365_SMOKE_MAILBOX` alone and compares it
824
+ with `M365_SMOKE_EXCHANGE_REFERENCE` (the administrator's PowerShell export) when set.
825
+
648
826
  `--write` requires `M365_MODE=full`, `M365_SMOKE_USER` and at least one of `M365_SMOKE_GROUP`,
649
827
  `M365_SMOKE_TEAM`, `M365_SMOKE_SKU`. **Create dedicated acceptance objects** (user, security group,
650
828
  team, a spare licence) whose names contain `M365_SMOKE_MARKER` (default `recette`); the script
@@ -684,6 +862,27 @@ snapshot, signals and comparison end to end.
684
862
 
685
863
  ## Validation status
686
864
 
865
+ - 0.6.0 (#152, Exchange mailbox audit in readonly): unit tests passing against a fake Exchange —
866
+ registered tools, cmdlets sent, `rbac_denied` / `auth_failed` / `permission_missing` / `not_found`
867
+ told apart, rights `NOT EVALUATED` instead of empty, ResultSize and page-budget cuts, access-review
868
+ sections *not configured* / *partial*, never compared as "rights removed". **No Microsoft call was
869
+ made for #152.** To validate, under approval, with `node smoke.mjs --exchange-audit` on the authorised
870
+ test mailbox: the role group derived from *Mail Recipients* (cmdlets and parameters actually covered),
871
+ the exact Exchange answers to an RBAC refusal (HTTP status, `CommandNotFoundException` or other —
872
+ mapped by status and message), whether the REST `Get-Mailbox` returns `GrantSendOnBehalfTo`, and how
873
+ trustees are named compared with the administrator's reference.
874
+
875
+ - 0.5.3 (#138): the read identity refuses every write or unrecognised Graph permission
876
+ (`User.ReadWrite.All`, `Sites.FullControl.All`…), even with `M365_ALLOW_BROAD_PERMISSIONS=true`,
877
+ with one shared classification (`classifyPermission`). Unit tests passing; a read app holding a
878
+ write permission now fails with `forbidden_permission` instead of a warning in `m365_capabilities`.
879
+
880
+ - 0.5.2: a 4xx that only carries an internal Microsoft exception (`UnknownError` /
881
+ `CultureNotFoundException` on the PIM API) is `service_error`, no longer `unsupported_by_tenant`;
882
+ a missing licence is not asserted when the subscribed SKUs show it. Unit tests passing on fixtures;
883
+ **to validate on the affected tenant**: whether `Accept-Language: en-US` on the PIM request removes
884
+ the HTTP 400 (the origin of the `*` culture is not established).
885
+
687
886
  - 0.4.2: a connection dropped while the answer is read (Node's `terminated`) is retried like a failed
688
887
  request, then reported as `transient` with the HTTP status and the Microsoft request-id — it used to
689
888
  surface as `unexpected: terminated`, which hid whether Exchange or the network had refused.
@@ -1,5 +1,6 @@
1
1
  import { M365Error } from "../errors.js";
2
2
  import { defaultFetcher, DEFAULT_TIMEOUT_MS } from "../http.js";
3
+ import { classifyPermission, notReadPermissions } from "../permissions.js";
3
4
  import { registerSecret } from "../redact.js";
4
5
  import { createCredential } from "./credentials.js";
5
6
  export const DEFAULT_AUTHORITY = "https://login.microsoftonline.com";
@@ -8,8 +9,10 @@ const GRAPH_AUDIENCES = new Set(["https://graph.microsoft.com", "https://graph.m
8
9
  /** Renew this long before expiry, so a token never expires mid-request. */
9
10
  const EXPIRY_MARGIN_MS = 5 * 60_000;
10
11
  /**
11
- * Application permissions refused by default: they would let the MCP rewrite the directory,
12
- * assign Entra roles or mint credentials — outside the v1 scope. Override: M365_ALLOW_BROAD_PERMISSIONS.
12
+ * Application permissions refused by default on the write identity: they would let the MCP rewrite
13
+ * the directory, assign Entra roles or mint credentials — outside the v1 scope. Override:
14
+ * M365_ALLOW_BROAD_PERMISSIONS (write identity only). The read identity refuses every permission
15
+ * that is not a read (classifyPermission), whatever this flag says.
13
16
  */
14
17
  export const FORBIDDEN_ROLES = [
15
18
  "Directory.ReadWrite.All",
@@ -61,6 +64,13 @@ export const WRITE_CAPABLE_DIRECTORY_ROLES = {
61
64
  "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3": "Application Administrator",
62
65
  "158c047a-c907-4556-b7ef-446551a6b5f7": "Cloud Application Administrator",
63
66
  };
67
+ /**
68
+ * Read-only but tenant-wide directory roles: accepted on the audit identity, yet broader than the
69
+ * Exchange mailbox audit needs (a view-only Exchange role group) — m365_capabilities warns.
70
+ */
71
+ export const BROAD_READ_DIRECTORY_ROLES = {
72
+ "f2ef992c-3afb-46b9-b7cf-a126ee74c451": "Global Reader",
73
+ };
64
74
  function decodeClaims(jwt) {
65
75
  const part = jwt.split(".")[1];
66
76
  if (!part)
@@ -203,6 +213,16 @@ export class TokenProvider {
203
213
  if (extra.length)
204
214
  throw new M365Error("forbidden_permission", `forbidden_permission: the entra identity holds roles outside its exact allowlist: ${extra.join(", ")}`);
205
215
  }
216
+ if (this.role === "read") {
217
+ // fail-closed: writes and unrecognised permissions alike; M365_ALLOW_BROAD_PERMISSIONS does not apply here
218
+ const refused = notReadPermissions(roles);
219
+ if (refused.length) {
220
+ const writes = refused.filter((r) => classifyPermission(r) === "write");
221
+ const unknown = refused.filter((r) => classifyPermission(r) === "unknown");
222
+ const held = [writes.length ? `write permission(s) ${writes.join(", ")}` : "", unknown.length ? `unrecognised permission(s) ${unknown.join(", ")} (treated as write)` : ""].filter(Boolean).join(" and ");
223
+ throw new M365Error("forbidden_permission", `forbidden_permission: the read identity holds ${held} — it must hold read permissions only. Remove them from the read Entra app; writes belong to the separate write identity (M365_WRITE_CLIENT_ID, M365_MODE=full). M365_ALLOW_BROAD_PERMISSIONS does not apply to the read identity.`);
224
+ }
225
+ }
206
226
  const hardForbidden = this.role === "entra" && forbidden.length > 0;
207
227
  if (forbidden.length && (hardForbidden || !this.opts.allowBroadPermissions)) {
208
228
  throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds ${forbidden.join(", ")} — refused by policy. Remove these permissions from the Entra app (or set M365_ALLOW_BROAD_PERMISSIONS=true knowingly).`);
package/dist/config.js CHANGED
@@ -180,7 +180,7 @@ export function loadConfig(env) {
180
180
  warnings.push("⚠ M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true — the audit identity may hold Sites.FullControl.All (tenant-wide full control of SharePoint); prefer Sites.Selected with per-site grants");
181
181
  const activityStartSubscriptions = parseBool(env, "M365_ACTIVITY_START_SUBSCRIPTIONS");
182
182
  if (allowBroadPermissions)
183
- warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — tokens with directory-wide write permissions are accepted");
183
+ warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — write-identity tokens with directory-wide write permissions are accepted (the read identity still refuses every write permission)");
184
184
  return {
185
185
  mode,
186
186
  tenantId: tenantId.toLowerCase(),
package/dist/errors.js CHANGED
@@ -9,6 +9,10 @@ export class M365Error extends Error {
9
9
  clientRequestId;
10
10
  /** Seconds Graph asked to wait (429 / 503 with Retry-After). */
11
11
  retryAfter;
12
+ /** API outside Graph whose HTTP answer this error is (exchange, activity, sharepoint) — absent for token and network errors. */
13
+ service;
14
+ /** That service's own error message, truncated and redacted, to classify it further. */
15
+ serviceMessage;
12
16
  constructor(code, message, extra = {}) {
13
17
  super(redactString(message));
14
18
  this.name = "M365Error";
@@ -36,6 +40,15 @@ function graphErrorBody(text) {
36
40
  }
37
41
  /** Graph codes and messages that say "this tenant cannot do it" rather than "you may not". */
38
42
  const UNSUPPORTED = /NonPremiumTenant|B2CTenant|RequestFromUnsupportedUserRole|NotSupported|not supported|not licensed|no license|requires a license|MailboxNotEnabled|not applicable to target tenant|PremiumLicense|premium license/i;
43
+ /**
44
+ * A 4xx whose only content is an internal exception of the Microsoft service (the PIM back end answers
45
+ * HTTP 400 UnknownError / CultureNotFoundException, "Culture is not supported … * is an invalid culture
46
+ * identifier"). It is neither a licence, a permission nor a data statement, and is tested before
47
+ * UNSUPPORTED: the bare words "not supported" in such a message say nothing about the tenant.
48
+ */
49
+ const SERVICE_FAULT = /CultureNotFound|invalid culture identifier|culture is not supported/i;
50
+ const DOTNET_EXCEPTION = /\b[A-Z]\w*Exception\b/;
51
+ const isServiceFault = (graphCode, hay) => SERVICE_FAULT.test(hay) || (graphCode === "UnknownError" && DOTNET_EXCEPTION.test(hay));
39
52
  const LICENSE = /available licenses|CountViolation|LicenseLimit|insufficient.*licen|MutuallyExclusiveViolation|DependsOnViolation|usage ?location/i;
40
53
  const CONFLICT = /already exist|Request_MultipleObjectsWithSameKeyValue|ObjectConflict|PreconditionFailed|conflict/i;
41
54
  /**
@@ -56,6 +69,8 @@ export function fromGraphResponse(status, bodyText, ids = {}) {
56
69
  code = "not_found";
57
70
  else if (status === 409 || status === 412)
58
71
  code = "conflict";
72
+ else if (isServiceFault(graphCode, hay))
73
+ code = "service_error";
59
74
  else if (UNSUPPORTED.test(hay))
60
75
  code = "unsupported_by_tenant";
61
76
  else if (LICENSE.test(hay))
@@ -67,7 +82,11 @@ export function fromGraphResponse(status, bodyText, ids = {}) {
67
82
  else
68
83
  code = "invalid_request";
69
84
  const short = (message ?? "").replace(/\s+/g, " ").slice(0, MAX_MESSAGE);
70
- const hint = code === "permission_missing" ? " — check the application permissions with m365_capabilities (admin consent granted?)" : "";
85
+ const hint = code === "permission_missing"
86
+ ? " — check the application permissions with m365_capabilities (admin consent granted?)"
87
+ : code === "service_error"
88
+ ? " — Microsoft failed on this request with an internal exception: the result is unknown (not an empty list), and this says nothing about the tenant's licences or the application's permissions. Quote the request-id to Microsoft support"
89
+ : "";
71
90
  return new M365Error(code, `${code} (HTTP ${status}${graphCode ? ` ${graphCode}` : ""})${short ? `: ${short}` : ""}${hint}`, {
72
91
  status,
73
92
  graphCode,
@@ -149,6 +149,8 @@ export class ExternalClient {
149
149
  requestId,
150
150
  clientRequestId,
151
151
  retryAfter,
152
+ service: this.opts.name,
153
+ serviceMessage: short || undefined,
152
154
  });
153
155
  }
154
156
  }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Acceptance of the Exchange mailbox audit (README → Exchange mailbox audit, step "Recette"): compare
3
+ * what m365_mailbox_permissions returned for the authorised test mailbox (format json) with the
4
+ * reference an Exchange administrator exported from PowerShell. Pure functions, no call to Microsoft:
5
+ * `node smoke.mjs --exchange-audit` runs them on the two JSON documents.
6
+ */
7
+ export const REFERENCE_RIGHTS = ["fullAccess", "sendAs", "sendOnBehalf"];
8
+ const norm = (v) => v.trim().toLowerCase();
9
+ /**
10
+ * PowerShell's ConvertTo-Json writes a one-element list as a bare string and an empty one as null
11
+ * depending on the version: accept string | string[] | null for each right.
12
+ */
13
+ function list(v, field) {
14
+ if (v === null || v === undefined)
15
+ return [];
16
+ if (typeof v === "string")
17
+ return v.trim() ? [v] : [];
18
+ if (Array.isArray(v) && v.every((x) => typeof x === "string"))
19
+ return v;
20
+ throw new Error(`reference: ${field} must be a list of strings`);
21
+ }
22
+ /** Validate the administrator's export (parsed JSON). */
23
+ export function parseReference(raw) {
24
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
25
+ throw new Error("reference: expected one JSON object { mailbox, fullAccess, sendAs, sendOnBehalf }");
26
+ const r = raw;
27
+ if (typeof r.mailbox !== "string" || !r.mailbox.trim())
28
+ throw new Error("reference: mailbox is required");
29
+ return { mailbox: r.mailbox, fullAccess: list(r.fullAccess, "fullAccess"), sendAs: list(r.sendAs, "sendAs"), sendOnBehalf: list(r.sendOnBehalf, "sendOnBehalf") };
30
+ }
31
+ /** Compare per right, case-insensitively: a right the server did not evaluate never counts as a match. */
32
+ export function compareWithReference(row, ref) {
33
+ const rights = REFERENCE_RIGHTS.map((right) => {
34
+ const served = row[right];
35
+ if (served === null || served === undefined)
36
+ return { right, status: "not_evaluated", onlyServer: [], onlyReference: [], reason: row.notEvaluated?.[right] ?? "absent from the server's answer" };
37
+ const s = new Set(served.map(norm));
38
+ const r = new Set(ref[right].map(norm));
39
+ const onlyServer = [...s].filter((x) => !r.has(x)).sort();
40
+ const onlyReference = [...r].filter((x) => !s.has(x)).sort();
41
+ return { right, status: onlyServer.length || onlyReference.length ? "differs" : "match", onlyServer, onlyReference };
42
+ });
43
+ const sameMailbox = norm(row.mailbox) === norm(ref.mailbox);
44
+ return { match: sameMailbox && rights.every((x) => x.status === "match"), sameMailbox, rights };
45
+ }