InformationProtection.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PSFPowerShellDataFile -Path "$($script:ModuleRoot)\InformationProtection.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName InformationProtection.Import.DoDotSource -Fallback $false
if ($InformationProtection_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName InformationProtection.Import.IndividualFiles -Fallback $false
if ($InformationProtection_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'InformationProtection' -Language 'en-US'

function Assert-MIPConnection {
    <#
    .SYNOPSIS
        Ensures the session is correctly connected already.
     
    .DESCRIPTION
        Ensures the session is correctly connected already.
        Throws a bloody terminating exception if not so.
        Use Connect-InformationProtection to connect first, which requires corresponding EntraAuth sessions.
     
    .PARAMETER Cmdlet
        The $PSCmdlet variable of the caller.
        Used to create the error in the context of the caller.
     
    .EXAMPLE
        PS C:\> Assert-MIPConnection -Cmdlet $PSCmdlet
 
        Ensures the session is correctly connected already.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Cmdlet
    )
    process {
        if ([InformationProtection.MipHost]::Context) { return }

        $errorRecord = [System.Management.Automation.ErrorRecord]::new(
            [System.InvalidOperationException]::new("Not yet connected! Use Connect-InformationProtection to connect first!"),
            "NotConnectedOmae!",
            [System.Management.Automation.ErrorCategory]::ConnectionError,
            $null
        )
        $Cmdlet.ThrowTerminatingError($errorRecord)
    }
}

function Connect-InformationProtection {
    <#
    .SYNOPSIS
        Connect the Microsoft Information Protection SDK with Entra.
     
    .DESCRIPTION
        Connect the Microsoft Information Protection SDK with Entra.
         
        There are two ways to perform the authentication:
 
        + Use previously established EntraAuth sessions
        + Create new sessions
 
        1) Previously established sessions
         
        If you have already previously established a connection using "Connect-EntraService", you can reuse those.
        By default, the services you need a connection to are "AzureRightsManagement" and "MIPSyncService".
        This option gives you the free choice about authentication methods used, covering all the scenarios supported by EntraAuth.
 
        Example 1:
 
        Connect-EntraService -TenantID $tenantID -ClientID $clientID -Service AzureRightsManagement
        Connect-EntraService -TenantID $tenantID -ClientID $clientID -Service MIPSyncService -UseRefreshToken
 
        Example 2:
 
        Connect-EntraService -TenantID $tenantID -ClientID $clientID -Service AzureRightsManagement, MIPSyncService -Certificate $cert
 
        2) Create new sessions
 
        You can establish new EntraAuth sessions as part of this command, by specifying the ClientID of the Entra Application to use:
 
        Connect-InformationProtection -ClientID $clientID
 
        This will always only be an interactive session, authenticating using the local default browser.
 
    .PARAMETER ServiceMap
        Optional hashtable to map service names to specific EntraAuth service instances.
        Used for advanced scenarios where you want to use something other than the default connections.
        Example: @{ AzureRightsManagement = 'MyARM' }
        This will switch all AzureRightsManagement API calls to use the service connection "MyARM".
 
    .PARAMETER ClientID
        The Application ID / Client ID of the Entra application used to authenticate.
        Specifying this will force the establishment of a new session through the browser.
        To reuse existing sessions, do not provide this parameter.
 
    .PARAMETER TenantID
        The tenant ID of the Entra application to use to authenticate.
        Defaults to: "organizations" (Which means the tenant, the selected account belongs to)
     
    .EXAMPLE
        PS C:\> Connect-InformationProtection
 
        Authenticate using already established EntraAuth sessions for the services "AzureRightsManagement" and "MIPSyncService".
 
    .EXAMPLE
        PS C:\> Connect-InformationProtection -ClientID $clientID
 
        Authenticate while creating new EntraAuth sessions for the services "AzureRightsManagement" and "MIPSyncService".
        This will only use the Authorization Code delegate authentication flow.
    #>

    [CmdletBinding()]
    param (
        [hashtable]
        $ServiceMap = @{},

        [string]
        $ClientID,

        [string]
        $TenantID = 'organizations'
    )
    begin {
        $services = $script:_serviceSelector.GetServiceMap($ServiceMap)

        if ($ClientID) {
            Connect-EntraService -TenantID $TenantID -ClientID $ClientID -Service $services.AzureRightsManagement
            Connect-EntraService -TenantID $TenantID -ClientID $ClientID -Service $services.MIPSyncService -UseRefreshToken
        }

        Assert-EntraConnection -Cmdlet $PSCmdlet -Service $services.AzureRightsManagement
        Assert-EntraConnection -Cmdlet $PSCmdlet -Service $services.MIPSyncService
    }
    process {
        $logPath = Join-Path -Path (Get-PSFPath -Name LocalAppData) -ChildPath 'PowerShell\InformationProtection\logs'
        [InformationProtection.MipHost]::Authenticate(
            (Get-EntraToken -Service $services.AzureRightsManagement),
            (Get-EntraToken -Service $services.MIPSyncService),
            $logPath
        )
    }
}

