Skip to content

Commit

Permalink
Change workspace id to 6 random characters (#100)
Browse files Browse the repository at this point in the history
* change workspace id size to 6

Signed-off-by: Yulong Ruan <ruanyl@amazon.com>

* added license header

Signed-off-by: Yulong Ruan <ruanyl@amazon.com>

---------

Signed-off-by: Yulong Ruan <ruanyl@amazon.com>
  • Loading branch information
ruanyl committed Sep 15, 2023
1 parent 5ce834e commit 7df3659
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/plugins/workspace/server/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import { generateRandomId } from './utils';

describe('workspace utils', () => {
it('should generate id with the specified size', () => {
expect(generateRandomId(6)).toHaveLength(6);
});

it('should generate random IDs', () => {
const NUM_OF_ID = 10000;
const ids = new Set<string>();
for (let i = 0; i < NUM_OF_ID; i++) {
ids.add(generateRandomId(6));
}
expect(ids.size).toBe(NUM_OF_ID);
});
});
13 changes: 13 additions & 0 deletions src/plugins/workspace/server/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import crypto from 'crypto';

/**
* Generate URL friendly random ID
*/
export const generateRandomId = (size: number) => {
return crypto.randomBytes(size).toString('base64url').slice(0, size);
};
5 changes: 5 additions & 0 deletions src/plugins/workspace/server/workspace_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import {
WorkspaceAttributeWithPermission,
} from './types';
import { workspace } from './saved_objects';
import { generateRandomId } from './utils';

const WORKSPACE_ID_SIZE = 6;

export class WorkspaceClientWithSavedObject implements IWorkspaceDBImpl {
private setupDep: CoreSetup;
Expand Down Expand Up @@ -53,9 +56,11 @@ export class WorkspaceClientWithSavedObject implements IWorkspaceDBImpl {
): ReturnType<IWorkspaceDBImpl['create']> {
try {
const { permissions, ...attributes } = payload;
const id = generateRandomId(WORKSPACE_ID_SIZE);
const result = await this.getSavedObjectClientsFromRequestDetail(requestDetail).create<
Omit<WorkspaceAttribute, 'id'>
>(WORKSPACE_TYPE, attributes, {
id,
permissions,
});
return {
Expand Down

0 comments on commit 7df3659

Please sign in to comment.