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
6 changes: 5 additions & 1 deletion docs/backend_arch.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,11 @@ pasa.
ejecución, una asignación como `teacher`.
- `Preparar y enviar entregas` (contenido y envío) queda reservado al `student`
asignado o a un `admin`. Docentes, evaluadores, directivos y proponentes solo
configuran y revisan la entrega, aunque estén asignados al proyecto.
configuran y revisan la entrega, aunque estén asignados al proyecto. Mientras
la entrega esté `pending` o `rejected`, su contenido solo lo ven los
estudiantes asignados y los administradores; al enviarse queda visible para
los miembros del proyecto. La misma regla protege el stream de archivos y la
descarga de adjuntos vinculados a la entrega.
- El `evaluator` de expo no tiene acceso global: solo participa en los
proyectos donde se le asigna el rol de proyecto `evaluator`. En ellos conserva
los permisos de revisión y aprobación de fase.
Expand Down
5 changes: 4 additions & 1 deletion docs/database_arch.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,10 @@ debe coincidir con el `type` de su entrega. Los tipos de texto y enlace usan
`textContent`/`url`/`label`; los de archivo referencian un `ProjectAttachment`
(`attachmentId`, único) y el binario vive en S3/RustFS. Cada fila guarda su autor
y su fecha de creación. Solo el estudiante asignado al proyecto (o un
administrador) puede aportar contenido y enviar la entrega.
administrador) puede aportar contenido y enviar la entrega. Mientras la entrega
está `pending` o `rejected`, el contenido solo se expone a los estudiantes
asignados y a los administradores; tras el envío lo ven todos los miembros del
proyecto.

### MilestoneReportLink

Expand Down
4 changes: 3 additions & 1 deletion docs/frontend_arch.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ La pestaña **Hitos** permite marcar hitos como **mínimos**, asignarles una fas
no se puede completar hasta que todas estén aceptadas. Al elegir el estado
«Finalizado» se avisa si aún quedan hitos mínimos pendientes o falta la
evaluación de la fase. En las entregas se muestra a qué hitos están vinculadas y
se advierte antes de eliminar hitos o entregas que tienen vínculos.
se advierte antes de eliminar hitos o entregas que tienen vínculos. Cuando una
entrega aún no se ha enviado, quien no es estudiante asignado ve un aviso de
contenido privado en lugar de sus textos, enlaces y archivos.

Los estudiantes ven los proyectos privados en `approved` mediante
`ProjectPrivatePreview`: una vista con aviso de información limitada, descripción,
Expand Down
91 changes: 91 additions & 0 deletions hub-backend/src/attachments/attachments.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { ForbiddenException } from '@nestjs/common';
import { Readable } from 'node:stream';
import { AttachmentsService } from './attachments.service';

