From 40f107b75e73f78868e5178571f3f03f88aa110d Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:45:53 +0100 Subject: [PATCH 1/2] feat: create and update users with New-InforcerUser and Set-InforcerUser The v1 API adds POST /tenants/{msTenantId}/users and PATCH /tenants/{msTenantId}/users/{userId}. Both cmdlets need an API client login; an API-key (beta) session stops with RequiresApiClient because beta has no equivalent. New-InforcerUser sends the required fields with safe defaults (sign-in enabled, password change at first sign-in, mail alias from the UPN) and returns the new id with the tenant, display name and UPN so it pipes into Set-InforcerUser. The password goes only into the request body. Set-InforcerUser sends only the parameters that were passed (JSON Merge Patch); '' or an empty array clears a field, and the four fields the API cannot clear refuse an empty value. Users pipe in by id. Invoke-InforcerApiRequest now treats 204 as success without output and adds a problem+json results[] list to the error text, so a partly applied update says which step failed. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + Tests/Consistency.Tests.ps1 | 6 +- Tests/V1.UserWrite.Tests.ps1 | 184 +++++++++++++ docs/API-REFERENCE.md | 70 ++++- docs/CMDLET-REFERENCE.md | 100 ++++++- module/InforcerCommunity.Format.ps1xml | 32 +++ module/InforcerCommunity.psd1 | 2 + module/Private/ConvertTo-InforcerUserBody.ps1 | 35 +++ module/Private/Invoke-InforcerApiRequest.ps1 | 11 + module/Public/New-InforcerUser.ps1 | 246 ++++++++++++++++++ module/Public/Set-InforcerUser.ps1 | 216 +++++++++++++++ module/README.md | 4 +- scripts/Test-AllCmdlets.ps1 | 7 + 13 files changed, 910 insertions(+), 5 deletions(-) create mode 100644 Tests/V1.UserWrite.Tests.ps1 create mode 100644 module/Private/ConvertTo-InforcerUserBody.ps1 create mode 100644 module/Public/New-InforcerUser.ps1 create mode 100644 module/Public/Set-InforcerUser.ps1 diff --git a/README.md b/README.md index b7abce5..a0ddbdd 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,8 @@ Some output contains personal data (names, UPNs, email addresses, IP addresses, | **Get-InforcerAuditEvent** | Retrieves audit events (optional EventType, date range; -EventType has tab completion). | | **Get-InforcerSupportedEventType** | Returns the canonical list of audit event types accepted by `Get-InforcerAuditEvent -EventType`. Drives the tab completer; cached after first call. | | **Get-InforcerUser** | Retrieves users from a tenant (list/search or detail by UserId). | +| **New-InforcerUser** | Creates a Microsoft Entra user in a tenant (API client login only). | +| **Set-InforcerUser** | Updates a user's profile, manager or sign-in; only the fields you pass change (API client login only). | | **Get-InforcerGroup** | Retrieves Entra ID groups from a tenant (list/search or detail by GroupId). | | **Get-InforcerRole** | Retrieves Entra ID directory role definitions from a tenant. | | **Get-InforcerSecureScore** | Retrieves the current and 90-day historic Microsoft Secure Score for a tenant, including per-category scores and actionable control profiles. | diff --git a/Tests/Consistency.Tests.ps1 b/Tests/Consistency.Tests.ps1 index 6a75683..2f8d3ab 100644 --- a/Tests/Consistency.Tests.ps1 +++ b/Tests/Consistency.Tests.ps1 @@ -30,12 +30,12 @@ Describe 'Consistency contract' { $path = Get-InforcerCommunityManifestPath Import-Module $path -Force $script:exported = (Get-Module -Name 'InforcerCommunity').ExportedCommands.Keys - $script:expectedCount = 21 + $script:expectedCount = 23 $script:expectedNames = @( 'Connect-Inforcer', 'Disconnect-Inforcer', 'Test-InforcerConnection', 'Get-InforcerTenant', 'Get-InforcerBaseline', 'Get-InforcerTenantPolicies', 'Get-InforcerAlignmentDetails', 'Get-InforcerAuditEvent', 'Get-InforcerSupportedEventType', - 'Get-InforcerUser', 'Get-InforcerGroup', 'Get-InforcerRole', 'Get-InforcerSecureScore', + 'Get-InforcerUser', 'New-InforcerUser', 'Set-InforcerUser', 'Get-InforcerGroup', 'Get-InforcerRole', 'Get-InforcerSecureScore', 'Export-InforcerTenantDocumentation', 'Compare-InforcerEnvironments', 'Get-InforcerAssessment', 'Invoke-InforcerAssessment', 'Get-InforcerReportType', 'Invoke-InforcerReport', 'Get-InforcerReportRun', 'Save-InforcerReportOutput' @@ -51,6 +51,8 @@ Describe 'Consistency contract' { 'Get-InforcerAuditEvent' = @('EventType', 'DateFrom', 'DateTo', 'User', 'PageSize', 'MaxResults', 'Format', 'OutputType') 'Get-InforcerSupportedEventType' = @() 'Get-InforcerUser' = @('Format', 'TenantId', 'Search', 'MaxResults', 'UserId', 'OutputType') + 'New-InforcerUser' = @('TenantId', 'DisplayName', 'UserPrincipalName', 'Password', 'MailNickname', 'AccountEnabled', 'ManagerId', 'OutputType') + 'Set-InforcerUser' = @('TenantId', 'UserId', 'AccountEnabled', 'DisplayName', 'ManagerId') 'Get-InforcerGroup' = @('TenantId', 'Search', 'Filter', 'MaxResults', 'Group', 'OutputType') 'Get-InforcerRole' = @('TenantId', 'OutputType') 'Get-InforcerSecureScore' = @('TenantId', 'OutputType') diff --git a/Tests/V1.UserWrite.Tests.ps1 b/Tests/V1.UserWrite.Tests.ps1 new file mode 100644 index 0000000..cbd2f03 --- /dev/null +++ b/Tests/V1.UserWrite.Tests.ps1 @@ -0,0 +1,184 @@ +# V1.UserWrite.Tests.ps1 +# New-InforcerUser and Set-InforcerUser (v1 only). Fixtures are anonymised; no network calls. + +BeforeAll { + Remove-Module -Name 'InforcerCommunity' -ErrorAction SilentlyContinue + Import-Module (Join-Path $PSScriptRoot '../module/InforcerCommunity.psd1') -Force + + $script:Tid = '00000000-0000-0000-0000-000000000001' + $script:Uid = '00000000-0000-0000-0000-000000000005' + $script:Pw = ConvertTo-SecureString 'Example-Passw0rd!' -AsPlainText -Force + + function global:New-UwResponse { + param([string]$Json, [int]$Status = 200) + $body = if ($Json) { $Json | ConvertFrom-Json -Depth 100 } else { '' } + [pscustomobject]@{ StatusCode = $Status; Body = $body; Headers = @{} } + } + + function global:Set-UwSession { + param([switch]$Beta) + & (Get-Module InforcerCommunity) { + param($Beta) + $script:InforcerTenantListCache = $null + $script:InforcerSession = @{ + AuthMode = $(if ($Beta) { 'ApiKey' } else { 'ClientCredentials' }); ApiVersion = $(if ($Beta) { 'beta' } else { 'v1' }) + ApiHost = 'https://api.example.invalid'; BaseUrl = 'https://api.example.invalid'; Region = 'uk'; ConnectedAt = Get-Date + ApiKey = (ConvertTo-SecureString 'beta-test-key-value' -AsPlainText -Force) + ClientId = 'client-id-example' + ClientSecret = (ConvertTo-SecureString 'client-secret-example-value' -AsPlainText -Force) + AccessToken = (ConvertTo-SecureString 'access-token-example-value' -AsPlainText -Force) + TokenExpiresAt = [datetime]::UtcNow.AddMinutes(50) + } + } $Beta.IsPresent + } + + function global:Set-UwRoute { + param([scriptblock]$Route) + $global:UwCalls = [System.Collections.Generic.List[object]]::new() + $global:UwRoute = $Route + Mock -ModuleName InforcerCommunity Invoke-InforcerHttpRequest { + $global:UwCalls.Add([pscustomobject]@{ Uri = [string]$Request.Uri; Method = $Request.Method; Body = $Request.Body }) + & $global:UwRoute ([string]$Request.Uri) $Request.Method $Request.Body + } + } +} + +AfterAll { + foreach ($f in 'New-UwResponse', 'Set-UwSession', 'Set-UwRoute') { Remove-Item "function:global:$f" -ErrorAction SilentlyContinue } + Remove-Variable -Name UwCalls, UwRoute -Scope Global -ErrorAction SilentlyContinue + & (Get-Module InforcerCommunity) { $script:InforcerSession = $null; $script:InforcerTenantListCache = $null } +} + +Describe 'New-InforcerUser' { + It 'POSTs the required fields, defaults and the password, and returns the new id' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse ('{"id":"' + $script:Uid + '"}') 201 } + $u = New-InforcerUser -TenantId $script:Tid -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $script:Pw -Department 'Sales' + $global:UwCalls.Count | Should -Be 1 + $global:UwCalls[0].Method | Should -Be 'POST' + $global:UwCalls[0].Uri | Should -Be "https://api.example.invalid/v1/tenants/$($script:Tid)/users" + $b = $global:UwCalls[0].Body | ConvertFrom-Json + $b.displayName | Should -Be 'Jo Bloggs' + $b.userPrincipalName | Should -Be 'jo.bloggs@contoso.com' + $b.mailNickname | Should -Be 'jo.bloggs' + $b.accountEnabled | Should -BeTrue + $b.department | Should -Be 'Sales' + $b.passwordProfile.password | Should -Be 'Example-Passw0rd!' + $b.passwordProfile.forceChangePasswordNextSignIn | Should -BeTrue + $b.PSObject.Properties.Name | Should -Not -Contain 'outputType' + $b.PSObject.Properties.Name | Should -Not -Contain 'tenantId' + $u.id | Should -Be $script:Uid + $u.TenantId | Should -Be $script:Tid + $u.userPrincipalName | Should -Be 'jo.bloggs@contoso.com' + $u.PSObject.TypeNames[0] | Should -Be 'InforcerCommunity.CreatedUser' + } + + It 'sends -AccountEnabled $false, -MailNickname and -ForceChangePasswordNextSignIn $false as given' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '{"id":"x"}' 201 } + $null = New-InforcerUser -TenantId $script:Tid -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $script:Pw -AccountEnabled $false -MailNickname 'jb' -ForceChangePasswordNextSignIn $false -BusinessPhones '+44 20 0000 0000' + $b = $global:UwCalls[0].Body | ConvertFrom-Json + $b.accountEnabled | Should -BeFalse + $b.mailNickname | Should -Be 'jb' + $b.passwordProfile.forceChangePasswordNextSignIn | Should -BeFalse + @($b.businessPhones).Count | Should -Be 1 + $global:UwCalls[0].Body.Contains('"businessPhones":["+44 20 0000 0000"]') | Should -BeTrue + } + + It 'keeps the password out of verbose output' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '{"id":"x"}' 201 } + $verbose = New-InforcerUser -TenantId $script:Tid -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $script:Pw -Verbose 4>&1 | Where-Object { $_ -is [System.Management.Automation.VerboseRecord] } + ($verbose | Out-String) | Should -Not -BeLike '*Example-Passw0rd!*' + } + + It 'makes no request with -WhatIf' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '{"id":"x"}' 201 } + New-InforcerUser -TenantId $script:Tid -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $script:Pw -WhatIf + $global:UwCalls.Count | Should -Be 0 + } + + It 'refuses an API-key (beta) login with RequiresApiClient and makes no request' { + Set-UwSession -Beta + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '{"id":"x"}' 201 } + New-InforcerUser -TenantId 5 -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $script:Pw -ErrorAction SilentlyContinue -ErrorVariable e + $e[0].FullyQualifiedErrorId | Should -BeLike 'RequiresApiClient*' + $global:UwCalls.Count | Should -Be 0 + } + + It 'surfaces a 409 conflict with the API reason' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '{"title":"Conflict","status":409,"detail":"A user with this userPrincipalName already exists"}' 409 } + { New-InforcerUser -TenantId $script:Tid -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $script:Pw -ErrorAction Stop } | Should -Throw '*HTTP 409*already exists*' + } + + It 'returns one JSON array for piped tenants with -OutputType JsonObject' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '{"id":"x"}' 201 } + $json = @([pscustomobject]@{ MsTenantId = $script:Tid }, [pscustomobject]@{ MsTenantId = '00000000-0000-0000-0000-000000000002' }) | + New-InforcerUser -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $script:Pw -OutputType JsonObject + @($json).Count | Should -Be 1 + @($json | ConvertFrom-Json).Count | Should -Be 2 + } +} + +Describe 'Set-InforcerUser' { + It 'PATCHes only the passed fields, and a 204 returns nothing without an error' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '' 204 } + $out = Set-InforcerUser -TenantId $script:Tid -UserId $script:Uid -Department 'Sales' -AccountEnabled $false -ErrorVariable e + $out | Should -BeNullOrEmpty + $e | Should -BeNullOrEmpty + $global:UwCalls[0].Method | Should -Be 'PATCH' + $global:UwCalls[0].Uri | Should -Be "https://api.example.invalid/v1/tenants/$($script:Tid)/users/$($script:Uid)" + $b = $global:UwCalls[0].Body | ConvertFrom-Json + @($b.PSObject.Properties.Name) | Sort-Object | Should -Be @('accountEnabled', 'department') + $b.accountEnabled | Should -BeFalse + } + + It "sends null for '' and empty arrays, so the fields are cleared" { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '' 204 } + Set-InforcerUser -TenantId $script:Tid -UserId $script:Uid -JobTitle '' -ManagerId $null -OtherMails @() + $global:UwCalls[0].Body | Should -Be '{"jobTitle":null,"otherMails":null,"managerId":null}' + } + + It 'refuses to clear a field the API cannot clear' { + { Set-InforcerUser -TenantId $script:Tid -UserId $script:Uid -DisplayName '' } | Should -Throw + } + + It 'refuses a call without any change and makes no request' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '' 204 } + Set-InforcerUser -TenantId $script:Tid -UserId $script:Uid -ErrorAction SilentlyContinue -ErrorVariable e + $e[0].FullyQualifiedErrorId | Should -BeLike 'NoChangeSpecified*' + $global:UwCalls.Count | Should -Be 0 + } + + It 'takes users from the pipeline by id' { + Set-UwSession + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '' 204 } + @([pscustomobject]@{ id = 'u1' }, [pscustomobject]@{ id = 'u2' }) | Set-InforcerUser -TenantId $script:Tid -Department 'Sales' + $global:UwCalls.Count | Should -Be 2 + $global:UwCalls[1].Uri | Should -BeLike '*/users/u2' + } + + It 'refuses an API-key (beta) login with RequiresApiClient' { + Set-UwSession -Beta + Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '' 204 } + Set-InforcerUser -TenantId 5 -UserId $script:Uid -Department 'Sales' -ErrorAction SilentlyContinue -ErrorVariable e + $e[0].FullyQualifiedErrorId | Should -BeLike 'RequiresApiClient*' + $global:UwCalls.Count | Should -Be 0 + } + + It 'lists each step when the update was only partly applied (502)' { + Set-UwSession + Set-UwRoute { + param($Uri, $Method, $Body) + New-UwResponse '{"title":"Bad gateway","status":502,"detail":"The manager could not be changed","results":[{"step":"profile","status":"succeeded"},{"step":"manager","status":"failed","title":"Manager not found","statusCode":404}]}' 502 + } + { Set-InforcerUser -TenantId $script:Tid -UserId $script:Uid -Department 'Sales' -ManagerId $script:Tid -ErrorAction Stop } | + Should -Throw '*HTTP 502*Steps: profile: succeeded; manager: failed (Manager not found)*' + } +} diff --git a/docs/API-REFERENCE.md b/docs/API-REFERENCE.md index e60b05b..119f96d 100644 --- a/docs/API-REFERENCE.md +++ b/docs/API-REFERENCE.md @@ -21,6 +21,7 @@ This document describes the inforcer REST API endpoints, schemas, and response s - [Rate limits](#rate-limits) - [failedPolicyTypes](#failedpolicytypes) - [v1 endpoints](#v1-endpoints) + - [Creating and updating users (v1 only)](#creating-and-updating-users-v1-only) - [How v1 fields map to the module's names](#how-v1-fields-map-to-the-modules-names) - [Alignment details renames](#alignment-details-renames) - [Beta endpoints](#beta-endpoints) @@ -52,6 +53,8 @@ This document describes the inforcer REST API endpoints, schemas, and response s - [UserSummary](#usersummary) - [User](#user) - [UserLicense](#userlicense) + - [CreatedUser](#createduser) + - [UserUpdate](#userupdate) - [TenantGroupSummary](#tenantgroupsummary) - [TenantGroup](#tenantgroup) - [TenantRole](#tenantrole) @@ -143,6 +146,8 @@ Built mechanically by tracing each public cmdlet through the module (including t | `Get-InforcerAuditEvent` | `POST /beta/auditEvents/search` (one search; without `-EventType` no event-type filter is sent) | `Audit.Read` *(unmapped — see note above)* | | `Get-InforcerSupportedEventType` | `GET /beta/auditEvents/eventTypes` | `Audit.Read` *(unmapped — see note above)* | | `Get-InforcerUser` | `GET /beta/tenants/{tenantId}/users[/...] ` + `GET /beta/tenants` *(GUID/name lookup)* | `Tenants.Users.Read` + `Tenants.Read`† | +| `New-InforcerUser` | none: the beta API cannot create users (the cmdlet needs an API client) | not available with an API key | +| `Set-InforcerUser` | none: the beta API cannot update users (the cmdlet needs an API client) | not available with an API key | | `Get-InforcerGroup` | `GET /beta/tenants/{tenantId}/groups[/...] ` + `GET /beta/tenants` *(GUID/name lookup)* | `Tenants.Groups.Read` + `Tenants.Read`† | | `Get-InforcerRole` | `GET /beta/tenants/{tenantId}/roles` + `GET /beta/tenants` *(GUID/name lookup)* | `Tenants.Roles.Read` + `Tenants.Read`† | | `Get-InforcerSecureScore` | `GET /beta/tenants/{tenantId}/secureScores` + `GET /beta/tenants` *(GUID/name lookup)* | `Tenants.SecureScores.Read` + `Tenants.Read`† | @@ -174,6 +179,7 @@ The permission names below are the ones the portal shows (feature and grant). ** | Tenants / Tenants | Read: View | `/v1/tenants`, `/v1/tenants/{msTenantId}` | unconfirmed | | Tenants / Policies | Read: View | `/v1/tenants/{msTenantId}/policies` | unconfirmed | | Tenants / User & Group Management | Read: View | `/v1/tenants/{msTenantId}/users`, `/v1/tenants/{msTenantId}/users/{userId}`, `/v1/tenants/{msTenantId}/groups`, `/v1/tenants/{msTenantId}/groups/{groupId}`, `/v1/tenants/{msTenantId}/groups/{groupId}/members` | unconfirmed | +| Tenants / User & Group Management | Write (grant name unconfirmed) | `POST /v1/tenants/{msTenantId}/users`, `PATCH /v1/tenants/{msTenantId}/users/{userId}` | unconfirmed (which write grant) | | Tenants / Entra Dashboard | Read: View | `/v1/tenants/{msTenantId}/secureScores`, `/v1/tenants/{msTenantId}/directoryRoles` | unconfirmed | | Align / Baselines | Read: View | `/v1/baselines` | unconfirmed | | Align / Align | Read: View | `/v1/alignmentScores`, `/v1/tenants/{msTenantId}/alignmentDetails` | unconfirmed | @@ -199,6 +205,8 @@ The permission names below are the ones the portal shows (feature and grant). ** | `Get-InforcerAuditEvent` | `POST /v1/auditEvents/search` | Activity | | `Get-InforcerSupportedEventType` | `GET /v1/auditEvents/types` | Activity | | `Get-InforcerUser` | `GET /v1/tenants/{msTenantId}/users[/{userId}]` | User & Group Management, Tenants† | +| `New-InforcerUser` | `POST /v1/tenants/{msTenantId}/users` | User & Group Management (write), Tenants† | +| `Set-InforcerUser` | `PATCH /v1/tenants/{msTenantId}/users/{userId}` | User & Group Management (write), Tenants† | | `Get-InforcerGroup` | `GET /v1/tenants/{msTenantId}/groups[/{groupId}]`, `.../groups/{groupId}/members` (with `-Group`) | User & Group Management, Tenants† | | `Get-InforcerRole` | `GET /v1/tenants/{msTenantId}/directoryRoles` | Entra Dashboard, Tenants† | | `Get-InforcerSecureScore` | `GET /v1/tenants/{msTenantId}/secureScores` | Entra Dashboard, Tenants† | @@ -298,7 +306,9 @@ Every path in the v1 spec, its beta equivalent and the module cmdlet. The module | `/v1/tenants/{msTenantId}/alignmentDetails` | GET (`baselineId` required) | `/beta/tenants/{tenantId}/alignmentDetails` (`customBaselineId`) | `Get-InforcerAlignmentDetails`; Export/Compare baseline scoping | | `/v1/tenants/{msTenantId}/secureScores` | GET | `/beta/tenants/{tenantId}/secureScores` | `Get-InforcerSecureScore` | | `/v1/tenants/{msTenantId}/users` | GET (`search`, `continuationToken`) | `/beta/tenants/{tenantId}/users` | `Get-InforcerUser` | +| `/v1/tenants/{msTenantId}/users` | POST (201 `{ id }`) | none (v1 only) | `New-InforcerUser` | | `/v1/tenants/{msTenantId}/users/{userId}` | GET | `/beta/tenants/{tenantId}/users/{userId}` | `Get-InforcerUser -UserId` | +| `/v1/tenants/{msTenantId}/users/{userId}` | PATCH (JSON Merge Patch, 204) | none (v1 only) | `Set-InforcerUser` | | `/v1/tenants/{msTenantId}/groups` | GET (`search`, `continuationToken`) | `/beta/tenants/{tenantId}/groups` | `Get-InforcerGroup` | | `/v1/tenants/{msTenantId}/groups/{groupId}` | GET | `/beta/tenants/{tenantId}/groups/{groupId}` | `Get-InforcerGroup -Group` | | `/v1/tenants/{msTenantId}/groups/{groupId}/members` | GET (`continuationToken`) | none (v1 only) | `Get-InforcerGroup -Group` (attached as members) | @@ -314,7 +324,33 @@ Every path in the v1 spec, its beta equivalent and the module cmdlet. The module | `/v1/auditEvents/types` | GET (`{ "eventTypes": [ { "name" } ] }`) | `/beta/auditEvents/eventTypes` | `Get-InforcerSupportedEventType` | | `/v1/auditEvents/search` | POST (`user`, `eventTypes`, `dateFrom`, `dateTo` in whole seconds, `pageSize`, `continuationToken`) | `/beta/auditEvents/search` | `Get-InforcerAuditEvent` | -That is 21 paths and 22 operations (`/v1/reports/runs` has GET and POST). Path parameters are `msTenantId` (Microsoft tenant GUID), `userId` (Entra object ID), `groupId`, `assessmentId`, `reportRunId` and `outputId`. Report runs are triggered with `{ "reports": [ { "type", "outputFormat", "collate", "parameters" } ], "msTenantIds": [ ... ] }` (beta: `tenants.includeTenants` with numeric IDs). +That is 21 paths and 24 operations (`/v1/reports/runs` has GET and POST, `/v1/tenants/{msTenantId}/users` GET and POST, `/v1/tenants/{msTenantId}/users/{userId}` GET and PATCH). Path parameters are `msTenantId` (Microsoft tenant GUID), `userId` (Entra object ID), `groupId`, `assessmentId`, `reportRunId` and `outputId`. Report runs are triggered with `{ "reports": [ { "type", "outputFormat", "collate", "parameters" } ], "msTenantIds": [ ... ] }` (beta: `tenants.includeTenants` with numeric IDs). + +### Creating and updating users (v1 only) + +The beta API has no equivalent, so `New-InforcerUser` and `Set-InforcerUser` need an API client; an API-key login stops with `RequiresApiClient`. + +#### `POST /v1/tenants/{msTenantId}/users` + +Creates a Microsoft Entra user in the tenant. + +**Required API scope(s)**: not available with an API key (beta). +**Required API client permission(s)**: User & Group Management (write) *(unconfirmed)* + +Body: the [UserUpdate](#userupdate) profile fields, of which `accountEnabled`, `displayName`, `mailNickname` and `userPrincipalName` are required, plus `passwordProfile` `{ password, forceChangePasswordNextSignIn }` (both required; the password must meet the tenant's password policy). + +**Response**: `201` with [CreatedUser](#createduser) and a `Location` header. Errors: `400` (invalid field, with `errors{}`), `404` (tenant), `409` (for example the user principal name is taken). + +#### `PATCH /v1/tenants/{msTenantId}/users/{userId}` + +Updates a user's profile, manager and whether they can sign in. JSON Merge Patch (RFC 7396): a property left out is kept, `null` clears it. + +**Required API scope(s)**: not available with an API key (beta). +**Required API client permission(s)**: User & Group Management (write) *(unconfirmed)* + +Body: [UserUpdate](#userupdate), at least one property. Sent as `application/json` (the API also takes `application/merge-patch+json`). + +**Response**: `204` without a body; a change can take a few seconds to show in a `GET`. When the manager could not be changed but the other changes were saved, the API answers `502` with problem+json and `results[]`: one `{ step, status, title?, statusCode? }` per step (`profile`, `manager`). The module adds them to the error text as `Steps: profile: succeeded; manager: failed (reason)`. ### How v1 fields map to the module's names @@ -1025,6 +1061,38 @@ License assignment on a user, used in both UserSummary and User schemas. | isCancelled | boolean | Whether the license is cancelled. | | state | string | License assignment state. | +### CreatedUser + +Returned by `POST /v1/tenants/{msTenantId}/users`. `New-InforcerUser` adds `TenantId`, `displayName` and `userPrincipalName` (from the request) so the result can be piped to `Set-InforcerUser`. + +| Property | Type | Description | +|----------|------|-------------| +| id | string (uuid) | The new user's Microsoft Entra object id. | + +### UserUpdate + +The profile fields of `PATCH /v1/tenants/{msTenantId}/users/{userId}` (and of the create body). All optional and nullable unless noted; `null` clears a field. `displayName`, `mailNickname`, `userPrincipalName`, `mail` and `accountEnabled` cannot be cleared. Unknown properties are rejected. + +| Property | Type | Limits / notes | +|----------|------|----------------| +| accountEnabled | boolean | `false` blocks sign-in; existing sessions last until their tokens expire. | +| displayName | string | 1-256 characters. | +| mailNickname | string | 1-64 characters. The mail alias. | +| userPrincipalName | string | The sign-in name. | +| givenName, surname | string | 1-64 characters. | +| jobTitle | string | 1-128 characters. | +| department | string | 1-64 characters. | +| officeLocation, city, state, country | string | 1-128 characters. | +| streetAddress | string | 1-1024 characters. | +| postalCode | string | 1-40 characters. | +| mobilePhone, preferredLanguage, companyName, employeeType | string | 1-64 characters. | +| usageLocation | string | Two letters (ISO 3166), such as `GB`. | +| employeeId | string | 1-16 characters. | +| mail | string (email) | | +| businessPhones | string[] | At most one number. | +| otherMails | string[] (email) | | +| managerId | string (uuid) | The manager's object id; `null` removes the manager. | + ### TenantGroupSummary Summary of an Entra ID group (returned from list endpoint). diff --git a/docs/CMDLET-REFERENCE.md b/docs/CMDLET-REFERENCE.md index 5a56630..9502444 100644 --- a/docs/CMDLET-REFERENCE.md +++ b/docs/CMDLET-REFERENCE.md @@ -4,7 +4,7 @@ This document describes each cmdlet with parameters, usage examples, and **examp > **Tip**: For detailed property definitions and API schemas, see the [API Reference](./API-REFERENCE.md). -> **Logins**: every cmdlet works with both logins. An API client (`Connect-Inforcer -ClientId -ClientSecret`) uses the v1 API; an API key (`-ApiKey`) uses the legacy beta API. Each cmdlet lists the beta API-key scopes and the v1 API client permissions it needs. The v1 permission mapping is unconfirmed (see [API client permissions](./API-REFERENCE.md#api-client-permissions-v1)). Tenant IDs: Microsoft tenant ID (GUID) or name on both logins; the numeric Client Tenant ID only with an API key. `-TenantId` has the aliases `ClientTenantId` and `MsTenantId`. +> **Logins**: every cmdlet works with both logins, except `New-InforcerUser` and `Set-InforcerUser`, which need an API client because the beta API cannot create or change users. An API client (`Connect-Inforcer -ClientId -ClientSecret`) uses the v1 API; an API key (`-ApiKey`) uses the legacy beta API. Each cmdlet lists the beta API-key scopes and the v1 API client permissions it needs. The v1 permission mapping is unconfirmed (see [API client permissions](./API-REFERENCE.md#api-client-permissions-v1)). Tenant IDs: Microsoft tenant ID (GUID) or name on both logins; the numeric Client Tenant ID only with an API key. `-TenantId` has the aliases `ClientTenantId` and `MsTenantId`. > **Note**: Default output shows key properties. Use `| Select-Object *` to see all properties including raw API fields. @@ -532,6 +532,104 @@ RiskLevel : --- +## New-InforcerUser + +Creates a Microsoft Entra user in a tenant. Needs a login with an API client (`Connect-Inforcer -ClientId -ClientSecret`); with an API key it stops with the error `RequiresApiClient`, because the beta API cannot create users. + +The user can sign in by default and must change the password at the first sign-in. `-MailNickname` defaults to the part of `-UserPrincipalName` before the `@`. The password must meet the tenant's password policy; it is sent only in the request body and never written to verbose output. A new user can take a few seconds to show in `Get-InforcerUser`. Supports `-WhatIf` and `-Confirm`. + +**Endpoints called (beta)**: none (not available on the beta API). +**Required API scope(s) (API key, beta)**: not available with an API key. +**Endpoints on v1**: `POST /v1/tenants/{msTenantId}/users` (+ `GET /v1/tenants` for a tenant name) +**Required API client permission(s) (v1)**: User & Group Management (write) + Tenants (only for a tenant name) *(unconfirmed, see [API client permissions](./API-REFERENCE.md#api-client-permissions-v1))* + +**Output schema**: [CreatedUser](./API-REFERENCE.md#createduser), with `TenantId`, `displayName` and `userPrincipalName` added. + +| Parameter | Type | Mandatory | Description | +|-----------|------|-----------|-------------| +| **TenantId** | Object | Yes | Microsoft tenant ID (GUID) or tenant name. Aliases: `ClientTenantId`, `MsTenantId`. Supports pipeline input by property name. | +| **DisplayName** | String | Yes | The name shown for the user. | +| **UserPrincipalName** | String | Yes | The sign-in name, such as `jo.bloggs@contoso.com`. The domain must be verified in the tenant. | +| **Password** | SecureString | Yes | The initial password. | +| **MailNickname** | String | No | The mail alias. Default: the part of `-UserPrincipalName` before the `@`. | +| **ForceChangePasswordNextSignIn** | Bool | No | Whether the user must change the password at the first sign-in. Default: `$true`. | +| **AccountEnabled** | Bool | No | Whether the user can sign in. Default: `$true`. | +| **GivenName**, **Surname**, **JobTitle**, **Department**, **OfficeLocation**, **StreetAddress**, **City**, **State**, **PostalCode**, **Country**, **MobilePhone**, **PreferredLanguage**, **CompanyName**, **EmployeeId**, **EmployeeType**, **Mail** | String | No | Profile fields, sent as given. | +| **UsageLocation** | String | No | Two-letter country code (ISO 3166) where the user's licences are used, such as `GB`. Needed before licences can be assigned. | +| **BusinessPhones** | String[] | No | Business phone number. Microsoft Entra allows one. | +| **OtherMails** | String[] | No | Other email addresses. | +| **ManagerId** | String | No | The Microsoft Entra object id of the user's manager. | +| **OutputType** | String | No | `PowerShellObject` (default) or `JsonObject`. JSON uses Depth 100; piped tenants return one array. | + +### Examples + +```powershell +$password = Read-Host -AsSecureString -Prompt 'Initial password' +New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password +New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password -GivenName 'Jo' -Surname 'Bloggs' -Department 'Sales' -UsageLocation 'GB' -AccountEnabled $false +New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password -WhatIf +New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password -OutputType JsonObject +``` + +### Example output + +``` +DisplayName : Jo Bloggs +UserPrincipalName : jo.bloggs@contoso.com +Id : 00000000-0000-0000-0000-000000000005 +TenantId : 00000000-0000-0000-0000-000000000001 +``` + +--- + +## Set-InforcerUser + +Updates a Microsoft Entra user's profile, manager or whether they can sign in. Needs a login with an API client (`Connect-Inforcer -ClientId -ClientSecret`); with an API key it stops with the error `RequiresApiClient`, because the beta API cannot change users. + +Only the parameters you pass are changed; every other field stays as it is. Pass an empty string (`''`) or `$null` to clear a field, such as `-JobTitle ''`, or `-ManagerId ''` to remove the manager. `DisplayName`, `MailNickname`, `UserPrincipalName` and `Mail` cannot be cleared. `-AccountEnabled $false` blocks sign-in, but existing sessions last until their tokens expire. A change can take a few seconds to show in `Get-InforcerUser`. Returns nothing. Supports `-WhatIf` and `-Confirm`. + +When the manager could not be changed but the other changes were saved (HTTP 502), the error lists each step and whether it was applied, for example `Steps: profile: succeeded; manager: failed (Manager not found)`. + +**Pipeline:** users from `Get-InforcerUser` or `New-InforcerUser` can be piped in; `-UserId` binds from their `id` and `-TenantId` from their `TenantId` when they have one. + +**Endpoints called (beta)**: none (not available on the beta API). +**Required API scope(s) (API key, beta)**: not available with an API key. +**Endpoints on v1**: `PATCH /v1/tenants/{msTenantId}/users/{userId}` (+ `GET /v1/tenants` for a tenant name) +**Required API client permission(s) (v1)**: User & Group Management (write) + Tenants (only for a tenant name) *(unconfirmed, see [API client permissions](./API-REFERENCE.md#api-client-permissions-v1))* + +**Request schema**: [UserUpdate](./API-REFERENCE.md#userupdate) + +| Parameter | Type | Mandatory | Description | +|-----------|------|-----------|-------------| +| **TenantId** | Object | Yes | Microsoft tenant ID (GUID) or tenant name. Aliases: `ClientTenantId`, `MsTenantId`. Supports pipeline input by property name. | +| **UserId** | String | Yes | The user's Microsoft Entra object id. Alias: `Id`. Supports pipeline input by property name. | +| **AccountEnabled** | Bool | No | Whether the user can sign in. | +| **DisplayName**, **MailNickname**, **UserPrincipalName**, **Mail** | String | No | Cannot be cleared; an empty value is refused. | +| **GivenName**, **Surname**, **JobTitle**, **Department**, **OfficeLocation**, **StreetAddress**, **City**, **State**, **PostalCode**, **Country**, **MobilePhone**, **UsageLocation**, **PreferredLanguage**, **CompanyName**, **EmployeeId**, **EmployeeType** | String | No | Profile fields; `''` clears the field. | +| **BusinessPhones**, **OtherMails** | String[] | No | Replace the whole list; `@()` clears it. | +| **ManagerId** | String | No | The manager's Microsoft Entra object id; `''` removes the manager. | + +At least one field must be passed; otherwise the cmdlet stops with `NoChangeSpecified` without a request. + +### Examples + +```powershell +Set-InforcerUser -TenantId 'Contoso' -UserId '00000000-0000-0000-0000-000000000005' -Department 'Sales' -JobTitle 'Account Manager' +Set-InforcerUser -TenantId 'Contoso' -UserId '00000000-0000-0000-0000-000000000005' -AccountEnabled $false +Get-InforcerUser -TenantId 'Contoso' -Search 'Adele' | Set-InforcerUser -TenantId 'Contoso' -ManagerId '' +Set-InforcerUser -TenantId 'Contoso' -UserId '00000000-0000-0000-0000-000000000005' -UsageLocation 'GB' -WhatIf +``` + +### Example output + +None. With `-WhatIf`: + +``` +What if: Performing the operation "Update usageLocation" on target "user 00000000-0000-0000-0000-000000000005 in tenant 00000000-0000-0000-0000-000000000001". +``` + +--- + ## Get-InforcerGroup Retrieves Entra ID groups from an inforcer tenant. When called without `-Group`, returns all groups (GroupSummary objects) with optional search filtering and auto-pagination. When called with `-Group`, resolves the group by GUID or display name and returns the full group detail (Group object) including members (on v1 the members come from a separate paged call, so a very large group takes one call per page of members). diff --git a/module/InforcerCommunity.Format.ps1xml b/module/InforcerCommunity.Format.ps1xml index a4cb1fe..3590454 100644 --- a/module/InforcerCommunity.Format.ps1xml +++ b/module/InforcerCommunity.Format.ps1xml @@ -174,6 +174,38 @@ + + + InforcerCommunity.CreatedUser.Default + + InforcerCommunity.CreatedUser + + + + + + + + displayName + + + + userPrincipalName + + + + id + + + + TenantId + + + + + + + InforcerCommunity.User.Default diff --git a/module/InforcerCommunity.psd1 b/module/InforcerCommunity.psd1 index 8e1613e..be28dec 100644 --- a/module/InforcerCommunity.psd1 +++ b/module/InforcerCommunity.psd1 @@ -19,6 +19,8 @@ 'Get-InforcerAuditEvent' 'Get-InforcerSupportedEventType' 'Get-InforcerUser' + 'New-InforcerUser' + 'Set-InforcerUser' 'Get-InforcerGroup' 'Get-InforcerRole' 'Get-InforcerSecureScore' diff --git a/module/Private/ConvertTo-InforcerUserBody.ps1 b/module/Private/ConvertTo-InforcerUserBody.ps1 new file mode 100644 index 0000000..da23bd5 --- /dev/null +++ b/module/Private/ConvertTo-InforcerUserBody.ps1 @@ -0,0 +1,35 @@ +function ConvertTo-InforcerUserBody { + <# + .SYNOPSIS + Builds the userProfile part of a create or update body from bound parameters (Private helper). + .DESCRIPTION + Only parameters the caller passed are included, so an update leaves every other field as it is + (JSON Merge Patch). An empty string or an empty array becomes null, which clears the field. + Parameter names map to the API names by lowercasing the first letter. + #> + [CmdletBinding()] + [OutputType([System.Collections.Specialized.OrderedDictionary])] + param( + [Parameter(Mandatory = $true)] + [System.Collections.Generic.IDictionary[string, object]]$BoundParameters + ) + + $fields = 'AccountEnabled', 'DisplayName', 'MailNickname', 'UserPrincipalName', 'GivenName', 'Surname', + 'JobTitle', 'Department', 'OfficeLocation', 'StreetAddress', 'City', 'State', 'PostalCode', 'Country', + 'MobilePhone', 'UsageLocation', 'PreferredLanguage', 'CompanyName', 'EmployeeId', 'EmployeeType', + 'Mail', 'BusinessPhones', 'OtherMails', 'ManagerId' + + $body = [ordered]@{} + foreach ($name in $fields) { + if (-not $BoundParameters.ContainsKey($name)) { continue } + $value = $BoundParameters[$name] + if ($value -is [array]) { + $value = @($value | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) + if ($value.Count -eq 0) { $value = $null } + } elseif ($value -is [string] -and $value -eq '') { + $value = $null + } + $body[$name.Substring(0, 1).ToLowerInvariant() + $name.Substring(1)] = $value + } + $body +} diff --git a/module/Private/Invoke-InforcerApiRequest.ps1 b/module/Private/Invoke-InforcerApiRequest.ps1 index b3b51d8..336e5d9 100644 --- a/module/Private/Invoke-InforcerApiRequest.ps1 +++ b/module/Private/Invoke-InforcerApiRequest.ps1 @@ -152,6 +152,14 @@ function Invoke-InforcerApiRequest { elseif ($problemDetail) { $problemDetail } else { $title } $fieldErrors = Format-InforcerProblemError -Errors $props['errors'].Value if ($fieldErrors) { $apiMessage = "$apiMessage ($fieldErrors)" } + # A partly applied operation lists each step, e.g. "profile: succeeded; manager: failed (reason)". + $steps = foreach ($r in @($props['results'].Value)) { + if ($r -isnot [System.Management.Automation.PSCustomObject]) { continue } + $step = "$($r.PSObject.Properties['step'].Value): $($r.PSObject.Properties['status'].Value)" + $why = $r.PSObject.Properties['title'].Value -as [string] + if ($why) { "$step ($why)" } else { $step } + } + if ($steps) { $apiMessage = "$apiMessage Steps: $(@($steps) -join '; ')" } $traceId = ($props['traceId'].Value -as [string]) } elseif ($isAppEnvelope -or $null -ne $props['errors']) { # App-layer envelope { success, message, errors[], errorCode } @@ -204,6 +212,9 @@ function Invoke-InforcerApiRequest { return } + # 204 No Content (an update): success with nothing to return. + if ($statusCode -eq 204) { return } + if ($null -eq $rawResponse -or ($rawResponse -is [string] -and [string]::IsNullOrWhiteSpace($rawResponse))) { Write-Error -Message 'API returned an empty response.' -ErrorId 'EmptyResponse' -Category InvalidData return diff --git a/module/Public/New-InforcerUser.ps1 b/module/Public/New-InforcerUser.ps1 new file mode 100644 index 0000000..b1eb221 --- /dev/null +++ b/module/Public/New-InforcerUser.ps1 @@ -0,0 +1,246 @@ +function New-InforcerUser { + <# + .SYNOPSIS + Creates a Microsoft Entra user in a tenant. + + Required API scope(s): none; the API-key (beta) API cannot create users. + Required permission: User & Group Management (API client, unconfirmed which grant). + + .DESCRIPTION + Creates a user with POST /tenants/{msTenantId}/users. Needs a login with an API client + (Connect-Inforcer -ClientId -ClientSecret); an API-key login gets the error RequiresApiClient. + + The user can sign in by default (-AccountEnabled $true) and must change the password at the + first sign-in (-ForceChangePasswordNextSignIn $true). -MailNickname defaults to the part of + -UserPrincipalName before the @. The password must meet the tenant's password policy. + + Returns the new user's id with the tenant, display name and user principal name, so the result + can be piped to Set-InforcerUser. A new user can take a few seconds to show in Get-InforcerUser. + + .PARAMETER TenantId + The tenant's Microsoft tenant GUID or tenant name. Supports pipeline input by property name. + + .PARAMETER DisplayName + The name shown for the user. + + .PARAMETER UserPrincipalName + The sign-in name, such as jo.bloggs@contoso.com. The domain must be verified in the tenant. + + .PARAMETER Password + The initial password as a SecureString. It must meet the tenant's password policy. + + .PARAMETER MailNickname + The mail alias. Defaults to the part of -UserPrincipalName before the @. + + .PARAMETER ForceChangePasswordNextSignIn + Whether the user must change the password at the first sign-in. Default: $true. + + .PARAMETER AccountEnabled + Whether the user can sign in. Default: $true. + + .PARAMETER GivenName + First name. + + .PARAMETER Surname + Last name. + + .PARAMETER JobTitle + Job title. + + .PARAMETER Department + Department. + + .PARAMETER OfficeLocation + Office location. + + .PARAMETER StreetAddress + Street address. + + .PARAMETER City + City. + + .PARAMETER State + State or province. + + .PARAMETER PostalCode + Postal code. + + .PARAMETER Country + Country or region. + + .PARAMETER MobilePhone + Mobile phone number. + + .PARAMETER UsageLocation + Two-letter country code (ISO 3166) where the user's licences are used, such as GB. Needed before + licences can be assigned. + + .PARAMETER PreferredLanguage + Preferred language, such as en-GB. + + .PARAMETER CompanyName + Company name. + + .PARAMETER EmployeeId + Employee id (at most 16 characters). + + .PARAMETER EmployeeType + Employee type, such as Employee or Contractor. + + .PARAMETER Mail + Email address. + + .PARAMETER BusinessPhones + Business phone number. Microsoft Entra allows one. + + .PARAMETER OtherMails + Other email addresses. + + .PARAMETER ManagerId + The Microsoft Entra object id of the user's manager. + + .PARAMETER OutputType + Output type: 'PowerShellObject' (default) or 'JsonObject' (JSON string, depth 100). + Piped tenants with JsonObject return one array for all of them. + + .EXAMPLE + $password = Read-Host -AsSecureString -Prompt 'Initial password' + New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password + + Creates Jo Bloggs in the tenant Contoso. Jo must change the password at the first sign-in. + + .EXAMPLE + New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password -GivenName 'Jo' -Surname 'Bloggs' -Department 'Sales' -UsageLocation 'GB' -AccountEnabled $false + + Creates the user with profile details, but blocked from signing in until enabled with Set-InforcerUser. + + .EXAMPLE + New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password -WhatIf + + Shows what would be created without creating it. + + .EXAMPLE + New-InforcerUser -TenantId 'Contoso' -DisplayName 'Jo Bloggs' -UserPrincipalName 'jo.bloggs@contoso.com' -Password $password -OutputType JsonObject + + Returns the new user's id, tenant, display name and user principal name as a JSON string. + + .OUTPUTS + PSObject or String (when -OutputType JsonObject) + + .LINK + https://github.com/royklo/InforcerCommunity/blob/main/docs/CMDLET-REFERENCE.md#new-inforceruser + + .LINK + Set-InforcerUser + + .LINK + Get-InforcerUser + #> + [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] + [OutputType([PSObject], [string])] + param( + [Parameter(Mandatory, ValueFromPipelineByPropertyName)] + [Alias('ClientTenantId', 'MsTenantId')] + [object]$TenantId, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$DisplayName, + + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$UserPrincipalName, + + [Parameter(Mandatory)] + [System.Security.SecureString]$Password, + + [ValidateNotNullOrEmpty()] + [string]$MailNickname, + + [bool]$ForceChangePasswordNextSignIn = $true, + + [bool]$AccountEnabled = $true, + + [string]$GivenName, + [string]$Surname, + [string]$JobTitle, + [string]$Department, + [string]$OfficeLocation, + [string]$StreetAddress, + [string]$City, + [string]$State, + [string]$PostalCode, + [string]$Country, + [string]$MobilePhone, + [string]$UsageLocation, + [string]$PreferredLanguage, + [string]$CompanyName, + [string]$EmployeeId, + [string]$EmployeeType, + [string]$Mail, + [string[]]$BusinessPhones, + [string[]]$OtherMails, + [string]$ManagerId, + + [ValidateSet('PowerShellObject', 'JsonObject')] + [string]$OutputType = 'PowerShellObject' + ) + + begin { $pipedJson = [System.Collections.Generic.List[object]]::new() } + + process { + if (-not (Test-InforcerSession)) { + Write-Error -Message 'Not connected to Inforcer. Use Connect-Inforcer first.' -ErrorId 'NotConnected' -Category ConnectionError + return + } + if ($script:InforcerSession.ApiVersion -ne 'v1') { + Write-Error -Message 'Creating users needs a login with an API client (Connect-Inforcer -ClientId -ClientSecret). The API-key (beta) API cannot create users.' -ErrorId 'RequiresApiClient' -Category InvalidOperation + return + } + + try { + $resolvedTenantId = Resolve-InforcerTenantId -TenantId $TenantId + } catch { + Write-Error -Message $_.Exception.Message -ErrorId 'InvalidTenantId' -Category InvalidArgument + return + } + + if (-not $PSCmdlet.ShouldProcess("$UserPrincipalName in tenant $resolvedTenantId", 'Create user')) { return } + + $body = ConvertTo-InforcerUserBody -BoundParameters $PSBoundParameters + $body['accountEnabled'] = $AccountEnabled + if (-not $body['mailNickname']) { $body['mailNickname'] = ($UserPrincipalName -split '@')[0] } + $body['passwordProfile'] = [ordered]@{ + password = ConvertFrom-InforcerSecureString -SecureString $Password + forceChangePasswordNextSignIn = $ForceChangePasswordNextSignIn + } + try { + $json = $body | ConvertTo-Json -Depth 100 -Compress + $body = $null + $response = Invoke-InforcerApiRequest -Endpoint "/tenants/$resolvedTenantId/users" -Method POST -Body $json -PreserveStructure + } finally { + $json = $null + $body = $null + } + if ($null -eq $response) { return } + + foreach ($p in ([ordered]@{ TenantId = $resolvedTenantId; displayName = $DisplayName; userPrincipalName = $UserPrincipalName }).GetEnumerator()) { + if (-not $response.PSObject.Properties[$p.Key]) { + $response.PSObject.Properties.Add([System.Management.Automation.PSNoteProperty]::new($p.Key, $p.Value)) + } + } + + if ($OutputType -eq 'JsonObject') { + if ($PSCmdlet.MyInvocation.ExpectingInput) { $pipedJson.Add($response); return } + return $response | ConvertTo-Json -Depth 100 + } + $response.PSObject.TypeNames.Insert(0, 'InforcerCommunity.CreatedUser') + $response + } + + end { + if ($PSCmdlet.MyInvocation.ExpectingInput -and $OutputType -eq 'JsonObject' -and $pipedJson.Count -gt 0) { + ConvertTo-Json -InputObject @($pipedJson) -Depth 100 + } + } +} diff --git a/module/Public/Set-InforcerUser.ps1 b/module/Public/Set-InforcerUser.ps1 new file mode 100644 index 0000000..adee20b --- /dev/null +++ b/module/Public/Set-InforcerUser.ps1 @@ -0,0 +1,216 @@ +function Set-InforcerUser { + <# + .SYNOPSIS + Updates a Microsoft Entra user's profile, manager or sign-in in a tenant. + + Required API scope(s): none; the API-key (beta) API cannot update users. + Required permission: User & Group Management (API client, unconfirmed which grant). + + .DESCRIPTION + Updates a user with PATCH /tenants/{msTenantId}/users/{userId}. Needs a login with an API client + (Connect-Inforcer -ClientId -ClientSecret); an API-key login gets the error RequiresApiClient. + + Only the parameters you pass are changed; everything else stays as it is. Pass an empty string + ('') or $null to clear a field, such as -JobTitle '' or -ManagerId '' to remove the manager. + DisplayName, MailNickname, UserPrincipalName and Mail cannot be cleared. + + -AccountEnabled $false blocks sign-in, but existing sessions last until their tokens expire. + A change can take a few seconds to show in Get-InforcerUser. Returns nothing. + + When the manager could not be changed but the other changes were saved, the error lists + each step and whether it was applied. + + .PARAMETER TenantId + The tenant's Microsoft tenant GUID or tenant name. Supports pipeline input by property name. + + .PARAMETER UserId + The user's Microsoft Entra object id. Supports pipeline input by property name (also from id), + so users from Get-InforcerUser or New-InforcerUser can be piped in. + + .PARAMETER AccountEnabled + Whether the user can sign in. + + .PARAMETER DisplayName + The name shown for the user. Cannot be cleared. + + .PARAMETER MailNickname + The mail alias. Cannot be cleared. + + .PARAMETER UserPrincipalName + The sign-in name, such as jo.bloggs@contoso.com. Cannot be cleared. + + .PARAMETER GivenName + First name. '' clears it. + + .PARAMETER Surname + Last name. '' clears it. + + .PARAMETER JobTitle + Job title. '' clears it. + + .PARAMETER Department + Department. '' clears it. + + .PARAMETER OfficeLocation + Office location. '' clears it. + + .PARAMETER StreetAddress + Street address. '' clears it. + + .PARAMETER City + City. '' clears it. + + .PARAMETER State + State or province. '' clears it. + + .PARAMETER PostalCode + Postal code. '' clears it. + + .PARAMETER Country + Country or region. '' clears it. + + .PARAMETER MobilePhone + Mobile phone number. '' clears it. + + .PARAMETER UsageLocation + Two-letter country code (ISO 3166) where the user's licences are used, such as GB. '' clears it. + + .PARAMETER PreferredLanguage + Preferred language, such as en-GB. '' clears it. + + .PARAMETER CompanyName + Company name. '' clears it. + + .PARAMETER EmployeeId + Employee id (at most 16 characters). '' clears it. + + .PARAMETER EmployeeType + Employee type, such as Employee or Contractor. '' clears it. + + .PARAMETER Mail + Email address. Cannot be cleared. + + .PARAMETER BusinessPhones + Business phone number. Microsoft Entra allows one. @() clears it. + + .PARAMETER OtherMails + Other email addresses. Replaces the whole list; @() clears it. + + .PARAMETER ManagerId + The Microsoft Entra object id of the user's manager. '' removes the manager. + + .EXAMPLE + Set-InforcerUser -TenantId 'Contoso' -UserId '00000000-0000-0000-0000-000000000005' -Department 'Sales' -JobTitle 'Account Manager' + + Changes the department and job title. Every other field stays as it is. + + .EXAMPLE + Set-InforcerUser -TenantId 'Contoso' -UserId '00000000-0000-0000-0000-000000000005' -AccountEnabled $false + + Blocks the user from signing in. + + .EXAMPLE + Get-InforcerUser -TenantId 'Contoso' -Search 'Adele' | Set-InforcerUser -TenantId 'Contoso' -ManagerId '' + + Removes the manager of every user matching "Adele". + + .EXAMPLE + Set-InforcerUser -TenantId 'Contoso' -UserId '00000000-0000-0000-0000-000000000005' -UsageLocation 'GB' -WhatIf + + Shows what would change without changing it. + + .OUTPUTS + None + + .LINK + https://github.com/royklo/InforcerCommunity/blob/main/docs/CMDLET-REFERENCE.md#set-inforceruser + + .LINK + New-InforcerUser + + .LINK + Get-InforcerUser + #> + [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')] + [OutputType([void])] + param( + [Parameter(Mandatory, ValueFromPipelineByPropertyName)] + [Alias('ClientTenantId', 'MsTenantId')] + [object]$TenantId, + + [Parameter(Mandatory, ValueFromPipelineByPropertyName)] + [Alias('Id')] + [ValidateNotNullOrEmpty()] + [string]$UserId, + + [bool]$AccountEnabled, + + [ValidateNotNullOrEmpty()] + [string]$DisplayName, + + [ValidateNotNullOrEmpty()] + [string]$MailNickname, + + [ValidateNotNullOrEmpty()] + [string]$UserPrincipalName, + + [string]$GivenName, + [string]$Surname, + [string]$JobTitle, + [string]$Department, + [string]$OfficeLocation, + [string]$StreetAddress, + [string]$City, + [string]$State, + [string]$PostalCode, + [string]$Country, + [string]$MobilePhone, + [string]$UsageLocation, + [string]$PreferredLanguage, + [string]$CompanyName, + [string]$EmployeeId, + [string]$EmployeeType, + + [ValidateNotNullOrEmpty()] + [string]$Mail, + + [AllowNull()] + [AllowEmptyCollection()] + [string[]]$BusinessPhones, + + [AllowNull()] + [AllowEmptyCollection()] + [string[]]$OtherMails, + + [string]$ManagerId + ) + + process { + if (-not (Test-InforcerSession)) { + Write-Error -Message 'Not connected to Inforcer. Use Connect-Inforcer first.' -ErrorId 'NotConnected' -Category ConnectionError + return + } + if ($script:InforcerSession.ApiVersion -ne 'v1') { + Write-Error -Message 'Updating users needs a login with an API client (Connect-Inforcer -ClientId -ClientSecret). The API-key (beta) API cannot update users.' -ErrorId 'RequiresApiClient' -Category InvalidOperation + return + } + + $body = ConvertTo-InforcerUserBody -BoundParameters $PSBoundParameters + if ($body.Count -eq 0) { + Write-Error -Message 'Nothing to change: pass at least one property, such as -Department or -AccountEnabled.' -ErrorId 'NoChangeSpecified' -Category InvalidArgument + return + } + + try { + $resolvedTenantId = Resolve-InforcerTenantId -TenantId $TenantId + } catch { + Write-Error -Message $_.Exception.Message -ErrorId 'InvalidTenantId' -Category InvalidArgument + return + } + + if (-not $PSCmdlet.ShouldProcess("user $UserId in tenant $resolvedTenantId", "Update $(@($body.Keys) -join ', ')")) { return } + + $json = $body | ConvertTo-Json -Depth 100 -Compress + $null = Invoke-InforcerApiRequest -Endpoint "/tenants/$resolvedTenantId/users/$([System.Uri]::EscapeDataString($UserId))" -Method PATCH -Body $json + } +} diff --git a/module/README.md b/module/README.md index ee7c4d6..082c1f3 100644 --- a/module/README.md +++ b/module/README.md @@ -11,7 +11,7 @@ module/ ├── InforcerCommunity.Format.ps1xml # Default table/list formats ├── InforcerCommunity.Types.ps1xml # Type definitions ├── README.md # This file -├── Public/ # Exported cmdlets (21) +├── Public/ # Exported cmdlets (23) │ ├── Connect-Inforcer.ps1 │ ├── Disconnect-Inforcer.ps1 │ ├── Test-InforcerConnection.ps1 @@ -22,6 +22,8 @@ module/ │ ├── Get-InforcerAuditEvent.ps1 │ ├── Get-InforcerSupportedEventType.ps1 │ ├── Get-InforcerUser.ps1 +│ ├── New-InforcerUser.ps1 +│ ├── Set-InforcerUser.ps1 │ ├── Get-InforcerGroup.ps1 │ ├── Get-InforcerRole.ps1 │ ├── Get-InforcerSecureScore.ps1 diff --git a/scripts/Test-AllCmdlets.ps1 b/scripts/Test-AllCmdlets.ps1 index 15e4989..c1f2328 100644 --- a/scripts/Test-AllCmdlets.ps1 +++ b/scripts/Test-AllCmdlets.ps1 @@ -51,6 +51,13 @@ foreach ($name in $exported) { 'Get-InforcerUser' { $out = & $name -TenantId 1 -ErrorVariable err -ErrorAction SilentlyContinue } + 'New-InforcerUser' { + $pw = ConvertTo-SecureString -String 'dummy' -AsPlainText -Force + $out = & $name -TenantId 1 -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $pw -ErrorVariable err -ErrorAction SilentlyContinue + } + 'Set-InforcerUser' { + $out = & $name -TenantId 1 -UserId '00000000-0000-0000-0000-000000000000' -Department 'Sales' -ErrorVariable err -ErrorAction SilentlyContinue + } 'Get-InforcerGroup' { $out = & $name -TenantId 1 -ErrorVariable err -ErrorAction SilentlyContinue } From f2e2b63575ec2c6d80e0dd88e6917fc89fae0935 Mon Sep 17 00:00:00 2001 From: Roy Klooster <76492458+royklo@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:21:16 +0100 Subject: [PATCH 2/2] fix: zero a failed request's body in the shared credential cleanup A failed web call keeps the disposed request on its ErrorRecord, and the disposed body's bytes stay in memory, reachable by reflection: for New-InforcerUser that is the initial password. Clear-InforcerRequestCredential already strips the auth headers from that request; it now also zeroes the body bytes, so every request path is covered. The regression test fails without the fix. Co-Authored-By: Claude Opus 5.5 --- Tests/V1.UserWrite.Tests.ps1 | 19 +++++++++++++++++++ module/Private/Get-InforcerAuthHeader.ps1 | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/Tests/V1.UserWrite.Tests.ps1 b/Tests/V1.UserWrite.Tests.ps1 index cbd2f03..d3e9fa7 100644 --- a/Tests/V1.UserWrite.Tests.ps1 +++ b/Tests/V1.UserWrite.Tests.ps1 @@ -92,6 +92,25 @@ Describe 'New-InforcerUser' { ($verbose | Out-String) | Should -Not -BeLike '*Example-Passw0rd!*' } + It 'leaves no readable password in the retained request after a transport failure' { + Set-UwSession + $global:UwSent = $null + Mock -ModuleName InforcerCommunity Invoke-InforcerHttpRequest { + # What a failed Invoke-RestMethod leaves: the disposed request as the ErrorRecord's TargetObject. + $msg = [System.Net.Http.HttpRequestMessage]::new('POST', [string]$Request.Uri) + $msg.Content = [System.Net.Http.StringContent]::new($Request.Body) + $msg.Dispose() + $global:UwSent = $msg + throw [System.Management.Automation.ErrorRecord]::new([System.Net.Http.HttpRequestException]::new('No such host is known.'), 'WebCmdletWebResponseException', 'ConnectionError', $msg) + } + New-InforcerUser -TenantId $script:Tid -DisplayName 'Jo' -UserPrincipalName 'jo@contoso.com' -Password $script:Pw -ErrorAction SilentlyContinue -ErrorVariable e + ($e | Out-String) | Should -Not -BeLike '*Example-Passw0rd!*' + $field = [System.Net.Http.ByteArrayContent].GetField('_content', [System.Reflection.BindingFlags]'NonPublic, Instance') + $field | Should -Not -BeNullOrEmpty -Because 'the cleanup relies on this field; a runtime without it needs another approach' + [System.Text.Encoding]::UTF8.GetString($field.GetValue($global:UwSent.Content)) | Should -Not -BeLike '*Example-Passw0rd!*' + Remove-Variable -Name UwSent -Scope Global + } + It 'makes no request with -WhatIf' { Set-UwSession Set-UwRoute { param($Uri, $Method, $Body) New-UwResponse '{"id":"x"}' 201 } diff --git a/module/Private/Get-InforcerAuthHeader.ps1 b/module/Private/Get-InforcerAuthHeader.ps1 index aba985d..25b0560 100644 --- a/module/Private/Get-InforcerAuthHeader.ps1 +++ b/module/Private/Get-InforcerAuthHeader.ps1 @@ -61,6 +61,18 @@ function Clear-InforcerRequestCredential { if ($message -is [System.Net.Http.HttpRequestMessage]) { $null = $message.Headers.Remove('Authorization') $null = $message.Headers.Remove('Inf-Api-Key') + # The body (a new user's password, for example) is disposed but its bytes stay in memory; + # zero them. ponytail: private .NET field, so a runtime without it keeps the bytes. + if ($message.Content -is [System.Net.Http.ByteArrayContent]) { + try { + $field = [System.Net.Http.ByteArrayContent].GetField('_content', [System.Reflection.BindingFlags]'NonPublic, Instance') + # No if-expression around GetValue: it would unroll the byte[] into a copy. + if ($field) { + $bytes = $field.GetValue($message.Content) + if ($bytes -is [byte[]]) { [array]::Clear($bytes, 0, $bytes.Length) } + } + } catch { Write-Debug "Could not clear the request body: $($_.Exception.Message)" } + } } }