function Get-MipFile {
    <#
    .SYNOPSIS
        Returns the comprehensive label & protection status of a file.
         
    .DESCRIPTION
        Returns the comprehensive label & protection status of a file.
 
        Must be connected first using "Connect-InformationProtection".
     
    .PARAMETER Path
        Path to the file to scan.
     
    .EXAMPLE
        PS C:\> Get-MipFile -Path .\*
 
        Returns the label & protection status of every file in the current folder.
 
    .EXAMPLE
        PS C:\> Get-ChildItem -Recurse -File | Get-MipFile
 
        Returns the label & protection status of every file in the current folder and all subfolders.
    #>

    [OutputType([InformationProtection.File])]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [PSFFile]
        $Path
    )
    begin {
        Assert-MIPConnection -Cmdlet $PSCmdlet
    }
    process {
        foreach ($filePath in $Path) {
            [InformationProtection.File]::new($filePath)
        }
    }
}

function Get-MipLabel {
    <#
    .SYNOPSIS
        List available labels or labels assigned to a file.
         
    .DESCRIPTION
        List available labels or labels assigned to a file.
 
        Must be connected first using "Connect-InformationProtection".
     
    .PARAMETER Path
        Path to the file(s) to retrieve labels from.
        Note: Consider using Get-MipFile instead, for a more comprehensive few at the state of a file.
     
    .PARAMETER Filter
        Name to filter the scopes by, when listing the available scopes.
     
    .EXAMPLE
        PS C:\> Get-MipLabel
 
        List all available labels
 
    .EXAMPLE
        PS C:\> Get-MipLabel -Path .\accounting-summary.xlsx
 
        Returns the label applied to "accounting-summary.xlsx"
    #>

    [CmdletBinding(DefaultParameterSetName = 'List')]
    param (
        [Parameter(ValueFromPipeline = $true, ParameterSetName = 'File')]
        [PsfFile]
        $Path,
        
        [Parameter(ParameterSetName = 'List')]
        [string]
        $Filter = '*'
    )
    begin {
        Assert-MIPConnection -Cmdlet $PSCmdlet
    }
    process {
        if ($PSCmdlet.ParameterSetName -eq 'List') {
            foreach ($label in [InformationProtection.MipHost]::FileEngine.SensitivityLabels) {
                if ($label.ID -eq $Filter -or $label.Name -like $Filter -or $label.FQLN -like $Filter) { $label }
                foreach ($childLabel in $label.Children) {
                    if ($childLabel.ID -eq $Filter -or $childLabel.Name -like $Filter -or $childLabel.FQLN -like $Filter) { $childLabel }
                }
            }
            return
        }

        foreach ($file in $Path) {
            ([InformationProtection.File]$file).GetLabel()
        }
    }
}

