Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Retry Tracking and Permissions for Tables in Hasura #663

Merged
merged 19 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from 16 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
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,71 @@ exports[`HasuraClient gets table names within a schema 1`] = `
}
`;

exports[`HasuraClient gets tracked tables and their permissions for a schema 1`] = `
[
{
"delete_permissions": [
{
"permission": {},
"role": "role",
},
],
"insert_permissions": [
{
"permission": {},
"role": "role",
},
],
"select_permissions": [
{
"permission": {},
"role": "role",
},
],
"table": {
"name": "tableA",
"schema": "schemaB",
},
"update_permissions": [
{
"permission": {},
"role": "role",
},
],
},
{
"delete_permissions": [
{
"permission": {},
"role": "role",
},
],
"insert_permissions": [
{
"permission": {},
"role": "role",
},
],
"select_permissions": [
{
"permission": {},
"role": "role",
},
],
"table": {
"name": "tableB",
"schema": "schemaB",
},
"update_permissions": [
{
"permission": {},
"role": "role",
},
],
},
]
`;

exports[`HasuraClient runs migrations for the specified schema 1`] = `
[
[
Expand Down
97 changes: 85 additions & 12 deletions runner/src/hasura-client/hasura-client.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
import type fetch from 'node-fetch';

import HasuraClient from './hasura-client';
import HasuraClient, {
type HasuraConfiguration,
type HasuraDatabaseConnectionParameters,
type HasuraMetadata,
type HasuraSource,
type HasuraTableMetadata
} from './hasura-client';

const DEFAULT_HASURA_SOURCE: HasuraSource = {
name: 'default',
kind: 'postgres',
tables: [],
configuration: {
connection_info: {
database_url: { from_env: 'HASURA_GRAPHQL_DATABASE_URL' },
}
}
};

describe('HasuraClient', () => {
const config = {
Expand Down Expand Up @@ -97,6 +114,20 @@ describe('HasuraClient', () => {
expect(JSON.parse(mockFetch.mock.calls[0][1].body)).toMatchSnapshot();
});

it('gets tracked tables and their permissions for a schema', async () => {
const TEST_METADATA = generateTableMetadata(['schemaA', 'schemaB'], ['tableA', 'tableB'], 'role');
const mockFetch = jest
.fn()
.mockResolvedValue({
status: 200,
text: () => JSON.stringify({ metadata: TEST_METADATA })
});
const client = new HasuraClient({ fetch: mockFetch as unknown as typeof fetch }, config);
const trackedTablePermissions = await client.getTrackedTablePermissions('role', 'schemaB');
expect(trackedTablePermissions).toMatchSnapshot();
expect(trackedTablePermissions[0].table).toEqual({ name: 'tableA', schema: 'schemaB' });
});

it('tracks the specified tables for a specified schema', async () => {
const mockFetch = jest
.fn()
Expand Down Expand Up @@ -237,7 +268,7 @@ describe('HasuraClient', () => {
testB_near: 'passB',
testC_near: 'passC'
};
const TEST_METADATA = generateMetadata(testUsers);
const TEST_METADATA = generateConnectionMetadata(testUsers);
const mockFetch = jest
.fn()
.mockResolvedValue({
Expand All @@ -251,8 +282,46 @@ describe('HasuraClient', () => {
});
});

function generateMetadata (testUsers: any): any {
const sources = [];
function generateTableMetadata (schemaNames: string[], tableNames: string[], role: string): any {
const sources: HasuraSource[] = [];
// Insert default source which has different format than the rest
sources.push(DEFAULT_HASURA_SOURCE);

const tables: HasuraTableMetadata[] = [];
schemaNames.forEach((schemaName) => {
tableNames.forEach((tableName) => {
tables.push(generateTableConfig(schemaName, tableName, role));
});
});

sources.push({
name: role,
kind: 'postgres',
tables,
configuration: generateHasuraConfiguration(role, 'password'),
});

return {
version: 3,
sources
};
}

function generateTableConfig (schemaName: string, tableName: string, role: string): HasuraTableMetadata {
return {
table: {
name: tableName,
schema: schemaName,
},
insert_permissions: [{ role, permission: {} }],
select_permissions: [{ role, permission: {} }],
update_permissions: [{ role, permission: {} }],
delete_permissions: [{ role, permission: {} }],
};
}

function generateConnectionMetadata (testUsers: any): HasuraMetadata {
const sources: HasuraSource[] = [];
// Insert default source which has different format than the rest
sources.push({
name: 'default',
Expand Down Expand Up @@ -283,22 +352,26 @@ function generateMetadata (testUsers: any): any {
};
}

function generateSource (user: string, password: string): any {
function generateSource (user: string, password: string): HasuraSource {
return {
name: user,
kind: 'postgres',
tables: [],
configuration: {
connection_info: {
database_url: { connection_parameters: generateConnectionParameter(user, password) },
isolation_level: 'read-committed',
use_prepared_statements: false
}
configuration: generateHasuraConfiguration(user, password),
};
}

function generateHasuraConfiguration (user: string, password: string): HasuraConfiguration {
return {
connection_info: {
database_url: { connection_parameters: generateConnectionParameter(user, password) },
isolation_level: 'read-committed',
use_prepared_statements: false
}
};
}

function generateConnectionParameter (user: string, password: string): any {
function generateConnectionParameter (user: string, password: string): HasuraDatabaseConnectionParameters {
return {
database: user,
host: 'postgres',
Expand Down
78 changes: 75 additions & 3 deletions runner/src/hasura-client/hasura-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,30 @@ interface SqlOptions {
source?: string
}

export type HasuraPermission = 'select' | 'insert' | 'update' | 'delete';

interface TableDefinition {
name: string
schema: string
}
export interface HasuraRolePermission {
role: string
permission: {
check?: Record<string, any>
columns?: string[]
backend_only?: boolean
filter?: Record<string, any>
allow_aggregations?: boolean
}
}
export interface HasuraTableMetadata {
table: TableDefinition
insert_permissions?: HasuraRolePermission[]
select_permissions?: HasuraRolePermission[]
update_permissions?: HasuraRolePermission[]
delete_permissions?: HasuraRolePermission[]
}

export interface HasuraDatabaseConnectionParameters {
password: string
database: string
Expand All @@ -18,6 +42,41 @@ export interface HasuraDatabaseConnectionParameters {
port: number
}

interface HasuraDatabaseUrl {
connection_parameters: HasuraDatabaseConnectionParameters
}

interface DefaultHasuraDatabaseUrl {
from_env: string
}

function isDefaultDatabaseUrl (
object: DefaultHasuraDatabaseUrl | HasuraDatabaseUrl
): object is DefaultHasuraDatabaseUrl {
return 'from_env' in object;
}

export interface HasuraConfiguration {
connection_info: {
database_url: DefaultHasuraDatabaseUrl | HasuraDatabaseUrl
isolation_level?: string
pool_settings?: Record<string, any>
use_prepared_statements?: boolean
}
}

export interface HasuraSource {
name: string
kind: string
tables: HasuraTableMetadata[]
configuration: HasuraConfiguration
}

export interface HasuraMetadata {
version: number
sources: HasuraSource[]
}

type MetadataRequestArgs = Record<string, any>;

type MetadataRequests = Record<string, any>;
Expand Down Expand Up @@ -116,7 +175,7 @@ export default class HasuraClient {
return await this.executeMetadataRequest('bulk', metadataRequests);
}

async exportMetadata (): Promise<any> {
async exportMetadata (): Promise<HasuraMetadata> {
const { metadata } = await this.executeMetadataRequest(
'export_metadata',
{},
Expand All @@ -126,10 +185,12 @@ export default class HasuraClient {
}

async getDbConnectionParameters (account: string): Promise<HasuraDatabaseConnectionParameters> {
const metadata = await this.exportMetadata();
const source = metadata.sources.find((source: { name: any, configuration: any }) => source.name === account);
const metadata: HasuraMetadata = await this.exportMetadata();
const source = metadata.sources.find((source: HasuraSource) => source.name === account);
if (source === undefined) {
throw new Error(`Could not find connection parameters for user ${account} on respective database.`);
} else if (isDefaultDatabaseUrl(source.configuration.connection_info.database_url)) {
throw new Error('Default connection parameters are not supported.');
}
return source.configuration.connection_info.database_url.connection_parameters;
}
Expand Down Expand Up @@ -177,6 +238,17 @@ export default class HasuraClient {
.map(({ name }: { name: string }) => name);
}

async getTrackedTablePermissions (
databaseName: string,
schemaName: string,
): Promise<any> {
darunrs marked this conversation as resolved.
Show resolved Hide resolved
const metadata: HasuraMetadata = await this.exportMetadata();
const hasuraSource = metadata.sources.find((source: HasuraSource) => source.name === databaseName);
const tablesForSchema = hasuraSource?.tables.filter((tableMetadata: HasuraTableMetadata) => tableMetadata.table.schema === schemaName);

return tablesForSchema;
}

async trackTables (
schemaName: string,
tableNames: string[],
Expand Down
2 changes: 1 addition & 1 deletion runner/src/hasura-client/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { default } from './hasura-client';
export type { HasuraDatabaseConnectionParameters } from './hasura-client';
export type { HasuraMetadata, HasuraSource, HasuraConfiguration, HasuraDatabaseConnectionParameters, HasuraTableMetadata, HasuraRolePermission, HasuraPermission } from './hasura-client';
Loading
Loading