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
9 changes: 7 additions & 2 deletions integration-tests/testkit/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ import { UpdateSchemaPolicyForOrganization, UpdateSchemaPolicyForProject } from
import { collect, CollectedOperation, legacyCollect } from './usage';
import { generateUnique, getServiceHost, pollForEmailVerificationLink } from './utils';

function createConnectionPool() {
function getPGConnectionString() {
const pg = {
user: ensureEnv('POSTGRES_USER'),
password: ensureEnv('POSTGRES_PASSWORD'),
Expand All @@ -83,8 +83,12 @@ function createConnectionPool() {
db: ensureEnv('POSTGRES_DB'),
};

return `postgres://${pg.user}:${pg.password}@${pg.host}:${pg.port}/${pg.db}?sslmode=disable`;
}

function createConnectionPool() {
return createPostgresDatabasePool({
connectionParameters: `postgres://${pg.user}:${pg.password}@${pg.host}:${pg.port}/${pg.db}?sslmode=disable`,
connectionParameters: getPGConnectionString(),
});
}

Expand Down Expand Up @@ -141,6 +145,7 @@ export function initSeed() {

return {
pollForEmailVerificationLink,
getPGConnectionString,
async purgeOIDCDomains() {
const pool = await getPool();
await pool.query(psql`
Expand Down
58 changes: 58 additions & 0 deletions integration-tests/tests/api/tokens.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { pollFor, readTokenInfo } from 'testkit/flow';
import { ProjectType } from 'testkit/gql/graphql';
import { createTokenStorage } from '@hive/storage';
import { generateToken } from '@hive/tokens';
import { initSeed } from '../../testkit/seed';

test.concurrent('deleting a token should clear the cache', async () => {
Expand Down Expand Up @@ -144,3 +146,59 @@ test.concurrent(
`);
},
);

test.concurrent(
'regression: reading existing token with "last_used_at" from pg database (and not redis cache) does not raise an exception',
async ({ expect }) => {
const seed = initSeed();
const { createOrg } = await seed.createOwner();
const { createProject, organization } = await createOrg();
const { project, target } = await createProject();

const tokenStorage = await createTokenStorage(seed.getPGConnectionString(), 1);

try {
const token = generateToken();

// create new token so it does not yet exist in redis cache
const record = await tokenStorage.createToken({
name: 'foo',
organization: organization.id,
project: project.id,
target: target.id,
scopes: [],
token: token.hash,
tokenAlias: token.alias,
});

// touch the token so it has a date
await tokenStorage.touchTokens({ tokens: [{ token: record.token, date: new Date() }] });
const result = await readTokenInfo(token.secret).then(res => res.expectNoGraphQLErrors());
expect(result.tokenInfo).toMatchInlineSnapshot(`
{
__typename: TokenInfo,
hasOrganizationDelete: false,
hasOrganizationIntegrations: false,
hasOrganizationMembers: false,
hasOrganizationRead: false,
hasOrganizationSettings: false,
hasProjectAlerts: false,
hasProjectDelete: false,
hasProjectOperationsStoreRead: false,
hasProjectOperationsStoreWrite: false,
hasProjectRead: false,
hasProjectSettings: false,
hasTargetDelete: false,
hasTargetRead: false,
hasTargetRegistryRead: false,
hasTargetRegistryWrite: false,
hasTargetSettings: false,
hasTargetTokensRead: false,
hasTargetTokensWrite: false,
}
`);
} finally {
await tokenStorage.destroy();
}
},
);
4 changes: 2 additions & 2 deletions packages/services/storage/src/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const tokenFields = psql`
, "token_alias" AS "tokenAlias"
, "name"
, to_json("created_at") AS "date"
, "last_used_at" AS "lastUsedAt"
, to_json("last_used_at") AS "lastUsedAt"
Comment on lines 23 to +24
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

New database interaction logic should be encapsulated in smaller classes within the corresponding GraphQL modules, not added to the legacy /packages/services/storage module. Additionally, using z.coerce.date() in the TokenModel is a more robust approach for handling timestamps. Note that the database driver returns timestamps as Unix timestamp numbers in milliseconds, so Zod coercion is appropriate to ensure they are treated as Date objects.

Suggested change
, to_json("created_at") AS "date"
, "last_used_at" AS "lastUsedAt"
, to_json("last_used_at") AS "lastUsedAt"
, "created_at" AS "date"
, "last_used_at" AS "lastUsedAt"
References
  1. New database interaction logic should be encapsulated in smaller classes within the corresponding GraphQL modules, not added to the legacy /packages/services/storage module.
  2. The database driver returns timestamps as Unix timestamp numbers in milliseconds, not seconds.

, "organization_id" AS "organization"
, "project_id" AS "project"
, "target_id" AS "target"
Expand Down Expand Up @@ -75,7 +75,7 @@ export async function createTokenStorage(
LIMIT 1
`,
)
.then(TokenModel.parse);
.then(TokenModel.nullable().parse);
},
async createToken({
token,
Expand Down
3 changes: 3 additions & 0 deletions packages/services/tokens/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
"type": "module",
"license": "MIT",
"private": true,
"exports": {
".": "./src/api.ts"
},
"scripts": {
"build": "tsx ../../../scripts/runify.ts",
"dev": "tsup-node --config ../../../configs/tsup/dev.config.node.ts src/dev.ts",
Expand Down
2 changes: 1 addition & 1 deletion packages/services/tokens/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function hashToken(token: string) {
return createHash('sha256').update(token).digest('hex');
}

function generateToken() {
export function generateToken() {
const token = createHash('md5')
.update(String(Math.random()))
.update(String(Date.now()))
Expand Down
8 changes: 0 additions & 8 deletions pnpm-lock.yaml

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

Loading