diff --git a/config/jest.config.js b/config/jest.config.js index 9a586e2..a8ab82d 100644 --- a/config/jest.config.js +++ b/config/jest.config.js @@ -13,7 +13,6 @@ const jestConfig = { moduleNameMapper: { "^@actions/core$": "/__mocks__/actions-core.ts", "^@actions/tool-cache$": "/__mocks__/actions-tool-cache.ts", - "^@actions/exec$": "/__mocks__/actions-exec.ts", "^@1password/sdk$": "/__mocks__/1password-sdk.ts", }, transform: { diff --git a/package-lock.json b/package-lock.json index 50b37b9..cfe06ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,6 @@ "@1password/op-js": "^0.1.11", "@1password/sdk": "0.5.0", "@actions/core": "^3.0.0", - "@actions/exec": "^3.0.0", "@actions/tool-cache": "^4.0.0", "dotenv": "^17.2.2", "semver": "^7.8.5" diff --git a/package.json b/package.json index e4413f7..030caff 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,6 @@ "@1password/sdk": "0.5.0", "@1password/op-js": "^0.1.11", "@actions/core": "^3.0.0", - "@actions/exec": "^3.0.0", "@actions/tool-cache": "^4.0.0", "dotenv": "^17.2.2", "semver": "^7.8.5" diff --git a/src/__mocks__/actions-exec.ts b/src/__mocks__/actions-exec.ts deleted file mode 100644 index 517e543..0000000 --- a/src/__mocks__/actions-exec.ts +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - getExecOutput: jest.fn(() => ({ - stdout: "MOCK_SECRET", - })), -}; diff --git a/src/index.ts b/src/index.ts index bd64646..90d09af 100644 --- a/src/index.ts +++ b/src/index.ts @@ -57,7 +57,7 @@ const loadSecretsAction = async () => { await installCLI(); // Load secrets - await loadSecrets(shouldExportEnv); + loadSecrets(shouldExportEnv); } } catch (error) { // It's possible for the Error constructor to be modified to be anything diff --git a/src/utils.test.ts b/src/utils.test.ts index 0f6b5ef..b48b66d 100644 --- a/src/utils.test.ts +++ b/src/utils.test.ts @@ -1,5 +1,4 @@ import * as core from "@actions/core"; -import * as exec from "@actions/exec"; import { read, setClientInfo } from "@1password/op-js"; import { extractSecret, @@ -8,6 +7,7 @@ import { loadSecrets, unsetPrevious, validateAuth, + getSecretReferenceEnvNames, } from "./utils"; import { authErr, @@ -196,6 +196,16 @@ describe("extractSecret", () => { expect(core.setSecret).toHaveBeenCalledWith(testSecretValue); }); + it("should trim whitespace from the reference before reading it", () => { + process.env[envTestSecretEnv] = ` ${testSecretRef}\n`; + + extractSecret(envTestSecretEnv, false); + + expect(read.parse).toHaveBeenCalledWith(testSecretRef); + + process.env[envTestSecretEnv] = testSecretRef; + }); + describe("when secret value is empty string", () => { const emptySecretValue = ""; @@ -233,43 +243,114 @@ describe("extractSecret", () => { }); describe("loadSecrets", () => { - it("sets the client info and gets the executed output", async () => { - await loadSecrets(true); + const originalEnv = process.env; + const testSecretRef = "op://vault/item/field"; + const testSecretValue = "Secret1@3$"; + + beforeEach(() => { + // eslint-disable-next-line @typescript-eslint/naming-convention + process.env = { MOCK_SECRET: testSecretRef }; + read.parse = jest.fn().mockReturnValue(testSecretValue); + }); + + afterEach(() => { + process.env = originalEnv; + }); + + it("sets the client info and resolves secret references", () => { + loadSecrets(true); expect(setClientInfo).toHaveBeenCalledWith({ name: "1Password GitHub Action", id: "GHA", }); - expect(exec.getExecOutput).toHaveBeenCalledWith('sh -c "op env ls"'); + expect(read.parse).toHaveBeenCalledWith(testSecretRef); expect(core.exportVariable).toHaveBeenCalledWith( - "OP_MANAGED_VARIABLES", + envManagedVariables, "MOCK_SECRET", ); }); - it("return early if no env vars with secrets found", async () => { - (exec.getExecOutput as jest.Mock).mockReturnValueOnce({ stdout: "" }); - await loadSecrets(true); + it("returns early if no env vars contain secret references", () => { + // eslint-disable-next-line @typescript-eslint/naming-convention + process.env = { PATH: "/usr/bin" }; - expect(exec.getExecOutput).toHaveBeenCalledWith('sh -c "op env ls"'); + loadSecrets(true); + + expect(read.parse).not.toHaveBeenCalled(); expect(core.exportVariable).not.toHaveBeenCalled(); }); + it("throws when a secret reference cannot be read", () => { + (read.parse as jest.Mock).mockImplementation(() => { + throw new Error("item not found"); + }); + + expect(() => loadSecrets(true)).toThrow("item not found"); + }); + describe("core.exportVariable", () => { - it("is called when shouldExportEnv is true", async () => { - await loadSecrets(true); + it("is called when shouldExportEnv is true", () => { + loadSecrets(true); - expect(core.exportVariable).toHaveBeenCalledTimes(1); + expect(core.exportVariable).toHaveBeenCalledWith( + "MOCK_SECRET", + testSecretValue, + ); + expect(core.exportVariable).toHaveBeenCalledTimes(2); }); - it("is not called when shouldExportEnv is false", async () => { - await loadSecrets(false); + it("is not called when shouldExportEnv is false", () => { + loadSecrets(false); + expect(core.setOutput).toHaveBeenCalledWith( + "MOCK_SECRET", + testSecretValue, + ); expect(core.exportVariable).not.toHaveBeenCalled(); }); }); }); +describe("getSecretReferenceEnvNames", () => { + it.each([ + // Valid references + ["op://vault/item/field", true], + ["op://vault/item/section/field", true], + ["op://vault/item//field", true], + ["op://my-vault/my_item/field.name", true], + ["op://my vault/my item/private key", true], + ["op://vault/item/field?attribute=otp", true], + ["op://vault/item/section/field?ssh-format=openssh", true], + [" op://vault/item/field ", true], + // Characters outside the secret reference syntax + ["op://My Vault/item (old)/pw", false], + ["op://vault/item@x/field", false], + ["op://vault/item/field#1", false], + ["op://vault/it\tem/field", false], + ["op://Café/item/field", false], + // Malformed structure + ["", false], + ["not-a-reference", false], + ["OP://vault/item/field", false], + ["prefix op://vault/item/field", false], + ["op://", false], + ["op://vault/item", false], + ["op://vault//field", false], + ["op://vault/item/section/field/extra", false], + ["op://vault/item/field\nmore", false], + // Malformed query + ["op://vault/item/field?", false], + ["op://vault/item/field?attribute", false], + ["op://vault/item/field?attribute=otp&ssh-format=openssh", false], + ])("%j is a secret reference: %s", (value, expected) => { + // eslint-disable-next-line @typescript-eslint/naming-convention + expect(getSecretReferenceEnvNames({ TEST: value })).toEqual( + expected ? ["TEST"] : [], + ); + }); +}); + describe("unsetPrevious", () => { const testManagedEnv = "TEST_SECRET"; const testSecretValue = "MyS3cr#T"; diff --git a/src/utils.ts b/src/utils.ts index 7aeee34..7c76c14 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,4 @@ import * as core from "@actions/core"; -import * as exec from "@actions/exec"; import { read, setClientInfo, semverToInt } from "@1password/op-js"; import { version } from "../package.json"; import { @@ -88,7 +87,7 @@ export const extractSecret = ( ): void => { core.info(`Populating variable: ${envName}`); - const ref = process.env[envName]; + const ref = process.env[envName]?.trim(); if (!ref) { return; } @@ -110,7 +109,17 @@ export const extractSecret = ( } }; -export const loadSecrets = async (shouldExportEnv: boolean): Promise => { +const secretReferencePattern = + /^op:\/\/[\w .-]+\/[\w .-]+(?:\/[\w .-]*)?\/[\w .-]+(?:\?[\w .-]*=[\w .-]*)?$/; + +export const getSecretReferenceEnvNames = ( + env: NodeJS.ProcessEnv = process.env, +): string[] => + Object.entries(env) + .filter(([, value]) => value && secretReferencePattern.test(value.trim())) + .map(([name]) => name); + +export const loadSecrets = (shouldExportEnv: boolean): void => { // Strip any prerelease suffix; semverToInt only accepts MAJOR.MINOR.PATCH. const [releaseVersion] = version.split("-"); setClientInfo({ @@ -119,16 +128,15 @@ export const loadSecrets = async (shouldExportEnv: boolean): Promise => { build: semverToInt(releaseVersion ?? version), }); - // Load secrets from environment variables using 1Password CLI. + // Load secrets from environment variables using process.env. // Iterate over them to find 1Password references, extract the secret values, // and make them available in the next steps either as step outputs or as environment variables. - const res = await exec.getExecOutput(`sh -c "op env ls"`); + const envs = getSecretReferenceEnvNames(); - if (res.stdout === "") { + if (envs.length === 0) { return; } - const envs = res.stdout.replace(/\n+$/g, "").split(/\r?\n/); for (const envName of envs) { extractSecret(envName, shouldExportEnv); }