Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Porting account functionality for TS SDK #86

Merged
merged 2 commits into from
Mar 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,8 @@ sdk/python/pyproject.toml linguist-generated=false

sdk/typescript/**/* linguist-generated=true
sdk/typescript/esc/index.ts linguist-generated=false
sdk/typescript/esc/workspace.ts linguist-generated=false
sdk/typescript/esc/workspace_models.ts linguist-generated=false
sdk/typescript/test/**/* linguist-generated=false
sdk/typescript/* linguist-generated=false
sdk/test/**/* linguist-generated=false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this line isn't necessary since everything is false by default. the only reason we specify the others above as false is because of the wildcard for sdk/typescript

2 changes: 2 additions & 0 deletions CHANGELOG_PENDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
[#76](https://github.com/pulumi/esc-sdk/pull/76)
- Adds support for reading credentials from disk to Python SDK
[#81](https://github.com/pulumi/esc-sdk/pull/81)
- Adds support for reading credentials from disk to Typescript SDK
[#86](https://github.com/pulumi/esc-sdk/pull/86)

### Bug Fixes

Expand Down
6 changes: 3 additions & 3 deletions sdk/python/test/test_workspace_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,21 @@ def test_no_creds_at_all(self):
self.assertTrue('Authorization' not in self.config.api_key)

def test_just_pulumi_creds(self):
os.environ["PULUMI_HOME"] = os.getcwd() + "/test/test_pulumi_home"
os.environ["PULUMI_HOME"] = os.path.dirname(os.getcwd()) + "/test/test_pulumi_home"
self.client = esc.esc_client.default_client()
self.config = self.client.esc_api.api_client.configuration
self.assertEqual(self.config.host, "https://api.moolumi.com/api/esc")
self.assertEqual(self.config.api_key['Authorization'], "pul-fake-token-moo")

def test_pulumi_creds_with_esc(self):
os.environ["PULUMI_HOME"] = os.getcwd() + "/test/test_pulumi_home_esc"
os.environ["PULUMI_HOME"] = os.path.dirname(os.getcwd()) + "/test/test_pulumi_home_esc"
self.client = esc.esc_client.default_client()
self.config = self.client.esc_api.api_client.configuration
self.assertEqual(self.config.host, "https://api.boolumi.com/api/esc")
self.assertEqual(self.config.api_key['Authorization'], "pul-fake-token-boo")

def test_pulumi_creds_bad_format(self):
os.environ["PULUMI_HOME"] = os.getcwd() + "/test/test_pulumi_home_bad_format"
os.environ["PULUMI_HOME"] = os.path.dirname(os.getcwd()) + "/test/test_pulumi_home_bad_format"
self.client = esc.esc_client.default_client()
self.config = self.client.esc_api.api_client.configuration
self.assertEqual(self.config.host, "https://api.pulumi.com/api/esc")
Expand Down
8 changes: 8 additions & 0 deletions sdk/typescript/esc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from "./raw/index";
import * as yaml from "js-yaml";
import { AxiosError } from "axios";
import { getCurrentAccount } from "workspace";

export {
Configuration,
Expand Down Expand Up @@ -828,6 +829,13 @@ export function DefaultConfiguration(config?: Configuration): Configuration {
}
config.accessToken ??= process.env.PULUMI_ACCESS_TOKEN;
config.basePath ??= process.env.PULUMI_BACKEND_URL;

if (!config.accessToken || !config.basePath) {
const {account, backendUrl} = getCurrentAccount();
config.accessToken ??= account?.accessToken;
config.basePath ??= backendUrl;
}

return config;
}

Expand Down
88 changes: 88 additions & 0 deletions sdk/typescript/esc/workspace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright 2025, Pulumi Corporation. All rights reserved.

import path from "path";
import fs from "fs";
import { Account, Credentials, EscCredentials } from "workspace_models";

/*
Pulumi workspace and account logic for python SDK.
This is a partial port of ESC and Pulumi CLI code found in
https://github.com/pulumi/esc/tree/main/cmd/esc/cli/workspace
*/

// Returns the path of the ".pulumi" folder where Pulumi puts its artifacts.
export function getPulumiHomeDir(): string {
// Allow the folder we use to be overridden by an environment variable
const dirEnv = process.env.PULUMI_HOME;
if (dirEnv) {
return dirEnv;
}

// Otherwise, use the current user's home dir + .pulumi
const homeDir = process.env.HOME || process.env.USERPROFILE || process.env.HOMEPATH;
if (!homeDir) {
throw new Error('Unable to determine home directory.');
}

return path.join(homeDir, '.pulumi');
}

// Returns the path of the ".esc" folder inside Pulumi home dir.
export function getEscBookkeepingDir(): string {
const homeDir = getPulumiHomeDir();
return path.join(homeDir, '.esc');
}

// Returns the path to the esc credentials file on disk.
export function getPathToCredsFile(dir: string): string {
return path.join(dir, 'credentials.json');
}

// Returns the current account name from the ESC credentials file.
export function getEscCurrentAccountName(): string | null {
try {
const credsFile = getPathToCredsFile(getEscBookkeepingDir());
if (!fs.existsSync(credsFile)) {
return null
}
const parsedData = JSON.parse(fs.readFileSync(credsFile, 'utf-8'));
return (parsedData as EscCredentials)?.name;
} catch (error) {
console.error(`An unexpected error occurred: ${error}`);
return null;
}
}

// Reads and parses credentials from the Pulumi credentials file.
export function getStoredCredentials(): Credentials | null {
try {
const credsFile = getPathToCredsFile(getPulumiHomeDir());
if (!fs.existsSync(credsFile)) {
return null
}
const parsedData = JSON.parse(fs.readFileSync(credsFile, 'utf8'));
return parsedData as Credentials
} catch (error) {
console.error(`An unexpected error occurred: ${error}`);
return null;
}
}

// Gets current account values from credentials file.
export function getCurrentAccount(): {account?: Account, backendUrl?: string } {
let backendUrl = getEscCurrentAccountName();
const pulumiCredentials = getStoredCredentials();
if (!pulumiCredentials) {
return {};
}
if (!backendUrl) {
backendUrl = pulumiCredentials.current;
}
if (!backendUrl || !(backendUrl in pulumiCredentials.accounts)) {
return {};
}
return {
account: pulumiCredentials.accounts[backendUrl],
backendUrl,
};
}
23 changes: 23 additions & 0 deletions sdk/typescript/esc/workspace_models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright 2025, Pulumi Corporation. All rights reserved.

/*
Models for Pulumi workspace and account logic for python SDK.
This is a partial port of ESC and Pulumi CLI code found in
https://github.com/pulumi/esc/tree/main/cmd/esc/cli/workspace
*/

export interface Account {
accessToken: string;
username: string;
organizations: string;
}

export interface Credentials {
current: string;
accessTokens: { [key: string]: string };
accounts: { [key: string]: Account };
}

export interface EscCredentials {
name: string;
}
55 changes: 55 additions & 0 deletions sdk/typescript/test/workspace.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2025, Pulumi Corporation.

import assert from "assert";
import { DefaultClient } from "index";
import { after, before, describe, it } from "node:test";
import path from "path";

describe("ESC", async () => {
let tokenBefore: string | undefined
let backendBefore: string | undefined
let homeBefore: string | undefined

before(async () => {
tokenBefore = process.env.PULUMI_ACCESS_TOKEN;
backendBefore = process.env.PULUMI_BACKEND_URL;
homeBefore = process.env.PULUMI_HOME;
delete process.env.PULUMI_ACCESS_TOKEN;
delete process.env.PULUMI_BACKEND_URL;
});

after(async () => {
process.env.PULUMI_ACCESS_TOKEN = tokenBefore;
process.env.PULUMI_BACKEND_URL = backendBefore;
process.env.PULUMI_HOME = homeBefore;
});

it("test no creds at all", async () => {
process.env.PULUMI_HOME = "/not_real_dir";
let client = DefaultClient();
assert.equal(client.config.basePath, undefined);
assert.equal(client.config.accessToken, undefined);
});

it("test just pulumi creds", async () => {
process.env.PULUMI_HOME = path.dirname(process.cwd()) + "/test/test_pulumi_home";
let client = DefaultClient();
assert.equal(client.config.basePath, "https://api.moolumi.com/api/esc");
assert.equal(client.config.accessToken, "pul-fake-token-moo");
});

it("test pulumi creds with esc", async () => {
process.env.PULUMI_HOME = path.dirname(process.cwd()) + "/test/test_pulumi_home_esc";
let client = DefaultClient();
assert.equal(client.config.basePath, "https://api.boolumi.com/api/esc");
assert.equal(client.config.accessToken, "pul-fake-token-boo");
});

it("test pulumi creds bad format", async () => {
process.env.PULUMI_HOME = path.dirname(process.cwd()) + "/test/test_pulumi_home_bad_format";
let client = DefaultClient();
assert.equal(client.config.basePath, undefined);
assert.equal(client.config.accessToken, undefined);
});

});
2 changes: 1 addition & 1 deletion sdk/typescript/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
"baseUrl": "./esc"
},
"lib": ["es2017"],
"include": ["src/**/*", "test/**/*"],
"include": ["src/**/*", "test/**/*", "esc/**/*"],
}
Loading