describe('AttachmentsService', () => {
const user = {
id: 7,
fullName: 'Teacher',
email: 'teacher@example.com',
roles: ['teacher'],
} as never;

function createService() {
const prisma = {
project: { findUnique: jest.fn() },
projectAttachment: { findFirst: jest.fn() },
};
const storage = { read: jest.fn() };
const authorization = {
assertProjectMember: jest.fn(),
assertCanViewReportContents: jest.fn(),
};

return {
service: new AttachmentsService(
prisma as never,
storage as never,
authorization as never,
),
prisma,
storage,
authorization,
};
}

function selectedAttachment(overrides: Record<string, unknown> = {}) {
return {
id: 55,
projectId: 10,
reportId: 3,
uploadedByUserId: 7,
originalName: 'documento.pdf',
storageKey: 'projects/10/documento.pdf',
mimeType: 'application/pdf',
sizeBytes: 1024,
createdAt: new Date('2026-09-13'),
uploadedBy: null,
...overrides,
};
}

it('blocks downloading an attachment linked to a draft report', async () => {
const { service, prisma, storage, authorization } = createService();
prisma.project.findUnique.mockResolvedValue({ id: 10 });
prisma.projectAttachment.findFirst.mockResolvedValue(
selectedAttachment({ report: { status: 'pending' } }),
);
authorization.assertCanViewReportContents.mockRejectedValue(
new ForbiddenException('Report contents are hidden'),
);

await expect(
service.downloadAttachment({ projectId: 10, attachmentId: 55, user }),
).rejects.toBeInstanceOf(ForbiddenException);

expect(authorization.assertCanViewReportContents).toHaveBeenCalledWith(
user,
10,
{ status: 'pending' },
);
expect(storage.read).not.toHaveBeenCalled();
});

it('downloads an attachment once the report has been submitted', async () => {
const { service, prisma, storage } = createService();
prisma.project.findUnique.mockResolvedValue({ id: 10 });
prisma.projectAttachment.findFirst.mockResolvedValue(
selectedAttachment({ report: { status: 'submitted' } }),
);
storage.read.mockResolvedValue({ stream: Readable.from([]) });

const result = await service.downloadAttachment({
projectId: 10,
attachmentId: 55,
user,
});

expect(result.attachment.originalName).toBe('documento.pdf');
expect(storage.read).toHaveBeenCalledWith('projects/10/documento.pdf');
});
});
13 changes: 12 additions & 1 deletion hub-backend/src/attachments/attachments.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,10 @@ export class AttachmentsService {

const attachment = await this.prisma.projectAttachment.findFirst({
where: { id: attachmentId, projectId },
select: attachmentSelect,
select: {
...attachmentSelect,
report: { select: { status: true } },
},
});

if (!attachment) {
Expand All @@ -116,6 +119,14 @@ export class AttachmentsService {
);
}

if (attachment.report) {
await this.authorization.assertCanViewReportContents(
user,
projectId,
attachment.report,
);
}

const stored = await this.storage.read(attachment.storageKey);

return { attachment: mapAttachment(attachment), stream: stored.stream };
Expand Down
52 changes: 51 additions & 1 deletion hub-backend/src/auth/authorization.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { ForbiddenException, NotFoundException } from '@nestjs/common';
import { ActorRole, ProjectStatus, UserRole } from '../generated/prisma/client';
import {
ActorRole,
ProjectStatus,
ReportStatus,
UserRole,
} from '../generated/prisma/client';
import { AuthorizationService } from './authorization.service';

describe('AuthorizationService', () => {
Expand Down Expand Up @@ -624,6 +629,51 @@ describe('AuthorizationService', () => {
});
});

it('allows assigned students to view pending report contents', async () => {
const { service, findAssignment } = createService({ id: 5 });

await expect(
service.assertCanViewReportContents(user([UserRole.student]), 10, {
status: ReportStatus.pending,
}),
).resolves.toBeUndefined();
expect(findAssignment).toHaveBeenCalledWith({
where: { projectId: 10, userId: 7, role: ActorRole.student },
select: { id: true },
});
});

it('rejects pending report contents for users without a student assignment', async () => {
const { service } = createService();

await expect(
service.assertCanViewReportContents(user([UserRole.teacher]), 10, {
status: ReportStatus.pending,
}),
).rejects.toBeInstanceOf(ForbiddenException);
});

it('hides rejected report contents again until they are resubmitted', async () => {
const { service } = createService();

await expect(
service.assertCanViewReportContents(user([UserRole.teacher]), 10, {
status: ReportStatus.rejected,
}),
).rejects.toBeInstanceOf(ForbiddenException);
});

it('shows submitted report contents without checking the assignment', async () => {
const { service, findAssignment } = createService();

await expect(
service.assertCanViewReportContents(user([UserRole.teacher]), 10, {
status: ReportStatus.submitted,
}),
).resolves.toBeUndefined();
expect(findAssignment).not.toHaveBeenCalled();
});

describe('project visibility', () => {
function visibilityPrisma(project: unknown) {
return {
Expand Down
53 changes: 46 additions & 7 deletions hub-backend/src/auth/authorization.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Prisma,
UserRole,
ProjectStatus,
ReportStatus,
} from '../generated/prisma/client';
import { PrismaService } from '../prisma.service';
import { AuthenticatedUser } from './auth.types';
Expand Down Expand Up @@ -256,25 +257,63 @@ export class AuthorizationService {
* Enviar entregas (y preparar su contenido) está reservado a
* administradores y estudiantes asignados al proyecto. Docentes,
* evaluadores y proponentes solo configuran y revisan la entrega.
*
* El mismo criterio decide quién puede ver el contenido de una entrega
* pendiente o rechazada.
*/
async assertCanSubmitReports(
async canSubmitReports(
user: AuthenticatedUser,
projectId: number,
): Promise<void> {
): Promise<boolean> {
if (user.roles.includes(UserRole.admin)) {
return;
return true;
}

const assignment = await this.prisma.projectActorAssignment.findFirst({
where: { projectId, userId: user.id, role: ActorRole.student },
select: { id: true },
});

if (!assignment) {
throw new ForbiddenException(
'A project student assignment is required to submit reports',
);
return Boolean(assignment);
}

async assertCanSubmitReports(
user: AuthenticatedUser,
projectId: number,
): Promise<void> {
if (await this.canSubmitReports(user, projectId)) {
return;
}

throw new ForbiddenException(
'A project student assignment is required to submit reports',
);
}

/**
* El contenido de una entrega solo se expone a los miembros del proyecto
* cuando ya fue enviada. Mientras esté pendiente o rechazada, únicamente los
* estudiantes asignados (y los administradores) pueden consultarlo.
*/
async assertCanViewReportContents(
user: AuthenticatedUser,
projectId: number,
report: { status: ReportStatus },
): Promise<void> {
if (
report.status !== ReportStatus.pending &&
report.status !== ReportStatus.rejected
) {
return;
}

if (await this.canSubmitReports(user, projectId)) {
return;
}

throw new ForbiddenException(
'Report contents are only visible to assigned students until the report is submitted',
);
}

assertCanCreateProject(user: AuthenticatedUser): void {
Expand Down
12 changes: 11 additions & 1 deletion hub-backend/src/projects/projects.select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,16 @@ export function mapProjectDetailResponse(
): ProjectDetailResponse {
const privatePreview = project.isPrivate && !canViewSensitiveData;
const { canExpressInterest = false, viewerInterest = null } = viewerContext;
// Mismo criterio que `AuthorizationService.canSubmitReports`: el borrador de
// una entrega solo lo ve un administrador o un estudiante asignado.
const canViewDraftReportContents =
viewer != null &&
(viewer.roles.includes(UserRole.admin) ||
project.actorAssignments.some(
(assignment) =>
assignment.userId === viewer.id &&
assignment.role === ActorRole.student,
));

return {
...mapProjectListResponse(project, canViewSensitiveData),
Expand Down Expand Up @@ -621,7 +631,7 @@ export function mapProjectDetailResponse(
? project.reports
.slice()
.sort(byDateThenId((report) => report.dueDate.getTime()))
.map(mapReport)
.map((report) => mapReport(report, canViewDraftReportContents))
: [],
};
}
21 changes: 19 additions & 2 deletions hub-backend/src/reports/reports.select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,25 @@ export type ProjectReportResponse = {
createdBy: ReportUser | null;
reviewedBy: ReportUser | null;
milestones: { id: number; title: string }[];
/** `false` mientras el contenido está oculto por no haberse enviado. */
canViewContents: boolean;
/** Indica si existe contenido aunque `contents` venga oculto. */
hasContents: boolean;
contents: ProjectReportContentResponse[];
};

export function mapReport(report: SelectedReport): ProjectReportResponse {
/** Estados en los que el estudiante aún puede editar el contenido. */
export function isDraftReportStatus(status: ReportStatus): boolean {
return status === ReportStatus.pending || status === ReportStatus.rejected;
}

export function mapReport(
report: SelectedReport,
canViewDraftContents = false,
): ProjectReportResponse {
const canViewContents =
!isDraftReportStatus(report.status) || canViewDraftContents;

return {
id: report.id,
projectId: report.projectId,
Expand All @@ -138,6 +153,8 @@ export function mapReport(report: SelectedReport): ProjectReportResponse {
id: link.milestone.id,
title: link.milestone.title,
})),
contents: report.contents.map(mapReportContent),
canViewContents,
hasContents: report.contents.length > 0,
contents: canViewContents ? report.contents.map(mapReportContent) : [],
};
}
Loading
Loading