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

ENG-2931 Fix error when no identity file is present #134

Merged
merged 1 commit into from
Oct 28, 2024
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
56 changes: 41 additions & 15 deletions src/commands/__tests__/login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jest.mock("../../drivers/auth", () => ({
jest.mock("../../drivers/config", () => ({
...jest.requireActual("../../drivers/config"),
saveConfig: jest.fn(),
getTenantConfig: jest.fn(() => bootstrapConfig),
loadConfig: jest.fn(() => bootstrapConfig),
}));
jest.mock("../../drivers/stdio");
jest.mock("../../plugins/login");
Expand Down Expand Up @@ -54,25 +54,26 @@ describe("login", () => {

describe("organization exists", () => {
let credentialData: string = "";
mockReadFile.mockImplementation(async () =>
Buffer.from(credentialData, "utf-8")
);
mockWriteFile.mockImplementation(async (_path, data) => {
credentialData = data;
});
mockSignInWithCredential.mockImplementation(
async (_auth, _firebaseCredential) =>
Promise.resolve({
user: {
email: "user@p0.dev",
},
})
);

beforeEach(() => {
credentialData = "";
jest.clearAllMocks();

mockReadFile.mockImplementation(async () =>
Buffer.from(credentialData, "utf-8")
);
mockWriteFile.mockImplementation(async (_path, data) => {
credentialData = data;
});
mockSignInWithCredential.mockImplementation(
async (_auth, _firebaseCredential) =>
Promise.resolve({
user: {
email: "user@p0.dev",
},
})
);
Comment on lines +68 to +75
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
mockSignInWithCredential.mockImplementation(
async (_auth, _firebaseCredential) =>
Promise.resolve({
user: {
email: "user@p0.dev",
},
})
);
mockSignInWithCredential.mockResolvedValue({
user: { email: "user@p0.dev", },
});


mockGetDoc({
slug: "test-org",
tenantId: "test-tenant",
Expand Down Expand Up @@ -105,4 +106,29 @@ Please contact support@p0.dev to enable this user."
`);
});
});

describe("identity file does not exist", () => {
beforeEach(() => {
jest.clearAllMocks();

// Mock `readFile` to throw an "ENOENT" error
mockReadFile.mockImplementation(() => {
const error = new Error("File not found");
(error as any).code = "ENOENT";
return Promise.reject(error);
});

mockGetDoc({
slug: "test-org",
tenantId: "test-tenant",
ssoProvider: "google",
});
});

it("it should ask user to log in", async () => {
await expect(login({ org: "test-org" })).rejects.toMatchInlineSnapshot(
`"Please run \`p0 login <organization>\` to use the P0 CLI."`
);
});
});
});
12 changes: 4 additions & 8 deletions src/drivers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ You should have received a copy of the GNU General Public License along with @p0
import { login } from "../commands/login";
import { Authn, Identity } from "../types/identity";
import { P0_PATH } from "../util";
import { loadConfig } from "./config";
import { authenticateToFirebase, initializeFirebase } from "./firestore";
import { authenticateToFirebase } from "./firestore";
import { print2 } from "./stdio";
import * as fs from "fs/promises";
import * as path from "path";
Expand Down Expand Up @@ -66,7 +65,7 @@ export const cached = async <T>(
}
};

export const loadCredentials = async (options?: {
const loadCredentialsWithAutoLogin = async (options?: {
noRefresh?: boolean;
}): Promise<Identity> => {
try {
Expand All @@ -78,7 +77,7 @@ export const loadCredentials = async (options?: {
) {
await login({ org: identity.org.slug }, { skipAuthenticate: true });
print2("\u200B"); // Force a new line
return loadCredentials({ noRefresh: true });
return loadCredentialsWithAutoLogin({ noRefresh: true });
}
return identity;
} catch (error: any) {
Expand All @@ -92,10 +91,7 @@ export const loadCredentials = async (options?: {
export const authenticate = async (options?: {
noRefresh?: boolean;
}): Promise<Authn> => {
await loadConfig();
initializeFirebase();

const identity = await loadCredentials(options);
const identity = await loadCredentialsWithAutoLogin(options);
const userCredential = await authenticateToFirebase(identity);

return { userCredential, identity };
Expand Down
3 changes: 2 additions & 1 deletion src/drivers/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ export async function saveConfig(config: Config) {
tenantConfig = config;
}

export async function loadConfig() {
export async function loadConfig(): Promise<Config> {
const buffer = await fs.readFile(CONFIG_FILE_PATH);
tenantConfig = JSON.parse(buffer.toString());
return tenantConfig;
}
13 changes: 9 additions & 4 deletions src/drivers/firestore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@ This file is part of @p0security/cli
You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
**/
import { Identity } from "../types/identity";
import { getTenantConfig } from "./config";
import { loadConfig } from "./config";
import { bootstrapConfig } from "./env";
import { FirebaseApp, initializeApp } from "firebase/app";
import {
getAuth,
OAuthProvider,
SignInMethod,
signInWithCredential,
UserCredential,
} from "firebase/auth";
import {
collection as fsCollection,
Expand All @@ -34,16 +35,20 @@ const bootstrapFirestore = getFirestore(bootstrapApp);
let app: FirebaseApp;
let firestore: Firestore;

export function initializeFirebase() {
const tenantConfig = getTenantConfig();
async function initializeFirebase() {
const tenantConfig = await loadConfig();
Copy link
Contributor

Choose a reason for hiding this comment

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

Is getTenantConfig used anymore?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, it's still in use.

app = initializeApp(tenantConfig.fs, "authFirebase");
firestore = getFirestore(app);
}

export async function authenticateToFirebase(identity: Identity) {
export async function authenticateToFirebase(
identity: Identity
): Promise<UserCredential> {
const { credential } = identity;
const tenantId = identity.org.tenantId;

await initializeFirebase();

// TODO: Move to map lookup
const provider = new OAuthProvider(
identity.org.ssoProvider === "google"
Expand Down
Loading