Skip to content

Commit

Permalink
Merge branch 'v3' into PMM-13608-dismiss-modal
Browse files Browse the repository at this point in the history
  • Loading branch information
doracretu3pillar authored Jan 14, 2025
2 parents ec965fa + 4708bc8 commit c520407
Show file tree
Hide file tree
Showing 23 changed files with 332 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ func (m *PerconaForwarderHTTPClientMiddleware) applyHeaders(ctx context.Context,
return httpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
reqCtx := contexthandler.FromContext(ctx)

xProxyFilter := reqCtx.Req.Header.Get("X-Proxy-Filter")
if xProxyFilter != "" {
req.Header.Set("X-Proxy-Filter", xProxyFilter)
if reqCtx != nil && reqCtx.Req != nil && reqCtx.Req.Header != nil {
xProxyFilter := reqCtx.Req.Header.Get("X-Proxy-Filter")
if xProxyFilter != "" {
req.Header.Set("X-Proxy-Filter", xProxyFilter)
}
}

return next.RoundTrip(req)
Expand Down
9 changes: 5 additions & 4 deletions pkg/services/serviceaccounts/database/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util/nameutil"
)

type ServiceAccountsStoreImpl struct {
Expand Down Expand Up @@ -58,8 +59,8 @@ func generateLogin(prefix string, orgId int64, name string) string {

// CreateServiceAccount creates service account
func (s *ServiceAccountsStoreImpl) CreateServiceAccount(ctx context.Context, orgId int64, saForm *serviceaccounts.CreateServiceAccountForm) (*serviceaccounts.ServiceAccountDTO, error) {
name := saForm.Name
login := generateLogin(serviceaccounts.ServiceAccountPrefix, orgId, saForm.Name)
name := nameutil.SanitizeSAName(saForm.Name)
login := nameutil.SanitizeSAName(generateLogin(serviceaccounts.ServiceAccountPrefix, orgId, saForm.Name))
isDisabled := false
role := org.RoleViewer
if saForm.IsDisabled != nil {
Expand Down Expand Up @@ -481,8 +482,8 @@ func (s *ServiceAccountsStoreImpl) MigrateApiKey(ctx context.Context, orgId int6
func (s *ServiceAccountsStoreImpl) CreateServiceAccountFromApikey(ctx context.Context, key *apikey.APIKey) error {
prefix := "sa-autogen"
cmd := user.CreateUserCommand{
Login: generateLogin(prefix, key.OrgID, key.Name),
Name: fmt.Sprintf("%v-%v", prefix, key.Name),
Login: nameutil.SanitizeSAName(generateLogin(prefix, key.OrgID, key.Name)),
Name: nameutil.SanitizeSAName(fmt.Sprintf("%v-%v", prefix, key.Name)),
OrgID: key.OrgID,
DefaultOrgRole: string(key.Role),
IsServiceAccount: true,
Expand Down
3 changes: 2 additions & 1 deletion pkg/services/serviceaccounts/database/token_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/grafana/grafana/pkg/services/apikey"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/serviceaccounts"
"github.com/grafana/grafana/pkg/util/nameutil"
)

const maxRetrievedTokens = 300
Expand Down Expand Up @@ -50,7 +51,7 @@ func (s *ServiceAccountsStoreImpl) AddServiceAccountToken(ctx context.Context, s
}

addKeyCmd := &apikey.AddCommand{
Name: cmd.Name,
Name: nameutil.SanitizeSAName(cmd.Name),
Role: org.RoleViewer,
OrgID: cmd.OrgId,
Key: cmd.Key,
Expand Down
23 changes: 23 additions & 0 deletions pkg/util/nameutil/serviceaccount.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package nameutil

import (
"crypto/md5"
"fmt"
)

// SanitizeSAName is used for sanitize name and it's length for service accounts.
// Max length of service account name is 190 chars (limit in Grafana Postgres DB).
// However, prefix added by grafana is counted too. Prefix is sa-{orgID}-.
// Bare minimum is 5 chars reserved (orgID is <10, like sa-1-) and could be more depends
// on orgID number. Let's reserve 10 chars. It will cover almost one million orgIDs.
// Sanitizing, ensure its length by hashing postfix when length is exceeded.
// MD5 is used because it has fixed length 32 chars.
//
// Be aware that the same method is implemented in the PMM repo, and all changes should be reflected there as well!
func SanitizeSAName(name string) string {
if len(name) <= 180 {
return name
}

return fmt.Sprintf("%s%x", name[:148], md5.Sum([]byte(name[148:]))) //nolint:gosec
}
32 changes: 32 additions & 0 deletions pkg/util/nameutil/serviceaccount_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package nameutil

import (
"crypto/rand"
"encoding/base64"
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func TestSanitizeSAName(t *testing.T) {
// max possible length without hashing
len180, err := generateRandomString(180)
require.NoError(t, err)
require.Equal(t, len180, SanitizeSAName(len180))

// too long length - postfix hashed
len200, err := generateRandomString(200)
require.NoError(t, err)
len200sanitized := SanitizeSAName(len200)
require.Equal(t, fmt.Sprintf("%s%s", len200[:148], len200sanitized[148:]), len200sanitized)
}

func generateRandomString(length int) (string, error) {
buffer := make([]byte, length)
_, err := rand.Read(buffer)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(buffer)[:length], nil
}
18 changes: 15 additions & 3 deletions public/app/core/components/Login/LoginCtrl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,27 @@ export class LoginCtrl extends PureComponent<Props, State> {
};

toGrafana = () => {
// @PERCONA
// trigger apikey migration on login
const constructUrl = (url: string) => {
const forceApiKeyMigration = 'force-apikey-migration=true';

if (url.includes('?')) {
return url + '&' + forceApiKeyMigration;
} else {
return url + '?' + forceApiKeyMigration;
}
};

// Use window.location.href to force page reload
if (this.result?.redirectUrl) {
if (config.appSubUrl !== '' && !this.result.redirectUrl.startsWith(config.appSubUrl)) {
window.location.assign(config.appSubUrl + this.result.redirectUrl);
window.location.assign(constructUrl(config.appSubUrl + this.result.redirectUrl));
} else {
window.location.assign(this.result.redirectUrl);
window.location.assign(constructUrl(this.result.redirectUrl));
}
} else {
window.location.assign(config.appSubUrl + '/');
window.location.assign(constructUrl(config.appSubUrl + '/'));
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useAppDispatch } from 'app/store/store';
import { useSelector } from 'app/types';

import { Telemetry } from '../../../ui-events/components/Telemetry';
import { useMigrator } from '../../core/hooks/migrator';
import usePerconaTour from '../../core/hooks/tour';
import { checkUpdatesAction } from '../../core/reducers/updates';
import { logger } from '../../helpers/logger';
Expand All @@ -27,6 +28,7 @@ import { isPmmAdmin } from '../../helpers/permissions';
import { Messages } from './PerconaBootstrapper.messages';
import { getStyles } from './PerconaBootstrapper.styles';
import { PerconaBootstrapperProps } from './PerconaBootstrapper.types';
import PerconaMigrator from './PerconaMigrator';
import PerconaNavigation from './PerconaNavigation/PerconaNavigation';
import PerconaTourBootstrapper from './PerconaTour';
import PerconaUpdateVersion from './PerconaUpdateVersion/PerconaUpdateVersion';
Expand All @@ -42,6 +44,7 @@ export const PerconaBootstrapper = ({ onReady }: PerconaBootstrapperProps) => {
const { user } = config.bootData;
const { isSignedIn } = user;
const theme = useTheme2();
const { migrationSummaryVisible } = useMigrator();

const dismissModal = () => {
setModalIsOpen(false);
Expand Down Expand Up @@ -114,7 +117,9 @@ export const PerconaBootstrapper = ({ onReady }: PerconaBootstrapperProps) => {
{isSignedIn && <Telemetry />}
<PerconaNavigation />
<PerconaTourBootstrapper />
{updateAvailable && showUpdateModal && !isLoadingUpdates ? (
{isSignedIn && isPmmAdmin(user) && migrationSummaryVisible ? (
<PerconaMigrator />
) : updateAvailable && showUpdateModal && !isLoadingUpdates ? (
<PerconaUpdateVersion />
) : (
isSignedIn &&
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React, { FC } from 'react';

import { useMigrator } from 'app/percona/shared/core/hooks/migrator';
import { useSelector } from 'app/types';

import MigrationSummary from './components/MigrationSummary';

const PerconaMigrator: FC = () => {
const migrationResult = useSelector((state) => state.apiKeys.migrationResult);
const { migrationSummaryVisible, dismissSummary } = useMigrator();

if (!migrationResult || !migrationSummaryVisible) {
return;
}

return <MigrationSummary data={migrationResult} visible={migrationSummaryVisible} onDismiss={dismissSummary} />;
};

export default PerconaMigrator;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const Messages = {
id: (id: number) => `API Key ID ${id}`,
name: 'Name: ',
error: 'Error: ',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React, { FC } from 'react';

import { Text } from '@grafana/ui';

import { Messages } from './FailedMigrationRow.messages';
import { FailedMigrationRowProps } from './FailedMigrationRow.types';
import { parseDetail } from './FailedMigrationRow.utils';

const FailedMigrationRow: FC<FailedMigrationRowProps> = ({ id, details }) => {
const { name, error } = parseDetail(details);

return (
<li>
<strong>{Messages.id(id)}</strong>
<ul>
{!!name && (
<li>
<Text>
<strong>{Messages.name}</strong>
{name}
</Text>
</li>
)}
<li>
<Text>
<strong>{Messages.error}</strong>
{error}
</Text>
</li>
</ul>
</li>
);
};

export default FailedMigrationRow;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface FailedMigrationRowProps {
id: number;
details: string;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { capitalizeText } from 'app/percona/shared/helpers/capitalizeText';

export const parseDetail = (detail: string) => {
if (!detail.includes('- Error: ')) {
return {
name: '',
error: detail,
};
}

const [name, error] = detail.split('- Error: ');

return {
name: name.replace('API key name: ', ''),
error: capitalizeText(error),
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// todo: use a shortened link
export const SERVICE_ACCOUNTS_DOCS_LINK =
'https://docs.percona.com/percona-monitoring-and-management/3/api/authentication.html?h=service+accounts';

// todo: use a shortened link
export const CONTACT_SUPPORT_LINK = 'https://www.percona.com/about/contact';
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const Messages = {
title: 'API migration status',
description:
'Migration of API keys complete. The following keys could not be converted to service accounts but remain fully functional:',
failed: (failed: number, total: number) => `Failed conversions (${failed} of ${total} total)`,
needHelp: 'Need help? See our ',
documentation: 'documentation',
or: ' or ',
contactSupport: 'contact support',
dot: '.',
close: 'Close',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { css } from '@emotion/css';

import { GrafanaTheme2 } from '@grafana/data';

export const getStyles = (theme: GrafanaTheme2) => ({
modal: css`
width: auto;
min-width: 750px;
max-width: 75vw;
`,
migrationSummary: css`
padding: ${theme.spacing(2)};
padding-top: 0;
`,
list: css`
margin-top: ${theme.spacing(0.5)};
margin-bottom: ${theme.spacing(2)};
ol,
ul {
margin-left: ${theme.spacing(2)};
li > * {
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
`,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React, { FC } from 'react';

import { Button, Modal, TextLink, useStyles2 } from '@grafana/ui';
import { MigrationSummaryProps } from 'app/features/api-keys/ApiKeysPage';

import FailedMigrationRow from './FailedMigrationRow';
import { CONTACT_SUPPORT_LINK, SERVICE_ACCOUNTS_DOCS_LINK } from './MigrationSummary.constants';
import { Messages } from './MigrationSummary.messages';
import { getStyles } from './MigrationSummary.styles';

const MigrationSummary: FC<MigrationSummaryProps> = ({ visible, data, onDismiss }) => {
const styles = useStyles2(getStyles);

return (
<Modal
title={Messages.title}
isOpen={visible}
closeOnBackdropClick={true}
onDismiss={onDismiss}
className={styles.modal}
>
<p>{Messages.description}</p>
<strong>{Messages.failed(data.failed, data.total)}</strong>
<div className={styles.list}>
<ol>
{data.failedApikeyIDs.map((id, idx) => (
<FailedMigrationRow key={id} id={id} details={data.failedDetails[idx]} />
))}
</ol>
</div>
<p>
{Messages.needHelp}
<TextLink href={SERVICE_ACCOUNTS_DOCS_LINK} external>
{Messages.documentation}
</TextLink>
{Messages.or}
<TextLink href={CONTACT_SUPPORT_LINK} external>
{Messages.contactSupport}
</TextLink>
{Messages.dot}
</p>
<Modal.ButtonRow>
<Button variant="secondary" onClick={onDismiss}>
{Messages.close}
</Button>
</Modal.ButtonRow>
</Modal>
);
};

export default MigrationSummary;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import PerconaMigrator from './PerconaMigrator';

export default PerconaMigrator;
Loading

0 comments on commit c520407

Please sign in to comment.