|
| 1 | +/*! |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +import * as vscode from 'vscode' |
| 7 | +import { Auth } from '../../auth/auth' |
| 8 | +import { getSecondaryAuth } from '../../auth/secondaryAuth' |
| 9 | +import { ToolkitError } from '../../shared/errors' |
| 10 | +import { withTelemetryContext } from '../../shared/telemetry/util' |
| 11 | +import { SsoConnection } from '../../auth/connection' |
| 12 | +import { showReauthenticateMessage } from '../../shared/utilities/messages' |
| 13 | +import * as localizedText from '../../shared/localizedText' |
| 14 | +import { ToolkitPromptSettings } from '../../shared/settings' |
| 15 | +import { setContext } from '../../shared/vscode/setContext' |
| 16 | +import { DataZoneClient } from '../shared/client/datazoneClient' |
| 17 | +import { createSmusProfile, isValidSmusConnection, SmusConnection } from './model' |
| 18 | +import { getLogger } from '../../shared/logger/logger' |
| 19 | + |
| 20 | +/** |
| 21 | + * Sets the context variable for SageMaker Unified Studio connection state |
| 22 | + * @param isConnected Whether SMUS is connected |
| 23 | + */ |
| 24 | +export function setSmusConnectedContext(isConnected: boolean): Promise<void> { |
| 25 | + return setContext('aws.smus.connected', isConnected) |
| 26 | +} |
| 27 | +const authClassName = 'SmusAuthenticationProvider' |
| 28 | + |
| 29 | +/** |
| 30 | + * Authentication provider for SageMaker Unified Studio |
| 31 | + * Manages authentication state and credentials for SMUS |
| 32 | + */ |
| 33 | +export class SmusAuthenticationProvider { |
| 34 | + public readonly onDidChangeActiveConnection = this.secondaryAuth.onDidChangeActiveConnection |
| 35 | + private readonly onDidChangeEmitter = new vscode.EventEmitter<void>() |
| 36 | + public readonly onDidChange = this.onDidChangeEmitter.event |
| 37 | + |
| 38 | + public constructor( |
| 39 | + public readonly auth = Auth.instance, |
| 40 | + public readonly secondaryAuth = getSecondaryAuth( |
| 41 | + auth, |
| 42 | + 'smus', |
| 43 | + 'SageMaker Unified Studio', |
| 44 | + isValidSmusConnection |
| 45 | + ) |
| 46 | + ) { |
| 47 | + this.onDidChangeActiveConnection(async () => { |
| 48 | + await setSmusConnectedContext(this.isConnected()) |
| 49 | + this.onDidChangeEmitter.fire() |
| 50 | + }) |
| 51 | + |
| 52 | + // Set initial context in case event does not trigger |
| 53 | + void setSmusConnectedContext(this.isConnectionValid()) |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Gets the active connection |
| 58 | + */ |
| 59 | + public get activeConnection() { |
| 60 | + return this.secondaryAuth.activeConnection |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * Checks if using a saved connection |
| 65 | + */ |
| 66 | + public get isUsingSavedConnection() { |
| 67 | + return this.secondaryAuth.hasSavedConnection |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Checks if the connection is valid |
| 72 | + */ |
| 73 | + public isConnectionValid(): boolean { |
| 74 | + return this.activeConnection !== undefined && !this.secondaryAuth.isConnectionExpired |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Checks if connected to SMUS |
| 79 | + */ |
| 80 | + public isConnected(): boolean { |
| 81 | + return this.activeConnection !== undefined |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * Restores the previous connection |
| 86 | + * Uses a promise to prevent multiple simultaneous restore calls |
| 87 | + */ |
| 88 | + public async restore() { |
| 89 | + await this.secondaryAuth.restoreConnection() |
| 90 | + } |
| 91 | + |
| 92 | + /** |
| 93 | + * Authenticates with SageMaker Unified Studio using a domain URL |
| 94 | + * @param domainUrl The SageMaker Unified Studio domain URL |
| 95 | + * @returns Promise resolving to the connection |
| 96 | + */ |
| 97 | + @withTelemetryContext({ name: 'connectToSmus', class: authClassName }) |
| 98 | + public async connectToSmus(domainUrl: string): Promise<SmusConnection> { |
| 99 | + const logger = getLogger() |
| 100 | + |
| 101 | + try { |
| 102 | + // Create DataZoneClient instance and extract domain info |
| 103 | + const dataZoneClient = DataZoneClient.getInstance() |
| 104 | + const { domainId, region } = dataZoneClient.extractDomainInfoFromUrl(domainUrl) |
| 105 | + |
| 106 | + // Validate domain ID |
| 107 | + if (!domainId) { |
| 108 | + throw new ToolkitError('Invalid domain URL format', { code: 'InvalidDomainUrl' }) |
| 109 | + } |
| 110 | + |
| 111 | + logger.info(`SMUS: Connecting to domain ${domainId} in region ${region}`) |
| 112 | + |
| 113 | + // Check if we already have a connection for this domain |
| 114 | + const existingConn = (await this.auth.listConnections()).find( |
| 115 | + (c): c is SmusConnection => |
| 116 | + isValidSmusConnection(c) && (c as any).domainUrl?.toLowerCase() === domainUrl.toLowerCase() |
| 117 | + ) |
| 118 | + |
| 119 | + if (existingConn) { |
| 120 | + const connectionState = this.auth.getConnectionState(existingConn) |
| 121 | + logger.info(`SMUS: Found existing connection ${existingConn.id} with state: ${connectionState}`) |
| 122 | + |
| 123 | + // If connection is valid, use it directly without triggering new auth flow |
| 124 | + if (connectionState === 'valid') { |
| 125 | + logger.info('SMUS: Using existing valid connection') |
| 126 | + |
| 127 | + // Use the existing connection |
| 128 | + const result = await this.secondaryAuth.useNewConnection(existingConn) |
| 129 | + logger.debug(`SMUS: Reused existing connection successfully, id=${result.id}`) |
| 130 | + return result |
| 131 | + } |
| 132 | + |
| 133 | + // If connection is invalid or expired, reauthenticate |
| 134 | + if (connectionState === 'invalid') { |
| 135 | + logger.info('SMUS: Existing connection is invalid, reauthenticating') |
| 136 | + const reauthenticatedConn = await this.reauthenticate(existingConn) |
| 137 | + |
| 138 | + // Create the SMUS connection wrapper |
| 139 | + const smusConn: SmusConnection = { |
| 140 | + ...reauthenticatedConn, |
| 141 | + domainUrl, |
| 142 | + domainId, |
| 143 | + } |
| 144 | + |
| 145 | + const result = await this.secondaryAuth.useNewConnection(smusConn) |
| 146 | + logger.debug(`SMUS: Reauthenticated connection successfully, id=${result.id}`) |
| 147 | + return result |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + // No existing connection found, create a new one |
| 152 | + logger.info('SMUS: No existing connection found, creating new connection') |
| 153 | + |
| 154 | + // Get SSO instance info from DataZone |
| 155 | + const ssoInstanceInfo = await dataZoneClient.getSsoInstanceInfo(domainUrl) |
| 156 | + |
| 157 | + // Create a new connection |
| 158 | + const profile = createSmusProfile(domainUrl, domainId, ssoInstanceInfo.issuerUrl, ssoInstanceInfo.region) |
| 159 | + const newConn = await this.auth.createConnection(profile) |
| 160 | + logger.debug(`SMUS: Created new connection ${newConn.id}`) |
| 161 | + |
| 162 | + const smusConn: SmusConnection = { |
| 163 | + ...newConn, |
| 164 | + domainUrl, |
| 165 | + domainId, |
| 166 | + } |
| 167 | + |
| 168 | + const result = await this.secondaryAuth.useNewConnection(smusConn) |
| 169 | + return result |
| 170 | + } catch (e) { |
| 171 | + throw ToolkitError.chain(e, 'Failed to connect to SageMaker Unified Studio', { |
| 172 | + code: 'FailedToConnect', |
| 173 | + }) |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Reauthenticates an existing connection |
| 179 | + * @param conn Connection to reauthenticate |
| 180 | + * @returns Promise resolving to the reauthenticated connection |
| 181 | + */ |
| 182 | + @withTelemetryContext({ name: 'reauthenticate', class: authClassName }) |
| 183 | + public async reauthenticate(conn: SsoConnection) { |
| 184 | + try { |
| 185 | + return await this.auth.reauthenticate(conn) |
| 186 | + } catch (err) { |
| 187 | + throw ToolkitError.chain(err, 'Unable to reauthenticate SageMaker Unified Studio connection.') |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + /** |
| 192 | + * Shows a reauthentication prompt to the user |
| 193 | + * @param conn Connection to reauthenticate |
| 194 | + */ |
| 195 | + public async showReauthenticationPrompt(conn: SsoConnection): Promise<void> { |
| 196 | + await showReauthenticateMessage({ |
| 197 | + message: localizedText.connectionExpired('SageMaker Unified Studio'), |
| 198 | + connect: localizedText.reauthenticate, |
| 199 | + suppressId: 'smusConnectionExpired', |
| 200 | + settings: ToolkitPromptSettings.instance, |
| 201 | + reauthFunc: async () => { |
| 202 | + await this.reauthenticate(conn) |
| 203 | + }, |
| 204 | + }) |
| 205 | + } |
| 206 | + |
| 207 | + // URL extraction functions have been moved to DataZoneClient |
| 208 | + |
| 209 | + static #instance: SmusAuthenticationProvider | undefined |
| 210 | + |
| 211 | + public static get instance(): SmusAuthenticationProvider | undefined { |
| 212 | + return SmusAuthenticationProvider.#instance |
| 213 | + } |
| 214 | + |
| 215 | + public static fromContext() { |
| 216 | + return (this.#instance ??= new this()) |
| 217 | + } |
| 218 | +} |
0 commit comments