Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
validateServiceAccount,
addServiceAccount,
} from 'components/NamespaceAdmin/store/ActionCreator';
import { getGcloudCommand } from 'components/NamespaceAdmin/ServiceAccounts/gcloudCommand';

const PREFIX = 'features.ServiceAccounts';

Expand All @@ -48,29 +49,6 @@ const StyledTextField = styled(TextField)`
}
`;

/**
* Generates the gcloud cli command to add an IAM policy binding. If any of the
* parameters for the command is not provided when the command is generated, then
* the user should be able to provide them as environment variables in their shell.
*
* @param tenantProjectId string, defaults to "${TENANT_PROJECT_ID}" so it can be
* provided as the environment variable TENANT_PROJECT_ID when
* the command is run
* @param identity string, defaults to "${IDENTITY}" so that it can be provided as the
* environment variable IDENTITY when the command is run
* @param gsaEmail string, defaults to "${GSA_EMAIL}" so that it can be provided as the
* environment variable GSA_EMAIL when the command is run
* @return string, the gcloud cli command to run
*/
const getGcloudCommand = ({
k8sWorkloadIdentityPool = '${TENANT_PROJECT_ID}.svc.id.goog',
identity = '${IDENTITY}',
gsaEmail = '${GSA_EMAIL}',
gsaProjectId = '${GSA_PROJECT_ID}',
k8snamespace = 'default',
}): string =>
`gcloud iam service-accounts add-iam-policy-binding --role roles/iam.workloadIdentityUser --member "serviceAccount:${k8sWorkloadIdentityPool}[${k8snamespace}/${identity}]" ${gsaEmail} --project ${gsaProjectId}`;

export const EditConfirmDialog = ({
selectedServiceAcccount,
isShow,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright © 2026 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

import { execSync } from 'child_process';
import { getGcloudCommand, shellQuote } from 'components/NamespaceAdmin/ServiceAccounts/gcloudCommand';

describe('shellQuote', () => {
// Round-trips a set of values through a real shell (printf) to confirm the
// quoted form is both safe (no injected command runs) and lossless (the shell
// sees exactly the original string as data, not as executed syntax).
test('round-trips arbitrary values through a real shell unexecuted', () => {
const values = [
'x@x.iam.gserviceaccount.com; touch /tmp/should-not-exist; echo done',
'$(touch /tmp/should-not-exist)',
'`touch /tmp/should-not-exist`',
"a'; touch /tmp/should-not-exist; echo '",
'a && touch /tmp/should-not-exist',
'plain-safe-value',
];

for (const value of values) {
const quoted = shellQuote(value);
const out = execSync(`printf '%s' ${quoted}`).toString();
expect(out).toBe(value);
}
});
});

describe('getGcloudCommand', () => {
// Regression test: gsaEmail (sourced from the stored, server-side-unvalidated
// "serviceAccount" value) used to be interpolated into the generated command with
// no quoting at all, so a value containing shell metacharacters would execute as
// additional commands if an admin copy-pasted the generated string into a
// terminal, per the component's own "copy to clipboard" affordance.
test('a malicious gsaEmail cannot inject additional shell commands', () => {
const command = getGcloudCommand({
identity: 'my-namespace-identity',
gsaEmail: 'x@x.iam.gserviceaccount.com; touch /tmp/should-not-exist; echo pwned',
k8snamespace: 'default',
k8sWorkloadIdentityPool: 'example-project.svc.id.goog',
});

let threw = false;
try {
execSync(command, { stdio: 'pipe' });
} catch (e) {
// gcloud isn't installed in the test environment -- that's expected and fine,
// what matters is that nothing after it ran as a separate command.
threw = true;
}
expect(threw).toBe(true);

const fs = require('fs');
expect(fs.existsSync('/tmp/should-not-exist')).toBe(false);
});

test('unsupplied parameters keep their literal, shell-expandable placeholder form', () => {
const command = getGcloudCommand({});
expect(command).toContain('${TENANT_PROJECT_ID}');
expect(command).toContain('${IDENTITY}');
expect(command).toContain('${GSA_EMAIL}');
expect(command).toContain('${GSA_PROJECT_ID}');
});

test('supplied parameters are individually quoted in the --member value', () => {
const command = getGcloudCommand({
identity: 'my-identity',
k8snamespace: 'my-ns',
k8sWorkloadIdentityPool: 'my-pool',
});
expect(command).toContain("--member serviceAccount:'my-pool'['my-ns'/'my-identity']");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Update the test assertion to expect the escaped brackets (\[ and \]) to match the updated command generation logic.

Suggested change
expect(command).toContain("--member serviceAccount:'my-pool'['my-ns'/'my-identity']");
expect(command).toContain("--member serviceAccount:'my-pool'\\\\['my-ns'/'my-identity'\\\\]");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@herdiyana256 please update this

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in a70e917 — the assertion now expects the escaped brackets: --member serviceAccount:'my-pool'\['my-ns'/'my-identity']. Also added tests covering the bracket escaping, the discard-on-invalid-email behavior, and the isValidServiceAccountEmail validator.

});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright © 2026 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

/**
* Quotes a value for safe use as a single POSIX shell word, so it can't be
* interpreted as additional shell syntax (metacharacters, command substitution, a
* new command after a `;`/`&&`/`|`, etc.) no matter what it contains. The
* `serviceAccount` value this command is built from is stored server-side with no
* format validation on the create path, so it must be treated as untrusted here.
*/
export const shellQuote = (value: string): string => `'${String(value).replace(/'/g, `'\\''`)}'`;

interface IGcloudCommandParams {
k8sWorkloadIdentityPool?: string;
identity?: string;
gsaEmail?: string;
gsaProjectId?: string;
k8snamespace?: string;
}

/**
* Generates the gcloud cli command to add an IAM policy binding. If any of the
* parameters for the command is not provided when the command is generated, then
* the user should be able to provide them as environment variables in their shell.
*
* @param tenantProjectId string, defaults to "${TENANT_PROJECT_ID}" so it can be
* provided as the environment variable TENANT_PROJECT_ID when
* the command is run
* @param identity string, defaults to "${IDENTITY}" so that it can be provided as the
* environment variable IDENTITY when the command is run
* @param gsaEmail string, defaults to "${GSA_EMAIL}" so that it can be provided as the
* environment variable GSA_EMAIL when the command is run
* @return string, the gcloud cli command to run
*/
export const getGcloudCommand = ({
k8sWorkloadIdentityPool,
identity,
gsaEmail,
gsaProjectId,
k8snamespace,
}: IGcloudCommandParams): string => {
// Real values are quoted so they can never break out of their argument position.
// The "${...}" fallbacks are meant to stay as literal, unquoted shell syntax so the
// user's own shell substitutes them from an environment variable when they run the
// command, per this function's own doc comment above.
const pool = k8sWorkloadIdentityPool
? shellQuote(k8sWorkloadIdentityPool)
: '${TENANT_PROJECT_ID}.svc.id.goog';
const ns = shellQuote(k8snamespace || 'default');
const id = identity ? shellQuote(identity) : '${IDENTITY}';
const email = gsaEmail ? shellQuote(gsaEmail) : '${GSA_EMAIL}';
const projectId = gsaProjectId ? shellQuote(gsaProjectId) : '${GSA_PROJECT_ID}';

return `gcloud iam service-accounts add-iam-policy-binding --role roles/iam.workloadIdentityUser --member serviceAccount:${pool}[${ns}/${id}] ${email} --project ${projectId}`;
Comment thread
herdiyana256 marked this conversation as resolved.
Outdated
};
Loading