function Set-MipLabel {
    <#
    .SYNOPSIS
        Applies a sensitivity label to a file.
     
    .DESCRIPTION
        Applies a sensitivity label to a file.
        _Downgrading_ a label's security level requires a Justification.
         
        The file being labeled will be temporarily duplicated, meaning ...
        - Write access to the folder is needed, not just the file (specifically, the ability to create a new file)
        - Delete access to the file being labeled is required (to enable rollback in case of error, the file gets renamed, which is essentially a delete & create operation)
        - Exclusive accesss to the file is required
        - Enough storage to copy the file is needed
 
        Must be connected first using "Connect-InformationProtection".
     
    .PARAMETER Label
        The label to apply.
     
    .PARAMETER Path
        Path to the file to label.
     
    .PARAMETER Justification
        The reason for the label change.
        This is required for any _changes_ to the label that downgrade its protection status.
 
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .EXAMPLE
        PS C:\> Set-MipLabel -Path .\test.docx -Label 'Highly Confidential\All Employees'
 
        Updates the label of test.docx to "Highly Confidential\All Employees"
 
    .EXAMPLE
        PS C:\> Get-ChildItem -Recurse -File | Set-MipLabel -Label Public
 
        Updates the label on all files in the current folder and subfolders to "Public"
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "")]
    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true)]
        [PsfArgumentCompleter('InformationProtection.Label')]
        [string]
        $Label,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [PsfFile]
        $Path,

        [string]
        $Justification
    )
    begin {
        Assert-MIPConnection -Cmdlet $PSCmdlet
        $killIt = $ErrorActionPreference -eq 'Stop'

        $labelObject = Get-MipLabel -Filter $Label
        if (-not $labelObject) {
            Stop-PSFFunction -String 'Set-MipLabel.Error.LabelNotFound' -StringValues $Label -Cmdlet $PSCmdlet -EnableException $true -Category InvalidArgument
        }
        if ($labelObject.ID -contains $Label) { $labelObject = $labelObject | Where-Object ID -eq $Label }
        elseif ($labelObject.FQLN -contains $Label) { $labelObject = $labelObject | Where-Object FQLN -eq $Label }

        if ($labelObject.Count -gt 1) {
            Stop-PSFFunction -String 'Set-MipLabel.Error.LabelAmbiguous' -StringValues $Label, ($labelObject.FQLN -join ', ') -Cmdlet $PSCmdlet -EnableException $true -Category InvalidArgument
        }
    }
    process {
        foreach ($filePath in $Path) {
            $file = [InformationProtection.File]$filePath
            $directory = Split-Path -Path $file.Path
            $fileName = Split-Path -Path $file.Path -Leaf
            $tempNewPath = Join-Path -Path $directory -ChildPath ([Guid]::NewGuid())
            $tempOldName = [Guid]::NewGuid().ToString()
            $tempOldPath = Join-Path -Path $directory -ChildPath $tempOldName
            Invoke-PSFProtectedCommand -ActionString 'Set-MipLabel.ApplyLabel' -ActionStringValues $labelObject.Name, $labelObject.ID -Target $file.Path -ScriptBlock {
                # Step 1: Label & New File
                $file.SetLabel($labelObject.ID, $tempNewPath, $Justification)

                # Step 2: Rename old file to temp name
                try { Rename-Item -LiteralPath $file.Path -NewName $tempOldName -Force -ErrorAction Stop }
                catch {
                    Remove-Item -LiteralPath $tempNewPath -Force
                    throw
                }

                # Step 3: Rename labeled file to original name
                try { Rename-Item -LiteralPath $tempNewPath -NewName $fileName -Force -ErrorAction Stop }
                catch {
                    # Rollback and delete new file
                    Rename-Item -LiteralPath $tempOldPath -NewName $fileName -Force
                    Remove-Item -LiteralPath $tempNewPath -Force
                    throw
                }

                # Step 4: Delete Renamed unlabeled file
                Remove-Item -LiteralPath $tempOldPath
            } -EnableException $killIt -PSCmdlet $PSCmdlet -Continue
        }
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'InformationProtection' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'InformationProtection' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'InformationProtection' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'InformationProtection.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "InformationProtection.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


Register-PSFTeppScriptblock -Name 'InformationProtection.Label' -ScriptBlock {
    foreach ($label in Get-MipLabel) {
        if (-not $label.IsActive) { continue }

        $toolTip = $label.FQLN
        if ($label.Description) { $toolTip = "$($toolTip) | $($label.Description)"    }

        @{ Text = $label.FQLN; ToolTip = $toolTip }
    }
} -Global

<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name InformationProtection.alcohol
#>


New-PSFLicense -Product 'InformationProtection' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2025-05-21") -Text @"
Copyright (c) 2025 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@


$script:_services = @{
    AzureRightsManagement = 'AzureRightsManagement'
    MIPSyncService = 'MIPSyncService'
}
$script:_serviceSelector = New-EntraServiceSelector -DefaultServices $script:_services

Register-EntraService -Name AzureRightsManagement -ServiceUrl 'https://aadrm.com/' -Resource 'https://aadrm.com/'
Register-EntraService -Name MIPSyncService -ServiceUrl 'https://psor.o365syncservice.com' -Resource 'https://psor.o365syncservice.com'

Register-PSFParameterClassMapping -ParameterClass Path -TypeName 'InformationProtection.File' -Properties Path
#endregion Load compiled code