Skip to content
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
1 change: 0 additions & 1 deletion config/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ const jestConfig = {
moduleNameMapper: {
"^@actions/core$": "<rootDir>/__mocks__/actions-core.ts",
"^@actions/tool-cache$": "<rootDir>/__mocks__/actions-tool-cache.ts",
"^@actions/exec$": "<rootDir>/__mocks__/actions-exec.ts",
"^@1password/sdk$": "<rootDir>/__mocks__/1password-sdk.ts",
},
transform: {
Expand Down
1 change: 0 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
5 changes: 0 additions & 5 deletions src/__mocks__/actions-exec.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
109 changes: 95 additions & 14 deletions src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -8,6 +7,7 @@ import {
loadSecrets,
unsetPrevious,
validateAuth,
getSecretReferenceEnvNames,
} from "./utils";
import {
authErr,
Expand Down Expand Up @@ -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 = "";

Expand Down Expand Up @@ -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";
Expand Down
22 changes: 15 additions & 7 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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;
}
Expand All @@ -110,7 +109,17 @@ export const extractSecret = (
}
};

export const loadSecrets = async (shouldExportEnv: boolean): Promise<void> => {
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({
Expand All @@ -119,16 +128,15 @@ export const loadSecrets = async (shouldExportEnv: boolean): Promise<void> => {
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);
}
Expand Down
Loading