Skip to content

fix: update rule check for connect with implicit many-to-many relation #565

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

Merged
merged 2 commits into from
Jul 8, 2023
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
7 changes: 7 additions & 0 deletions packages/runtime/src/enhancements/model-meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,10 @@ export function getDefaultModelMeta(): ModelMeta {
export function resolveField(modelMeta: ModelMeta, model: string, field: string) {
return modelMeta.fields[lowerCaseFirst(model)][field];
}

/**
* Gets all fields of a model.
*/
export function getFields(modelMeta: ModelMeta, model: string) {
return modelMeta.fields[lowerCaseFirst(model)];
}
40 changes: 37 additions & 3 deletions packages/runtime/src/enhancements/policy/policy-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
PrismaWriteActionType,
} from '../../types';
import { getVersion } from '../../version';
import { resolveField } from '../model-meta';
import { getFields, resolveField } from '../model-meta';
import { NestedWriteVisitor, type VisitorContext } from '../nested-write-vistor';
import type { ModelMeta, PolicyDef, PolicyFunc, ZodSchemas } from '../types';
import {
Expand Down Expand Up @@ -294,6 +294,37 @@ export class PolicyUtil {
return;
}

if (injectTarget._count !== undefined) {
// _count needs to respect read policies of related models
if (injectTarget._count === true) {
// include count for all relations, expand to all fields
// so that we can inject guard conditions for each of them
injectTarget._count = { select: {} };
const modelFields = getFields(this.modelMeta, model);
if (modelFields) {
for (const [k, v] of Object.entries(modelFields)) {
if (v.isDataModel && v.isArray) {
// create an entry for to-many relation
injectTarget._count.select[k] = {};
}
}
}
}

// inject conditions for each relation
for (const field of Object.keys(injectTarget._count.select)) {
if (typeof injectTarget._count.select[field] !== 'object') {
injectTarget._count.select[field] = {};
}
const fieldInfo = resolveField(this.modelMeta, model, field);
if (!fieldInfo) {
continue;
}
// inject into the "where" clause inside select
await this.injectAuthGuard(injectTarget._count.select[field], fieldInfo.type, 'read');
}
}

const idFields = this.getIdFields(model);
for (const field of getModelFields(injectTarget)) {
const fieldInfo = resolveField(this.modelMeta, model, field);
Expand Down Expand Up @@ -602,6 +633,9 @@ export class PolicyUtil {

// process relation updates: connect, connectOrCreate, and disconnect
const processRelationUpdate = async (model: string, args: any, context: VisitorContext) => {
// CHECK ME: equire the entity being connected readable?
// await this.checkPolicyForFilter(model, args, 'read', this.db);

if (context.field?.backLink) {
// fetch the backlink field of the model being connected
const backLinkField = resolveField(this.modelMeta, model, context.field.backLink);
Expand Down Expand Up @@ -720,9 +754,9 @@ export class PolicyUtil {
}
}

private getModelField(model: string, backlinkField: string) {
private getModelField(model: string, field: string) {
model = lowerCaseFirst(model);
return this.modelMeta.fields[model]?.[backlinkField];
return this.modelMeta.fields[model]?.[field];
}

private transaction(db: DbClientContract, action: (tx: Record<string, DbOperations>) => Promise<any>) {
Expand Down
19 changes: 16 additions & 3 deletions packages/schema/src/plugins/model-meta/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ function generateModelMetadata(dataModels: DataModel[], writer: CodeBlockWriter)
isOptional: ${f.type.optional},
attributes: ${JSON.stringify(getFieldAttributes(f))},
backLink: ${backlink ? "'" + backlink.name + "'" : 'undefined'},
isRelationOwner: ${isRelationOwner(f)},
isRelationOwner: ${isRelationOwner(f, backlink)},
},`);
}
});
Expand Down Expand Up @@ -177,6 +177,19 @@ function getUniqueConstraints(model: DataModel) {
return constraints;
}

function isRelationOwner(field: DataModelField) {
return hasAttribute(field, '@relation');
function isRelationOwner(field: DataModelField, backLink: DataModelField | undefined) {
if (!isDataModel(field.type.reference?.ref)) {
return false;
}

if (hasAttribute(field, '@relation')) {
// this field has `@relation` attribute
return true;
} else if (!backLink || !hasAttribute(backLink, '@relation')) {
// if the opposite side field doesn't have `@relation` attribute either,
// it's an implicit many-to-many relation, both sides are owners
return true;
} else {
return false;
}
}
132 changes: 132 additions & 0 deletions tests/integration/tests/with-policy/connect-disconnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ describe('With Policy: connect-disconnect', () => {
model M1 {
id String @id @default(uuid())
m2 M2[]
value Int @default(0)

@@deny('read', value < 0)
@@allow('all', true)
}

Expand Down Expand Up @@ -49,6 +51,7 @@ describe('With Policy: connect-disconnect', () => {

const db = withPolicy();

// m1-1 -> m2-1
await db.m2.create({ data: { id: 'm2-1', value: 1, deleted: false } });
await db.m1.create({
data: {
Expand All @@ -58,7 +61,9 @@ describe('With Policy: connect-disconnect', () => {
},
},
});
// mark m2-1 deleted
await prisma.m2.update({ where: { id: 'm2-1' }, data: { deleted: true } });
// disconnect denied because of violation of m2's update rule
await expect(
db.m1.update({
where: { id: 'm1-1' },
Expand All @@ -69,7 +74,9 @@ describe('With Policy: connect-disconnect', () => {
},
})
).toBeRejectedByPolicy();
// reset m2-1 delete
await prisma.m2.update({ where: { id: 'm2-1' }, data: { deleted: false } });
// disconnect allowed
await db.m1.update({
where: { id: 'm1-1' },
data: {
Expand All @@ -79,6 +86,7 @@ describe('With Policy: connect-disconnect', () => {
},
});

// connect during create denied
await db.m2.create({ data: { id: 'm2-2', value: 1, deleted: true } });
await expect(
db.m1.create({
Expand Down Expand Up @@ -138,6 +146,21 @@ describe('With Policy: connect-disconnect', () => {
},
})
).toBeRejectedByPolicy();

// // connect from m2 to m1, require m1 to be readable
// await db.m2.create({ data: { id: 'm2-7', value: 1 } });
// await prisma.m1.create({ data: { id: 'm1-2', value: -1 } });
// // connect is denied because m1 is not readable
// await expect(
// db.m2.update({
// where: { id: 'm2-7' },
// data: {
// m1: {
// connect: { id: 'm1-2' },
// },
// },
// })
// ).toBeRejectedByPolicy();
});

it('nested to-many', async () => {
Expand Down Expand Up @@ -267,4 +290,113 @@ describe('With Policy: connect-disconnect', () => {
})
).toBeRejectedByPolicy();
});

const modelImplicitManyToMany = `
model M1 {
id String @id @default(uuid())
value Int @default(0)
m2 M2[]

@@deny('read', value < 0)
@@allow('all', true)
}

model M2 {
id String @id @default(uuid())
value Int
deleted Boolean @default(false)
m1 M1[]

@@deny('read', value < 0)
@@allow('read,create', true)
@@allow('update', !deleted)
}
`;

it('implicit many-to-many', async () => {
const { withPolicy, prisma } = await loadSchema(modelImplicitManyToMany);

const db = withPolicy();

await prisma.m1.create({ data: { id: 'm1-1', value: 1 } });
await prisma.m2.create({ data: { id: 'm2-1', value: 1 } });
await expect(
db.m1.update({
where: { id: 'm1-1' },
data: { m2: { connect: { id: 'm2-1' } } },
})
).toResolveTruthy();

await prisma.m1.create({ data: { id: 'm1-2', value: 1 } });
await prisma.m2.create({ data: { id: 'm2-2', value: 1, deleted: true } });
// m2-2 not updatable
await expect(
db.m1.update({
where: { id: 'm1-2' },
data: { m2: { connect: { id: 'm2-2' } } },
})
).toBeRejectedByPolicy();

// await prisma.m1.create({ data: { id: 'm1-3', value: -1 } });
// await prisma.m2.create({ data: { id: 'm2-3', value: 1 } });
// // m1-3 not readable
// await expect(
// db.m2.update({
// where: { id: 'm2-3' },
// data: { m1: { connect: { id: 'm1-3' } } },
// })
// ).toBeRejectedByPolicy();
});

const modelExplicitManyToMany = `
model M1 {
id String @id @default(uuid())
value Int @default(0)
m2 M1OnM2[]

@@allow('all', true)
}

model M2 {
id String @id @default(uuid())
value Int
deleted Boolean @default(false)
m1 M1OnM2[]

@@allow('read,create', true)
}

model M1OnM2 {
m1 M1 @relation(fields: [m1Id], references: [id])
m1Id String
m2 M2 @relation(fields: [m2Id], references: [id])
m2Id String

@@id([m1Id, m2Id])
@@allow('read', true)
@@allow('create', !m2.deleted)
}
`;

it('explicit many-to-many', async () => {
const { withPolicy, prisma } = await loadSchema(modelExplicitManyToMany);

const db = withPolicy();

await prisma.m1.create({ data: { id: 'm1-1', value: 1 } });
await prisma.m2.create({ data: { id: 'm2-1', value: 1 } });
await expect(
db.m1OnM2.create({
data: { m1: { connect: { id: 'm1-1' } }, m2: { connect: { id: 'm2-1' } } },
})
).toResolveTruthy();

await prisma.m1.create({ data: { id: 'm1-2', value: 1 } });
await prisma.m2.create({ data: { id: 'm2-2', value: 1, deleted: true } });
await expect(
db.m1OnM2.create({
data: { m1: { connect: { id: 'm1-2' } }, m2: { connect: { id: 'm2-2' } } },
})
).toBeRejectedByPolicy();
});
});
Loading