1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import Basics
import Commands
import CoreCommands
import Foundation
import PackageModel
import PackageRegistry
import struct TSCBasic.SHA256
#if os(Windows)
import WinSDK
private func readpassword(_ prompt: String) throws -> String {
enum StaticStorage {
static var buffer: UnsafeMutableBufferPointer<CChar> =
.allocate(capacity: PackageRegistryCommand.Login.passwordBufferSize)
}
let hStdIn: HANDLE = GetStdHandle(STD_INPUT_HANDLE)
if hStdIn == INVALID_HANDLE_VALUE {
throw StringError("unable to read input: GetStdHandle returns INVALID_HANDLE_VALUE")
}
var dwMode: DWORD = 0
guard GetConsoleMode(hStdIn, &dwMode) else {
throw StringError("unable to read input: GetConsoleMode failed")
}
print(prompt, terminator: "")
guard SetConsoleMode(hStdIn, DWORD(ENABLE_LINE_INPUT)) else {
throw StringError("unable to read input: SetConsoleMode failed")
}
defer { SetConsoleMode(hStdIn, dwMode) }
var dwNumberOfCharsRead: DWORD = 0
_ = ReadConsoleA(
hStdIn,
StaticStorage.buffer.baseAddress,
DWORD(StaticStorage.buffer.count),
&dwNumberOfCharsRead,
nil
)
let password = String(cString: UnsafePointer<CChar>(StaticStorage.buffer.baseAddress!))
guard password.count <= PackageRegistryCommand.Login.maxPasswordLength else {
throw PackageRegistryCommand.ValidationError
.credentialLengthLimitExceeded(PackageRegistryCommand.Login.maxPasswordLength)
}
return password
}
#else
private func readpassword(_ prompt: String) throws -> String {
let password: String
#if canImport(Darwin)
var buffer = [CChar](repeating: 0, count: PackageRegistryCommand.Login.passwordBufferSize)
password = try withExtendedLifetime(buffer) {
guard let passwordPtr = readpassphrase(prompt, &buffer, buffer.count, 0) else {
throw StringError("unable to read input")
}
return String(cString: passwordPtr)
}
#else
// GNU C implementation of getpass has no limit on the password length
// (https://man7.org/linux/man-pages/man3/getpass.3.html)
password = String(cString: getpass(prompt))
#endif
guard password.count <= PackageRegistryCommand.Login.maxPasswordLength else {
throw PackageRegistryCommand.ValidationError
.credentialLengthLimitExceeded(PackageRegistryCommand.Login.maxPasswordLength)
}
return password
}
#endif
extension PackageRegistryCommand {
struct Login: AsyncSwiftCommand {
static func loginURL(from registryURL: URL, loginAPIPath: String?) throws -> URL {
// Login URL must be HTTPS
var loginURLComponents = URLComponents(url: registryURL, resolvingAgainstBaseURL: true)
loginURLComponents?.scheme = "https"
loginURLComponents?.path = loginAPIPath ?? "/login"
guard let loginURL = loginURLComponents?.url else {
throw ValidationError.invalidURL(registryURL)
}
return loginURL
}
static let configuration = CommandConfiguration(
abstract: "Log in to a registry"
)
static let maxPasswordLength = 512
// Define a larger buffer size so we read more than allowed, and
// this way we can tell if the entered password is over the length
// limit. One space is for \0, another is for the "overflowing" char.
static let passwordBufferSize = Self.maxPasswordLength + 2
@OptionGroup(visibility: .hidden)
var globalOptions: GlobalOptions
@Argument(help: "The registry URL")
var url: URL?
var registryURL: URL? {
self.url
}
@Option(help: "Username")
var username: String?
@Option(help: "Password")
var password: String?
@Option(help: "Access token")
var token: String?
@Option(
name: .customLong("token-file"),
help: "Path to the file containing access token"
)
var tokenFilePath: AbsolutePath?
@Flag(help: "Allow writing to netrc file without confirmation")
var noConfirm: Bool = false
private static let PLACEHOLDER_TOKEN_USER = "token"
func run(_ swiftCommandState: SwiftCommandState) async throws {
// We need to be able to read/write credentials
// Make sure credentials store is available before proceeding
let authorizationProvider: AuthorizationProvider?
do {
authorizationProvider = try swiftCommandState.getRegistryAuthorizationProvider()
} catch {
throw ValidationError.invalidCredentialStore(error)
}
guard let authorizationProvider else {
throw ValidationError.unknownCredentialStore
}
// Auth config is in user-level registries config only
let configuration = try getRegistriesConfig(swiftCommandState, global: true)
// compute and validate registry URL
guard let registryURL = self.registryURL ?? configuration.configuration.defaultRegistry?.url else {
throw ValidationError.unknownRegistry
}
try registryURL.validateRegistryURL()
let authenticationType: RegistryConfiguration.AuthenticationType
let storeUsername: String
let storePassword: String
var saveChanges = true
if let username {
authenticationType = .basic
storeUsername = username
if let password {
// User provided password
storePassword = password
} else if let stored = authorizationProvider.authentication(for: registryURL),
stored.user == storeUsername
{
// Password found in credential store
storePassword = stored.password
saveChanges = false
} else {
// Prompt user for password
storePassword = try readpassword("Enter password for '\(storeUsername)': ")
}
} else {
authenticationType = .token
// All token auth accounts have the same placeholder value
storeUsername = Self.PLACEHOLDER_TOKEN_USER
if let token {
// User provided token
storePassword = token
} else if let tokenFilePath {
print("Reading access token from \(tokenFilePath).")
storePassword = try localFileSystem.readFileContents(tokenFilePath)
.trimmingCharacters(in: .whitespacesAndNewlines)
} else if let stored = authorizationProvider.authentication(for: registryURL),
stored.user == storeUsername
{
// Token found in credential store
storePassword = stored.password
saveChanges = false
} else {
// Prompt user for token
storePassword = try readpassword("Enter access token: ")
}
}
let authorizationWriter = authorizationProvider as? AuthorizationWriter
if saveChanges, authorizationWriter == nil {
throw StringError("Credential store must be writable")
}
// Save in cache so we can try the credentials and persist to storage only if login succeeds
try await authorizationWriter?.addOrUpdate(
for: registryURL,
user: storeUsername,
password: storePassword,
persist: false
)
// `url` can either be base URL of the registry, in which case the login API
// is assumed to be at /login, or the full URL of the login API.
var loginAPIPath: String?
if !registryURL.path.isEmpty, registryURL.path != "/" {
loginAPIPath = registryURL.path
}
let loginURL = try Self.loginURL(from: registryURL, loginAPIPath: loginAPIPath)
// Build a RegistryConfiguration with the given authentication settings
var registryConfiguration = configuration.configuration
try registryConfiguration.add(authentication: .init(type: authenticationType, loginAPIPath: loginAPIPath), for: registryURL)
// Build a RegistryClient to test login credentials (fingerprints don't matter in this case)
let registryClient = RegistryClient(
configuration: registryConfiguration,
fingerprintStorage: .none,
fingerprintCheckingMode: .strict,
skipSignatureValidation: false,
signingEntityStorage: .none,
signingEntityCheckingMode: .strict,
authorizationProvider: authorizationProvider,
delegate: .none,
checksumAlgorithm: SHA256()
)
// Try logging in
try await registryClient.login(
loginURL: loginURL,
timeout: .seconds(5),
observabilityScope: swiftCommandState.observabilityScope,
callbackQueue: .sharedConcurrent
)
print("Login successful.")
// Login successful. Persist credentials to storage.
let osStore = !(authorizationWriter is NetrcAuthorizationProvider)
// Prompt if writing to netrc file and --no-confirm is not set
if saveChanges, !osStore, !self.noConfirm {
if self.globalOptions.security.forceNetrc {
print("""
WARNING: You choose to use netrc file instead of the operating system's secure credential store.
Your credentials will be written out to netrc file.
""")
} else {
print("""
WARNING: Secure credential store is not supported on this platform.
Your credentials will be written out to netrc file.
""")
}
print("Continue? (Yes/No): ")
guard readLine(strippingNewline: true)?.lowercased() == "yes" else {
print("Credentials not saved. Exiting...")
return
}
}
if saveChanges {
try await authorizationWriter?.addOrUpdate(
for: registryURL,
user: storeUsername,
password: storePassword,
persist: true
)
if osStore {
print("\nCredentials have been saved to the operating system's secure credential store.")
} else {
print("\nCredentials have been saved to netrc file.")
}
}
// Update user-level registry configuration file
let update: (inout RegistryConfiguration) throws -> Void = { configuration in
try configuration.add(authentication: .init(type: authenticationType, loginAPIPath: loginAPIPath), for: registryURL)
}
try configuration.updateShared(with: update)
print("Registry configuration updated.")
}
}
struct Logout: AsyncSwiftCommand {
static let configuration = CommandConfiguration(
abstract: "Log out from a registry"
)
@OptionGroup(visibility: .hidden)
var globalOptions: GlobalOptions
@Argument(help: "The registry URL")
var url: URL?
var registryURL: URL? {
self.url
}
func run(_ swiftCommandState: SwiftCommandState) async throws {
// Auth config is in user-level registries config only
let configuration = try getRegistriesConfig(swiftCommandState, global: true)
// compute and validate registry URL
guard let registryURL = self.registryURL ?? configuration.configuration.defaultRegistry?.url else {
throw ValidationError.unknownRegistry
}
try registryURL.validateRegistryURL()
// We need to be able to read/write credentials
guard let authorizationProvider = try swiftCommandState.getRegistryAuthorizationProvider() else {
throw ValidationError.unknownCredentialStore
}
let authorizationWriter = authorizationProvider as? AuthorizationWriter
let osStore = !(authorizationWriter is NetrcAuthorizationProvider)
// Only OS credential store supports deletion
if osStore {
try await authorizationWriter?.remove(for: registryURL)
print("Credentials have been removed from operating system's secure credential store.")
} else {
print("netrc file not updated. Please remove credentials from the file manually.")
}
// Update user-level registry configuration file
let update: (inout RegistryConfiguration) throws -> Void = { configuration in
configuration.removeAuthentication(for: registryURL)
}
try configuration.updateShared(with: update)
print("Registry configuration updated.")
print("Logout successful.")
}
}
}
|