Authentication and Connection Management
The glean-powershell module manages Glean API connectivity through a centralized, module-scoped connection state object that abstracts two distinct authentication modes: Token-based Bearer authentication and Cookie-based Single Sign-On (SSO). The Connect-Glean cmdlet serves as the primary entry point, accepting parameters to configure the deployment instance, API base URLs, and authentication credentials, while delegating to specialized internal workers for browser-based cookie capture or direct token validation. Once established, the connection state is stored in $script:GleanConnection, allowing subsequent API requests to automatically inject the appropriate headers or session cookies without requiring repeated user interaction.
Connection Initialization and Modes
Section titled “Connection Initialization and Modes”The Connect-Glean function determines the authentication mode based on the parameter set used during invocation. It supports two primary modes: Token and Cookie.
Token Mode
Section titled “Token Mode”In Token mode, the module authenticates against the REST API using a Bearer token. The deployment target is specified either via the -Instance parameter, which expands to https://<instance>-be.glean.com, or via an explicit -BaseUrl 1. The token itself can be provided as a SecureString or plaintext string via the -Token parameter, or it falls back to the GLEAN_API_TOKEN environment variable. If neither is provided, the function throws an ArgumentException. The plaintext token is converted to a SecureString using ConvertTo-SecureString with the -AsPlainText flag to ensure secure storage in memory.
Cookie (SSO) Mode
Section titled “Cookie (SSO) Mode”Cookie mode is selected using the -CookieAuth switch and is designed for environments protected by an identity provider that does not issue API tokens. This mode requires a -WebAppUrl to initiate the sign-in process. The module launches a browser (Auto, Edge, or Chrome) to capture the SSO session cookies. These cookies are then stored encrypted and reused for subsequent requests, enabling headless operation such as in MCP servers. The API base URL defaults to the origin of the WebAppUrl but can be overridden with -ApiBaseUrl.
Connection State Management
Section titled “Connection State Management”The active connection is stored in the module-scoped variable $script:GleanConnection 2. This object is a pscustomobject that contains all necessary context for making API requests, including the authentication mode, base URL, API prefixes, and credentials.
The Connection Object Structure
Section titled “The Connection Object Structure”The New-GleanConnection function constructs this object, ensuring a consistent shape regardless of the auth mode. Key properties include:
AuthMode: Either'Token'or'Cookie'.BaseUrl: The trimmed base URL for the API.ApiPrefix: A hashtable defining path prefixes for client and indexing APIs, defaulting to/rest/api/v1and/api/index/v1respectively.Token: TheSecureStringbearer token (present only in Token mode).WebSession: AWebRequestSessionobject containing cookies (present only in Cookie mode).DefaultHeaders: A hashtable for custom headers likeX-Glean-ActAsorX-Glean-Auth-Type1.SyncedAtandConnectedAt: Timestamps for tracking connection lifecycle 2.
Inspecting Connection State
Section titled “Inspecting Connection State”Engineers can inspect the current connection using Get-GleanConnection. This function returns a redacted view of the connection state via Get-GleanConnectionView 3. The view explicitly excludes sensitive data; for example, it reports HasToken as a boolean rather than exposing the token value, and similarly reports HasCookies based on the presence of the WebSession object 2. If no connection exists, it returns $null 3.
Cleanup and Security
Section titled “Cleanup and Security”Disconnecting
Section titled “Disconnecting”The Disconnect-Glean cmdlet clears the active connection by setting $script:GleanConnection to $null 4. This ensures that subsequent API calls will fail with a clear error message unless a new connection is established 2.
Cookie Storage and Security
Section titled “Cookie Storage and Security”In Cookie mode, captured cookies are saved using Save-GleanCookieState 1. The module supports rebuilding a connection from this stored state using the -FromStore parameter, which avoids opening a browser window. The Convert-GleanSecureStringToPlain helper function is available for internal use to convert secure strings to plaintext when necessary, but it securely zeroes the memory after use to prevent leakage 2. For cookie capture, the module uses a debug transport that can be configured with AllowUnsafeDebugPort for local loopback access, though this is restricted in non-interactive contexts due to security risks 1.
<#
.SYNOPSIS
Establish a connection to a Glean deployment using an API token or browser SSO cookies.
.DESCRIPTION
Two auth modes:
Token - a Bearer API token against the REST API. Use -Instance or -BaseUrl plus -Token
(or set the token environment variable). Enables the full typed cmdlet surface.
Cookie - capture a single-sign-on session from a browser for an endpoint protected by an
identity provider that does not issue API tokens. Use -CookieAuth with -WebAppUrl.
A browser window opens for you to sign in; the session is captured and stored
encrypted, then reused (including headless, for example by the MCP server). Cookie
mode targets the web-client API via Invoke-GleanWebRequest.
All endpoints, domains, versions, ports, and browser paths are parameters. Nothing is hardcoded.
.PARAMETER Instance
Token mode: the deployment name. Expands to https://<instance>-be.glean.com.
.PARAMETER BaseUrl
Token mode: an explicit REST API base URL.
.PARAMETER Token
Token mode: the API bearer token (SecureString or string). Falls back to the GLEAN_API_TOKEN
environment variable.
.PARAMETER CookieAuth
Select cookie/SSO auth mode.
.PARAMETER WebAppUrl
Cookie mode: the sign-in URL of the protected web app. Required.
.PARAMETER ApiBaseUrl
Cookie mode: the API base URL. Defaults to the WebAppUrl origin.
.PARAMETER ApiPathPrefix
Cookie mode: the API path prefix used by Invoke-GleanWebRequest. Default '/rest/api/v1'.
.PARAMETER ClientVersion
Cookie mode: an optional clientVersion query value some deployments require.
.PARAMETER CookieDomain
Cookie mode: the cookie domain to capture. Defaults to the WebAppUrl host.
.PARAMETER Browser
Cookie mode: Auto (default), Edge, or Chrome.
.PARAMETER BrowserPath
Cookie mode: explicit path to the browser executable.
.PARAMETER AllowUnsafeDebugPort
# Module-scoped connection state, set by Connect-Glean and consumed by Invoke-GleanRequest.
# The connection abstracts the auth provider: Token (Bearer over the REST API) or Cookie
# (a browser SSO WebRequestSession over a web-client API). The HTTP layer branches on AuthMode.
$script:GleanConnection = $null
# Default REST API path prefixes for token mode.
$script:GleanDefaultApiPrefix = @{ client = '/rest/api/v1'; indexing = '/api/index/v1' }
function Get-GleanConnectionOrThrow {
[CmdletBinding()]
param()
if ($null -eq $script:GleanConnection) {
throw [System.InvalidOperationException]::new(
'Not connected to Glean. Call Connect-Glean first (-Token or -CookieAuth).')
}
return $script:GleanConnection
}
function New-GleanConnection {
# Build and store the module connection object. Centralized so both auth modes share shape.
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateSet('Token', 'Cookie')][string] $AuthMode,
[Parameter(Mandatory)][string] $BaseUrl,
[hashtable] $ApiPrefix,
[securestring] $Token,
[Microsoft.PowerShell.Commands.WebRequestSession] $WebSession,
[string] $ClientVersion,
[string] $WebOrigin,
[string] $WebReferer,
[hashtable] $DefaultHeaders,
[datetime] $SyncedAt
)
$prefix = if ($ApiPrefix) { $ApiPrefix } else { $script:GleanDefaultApiPrefix }
$script:GleanConnection = [pscustomobject]@{
AuthMode = $AuthMode
BaseUrl = $BaseUrl.TrimEnd('/')
ApiPrefix = $prefix
Token = $Token
<#
.SYNOPSIS
Return the active Glean connection (token redacted).
.DESCRIPTION
Returns a view of the current connection state for inspection. The bearer token is never
returned in plain text; only whether one is set is reported.
.EXAMPLE
Get-GleanConnection
#>
function Get-GleanConnection {
[CmdletBinding()]
[OutputType([pscustomobject])]
param()
if ($null -eq $script:GleanConnection) {
Write-Verbose 'No active Glean connection.'
return $null
}
return Get-GleanConnectionView -Connection $script:GleanConnection
}
<#
.SYNOPSIS
Clear the active Glean connection and its stored token.
.DESCRIPTION
Removes the module-scoped connection state established by Connect-Glean.
.EXAMPLE
Disconnect-Glean
#>
function Disconnect-Glean {
[CmdletBinding()]
[OutputType([void])]
param()
$script:GleanConnection = $null
Write-Verbose 'Disconnected from Glean.'
}