Merge branch 'dev' into freight/nati-2

# Conflicts:
#	apps/edr-freight-api/src/app.module.ts
#	apps/edr-freight-api/src/seed/freight-permissions.registry.ts
#	apps/edr-freight-web/backoffice/src/components/layout/sidebar-sections.tsx
#	apps/edr-freight-web/backoffice/src/constants/URLS.ts
#	apps/edr-freight-web/backoffice/src/lib/permissions.ts
This commit is contained in:
Nathnael
2026-08-20 11:29:21 +00:00
287 changed files with 25453 additions and 2339 deletions

View File

@@ -0,0 +1,194 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { DataSource, In, IsNull } from 'typeorm';
import { YardPosition } from '../entities/yard-position.entity';
import { Yard } from '../entities/yard.entity';
/** A mapped desk, joined to its IAM position for display. */
export interface YardPositionRow {
id: string;
yardId: string;
yardCode: string;
yardLabel: string;
positionId: string;
/** Localised name from `iam.positions.name` — null if the position is gone. */
positionName: { am?: string; en?: string } | null;
positionTypeKey: string | null;
}
/**
* The desk↔yard mapping behind yard access scoping.
*
* Reads always join `iam.positions` and drop soft-deleted rows: the mapping has
* no FK to IAM (see the migration), so a position deleted in the admin UI leaves
* an orphan row here. Dropping it on read means the orphan can never widen
* someone's scope — it just disappears.
*/
@Injectable()
export class YardPositionsService {
constructor(private readonly dataSource: DataSource) {}
/** Mapping rows, optionally narrowed to one yard or one position. */
async list(filter: {
yardId?: string;
positionId?: string;
}): Promise<YardPositionRow[]> {
const params: unknown[] = [];
const where: string[] = ['yp.deleted_at IS NULL', 'y.deleted_at IS NULL'];
if (filter.yardId) {
params.push(filter.yardId);
where.push(`yp.yard_id = $${params.length}`);
}
if (filter.positionId) {
params.push(filter.positionId);
where.push(`yp.position_id = $${params.length}`);
}
return this.dataSource.query(
`SELECT yp.id AS "id",
yp.yard_id AS "yardId",
y.code AS "yardCode",
y.label AS "yardLabel",
yp.position_id AS "positionId",
p.name AS "positionName",
pt.key AS "positionTypeKey"
FROM freight.yard_positions yp
JOIN freight.yards y ON y.id = yp.yard_id
-- INNER join: a mapping whose position was deleted grants nothing and
-- is not shown. The row stays for audit until someone re-saves the set.
JOIN iam.positions p ON p.id = yp.position_id AND p.deleted_at IS NULL
LEFT JOIN iam.position_types pt ON pt.id = p.position_type_id
WHERE ${where.join(' AND ')}
ORDER BY y.display_order ASC, y.label ASC, p.name->>'en' ASC`,
params,
);
}
/**
* Replace the yard's entire position set.
*
* Replace, not append — the admin UI submits the full multi-select value, so a
* partial payload would silently keep desks the user just unticked. Callers
* sending a delta will remove everything they omit.
*/
async setPositionsForYard(
yardId: string,
positionIds: string[],
): Promise<YardPositionRow[]> {
await this.assertYardExists(yardId);
await this.assertPositionsExist(positionIds);
await this.dataSource.transaction(async (manager) => {
const repo = manager.getRepository(YardPosition);
await repo.delete({ yardId });
if (positionIds.length) {
await repo.insert(
[...new Set(positionIds)].map((positionId) => ({ yardId, positionId })),
);
}
});
return this.list({ yardId });
}
/** Replace the position's entire yard set. Same replace semantics. */
async setYardsForPosition(
positionId: string,
yardIds: string[],
): Promise<YardPositionRow[]> {
await this.assertPositionsExist([positionId]);
await this.assertYardsExist(yardIds);
await this.dataSource.transaction(async (manager) => {
const repo = manager.getRepository(YardPosition);
await repo.delete({ positionId });
if (yardIds.length) {
await repo.insert(
[...new Set(yardIds)].map((yardId) => ({ yardId, positionId })),
);
}
});
return this.list({ positionId });
}
/**
* Positions offered by the mapping picker.
*
* Reads `iam.positions` directly rather than going through IAM's
* `/positions/list/{unitId}`: that endpoint needs the caller to resolve a unit
* first, and the picker wants every desk that could staff a yard regardless of
* which unit it hangs under.
*/
async listSelectablePositions(): Promise<
Array<{
id: string;
name: { am?: string; en?: string } | null;
positionTypeKey: string | null;
unitKey: string | null;
}>
> {
return this.dataSource.query(
`SELECT p.id AS "id",
p.name AS "name",
pt.key AS "positionTypeKey",
u.key AS "unitKey"
FROM iam.positions p
LEFT JOIN iam.position_types pt ON pt.id = p.position_type_id
LEFT JOIN iam.units u ON u.id = p.unit_id
WHERE p.deleted_at IS NULL
ORDER BY p.name->>'en' ASC`,
);
}
/** Yard ids mapped to any of these positions — the scope resolver's read. */
async yardIdsForPositions(positionIds: string[]): Promise<string[]> {
if (!positionIds.length) return [];
const rows: { yardId: string }[] = await this.dataSource.query(
`SELECT DISTINCT yp.yard_id AS "yardId"
FROM freight.yard_positions yp
JOIN freight.yards y ON y.id = yp.yard_id AND y.deleted_at IS NULL
WHERE yp.deleted_at IS NULL
AND yp.position_id = ANY($1)`,
[positionIds],
);
return rows.map((r) => r.yardId);
}
private async assertYardExists(yardId: string): Promise<void> {
const yard = await this.dataSource
.getRepository(Yard)
.findOne({ where: { id: yardId, deletedAt: IsNull() } });
if (!yard) throw new NotFoundException(`Yard ${yardId} not found`);
}
private async assertYardsExist(yardIds: string[]): Promise<void> {
if (!yardIds.length) return;
const found = await this.dataSource
.getRepository(Yard)
.count({ where: { id: In(yardIds), deletedAt: IsNull() } });
if (found !== new Set(yardIds).size) {
throw new BadRequestException('One or more yards do not exist');
}
}
/**
* Validated in the service because the database cannot: there is no FK to
* `iam.positions`, so an unchecked payload would happily store a typo'd uuid
* that silently grants nothing and reads as a configuration bug later.
*/
private async assertPositionsExist(positionIds: string[]): Promise<void> {
if (!positionIds.length) return;
const unique = [...new Set(positionIds)];
const rows: { count: string }[] = await this.dataSource.query(
`SELECT COUNT(*)::text AS count
FROM iam.positions
WHERE id = ANY($1) AND deleted_at IS NULL`,
[unique],
);
if (Number(rows[0]?.count ?? 0) !== unique.length) {
throw new BadRequestException('One or more positions do not exist');
}
}
}

View File

@@ -0,0 +1,139 @@
import { ForbiddenException } from '@nestjs/common';
import { YardScopeService } from './yard-scope.service';
/**
* The resolver answers "which yards", never "may they act at all" — that stays
* with the permission guard. So a mapped desk is narrowed to its yards, and an
* unmapped one keeps the reach its permissions already gave it.
*/
describe('YardScopeService', () => {
const yardIdsForPositions = jest.fn();
const service = () =>
new YardScopeService({ yardIdsForPositions } as never);
const staff = (positionId: string, permissions: string[] = []) => ({
roles: [{ key: 'staff' }],
permissions: permissions.map((key) => ({ key })),
employee: { position: { id: positionId, permissions: [] } },
});
beforeEach(() => {
jest.clearAllMocks();
delete process.env.YARD_SCOPE_ENFORCE;
});
it('resolves a mapped position to its yards', async () => {
yardIdsForPositions.mockResolvedValue(['yard-kality', 'yard-mojo']);
const scope = await service().getScopedYardIds(staff('pos-officer'));
expect(scope).toEqual(['yard-kality', 'yard-mojo']);
expect(yardIdsForPositions).toHaveBeenCalledWith(['pos-officer']);
});
it('leaves an unmapped position unrestricted — permissions still gate the action', async () => {
yardIdsForPositions.mockResolvedValue([]);
expect(await service().getScopedYardIds(staff('pos-unmapped'))).toBeNull();
});
it('leaves a caller with no resolvable position unrestricted', async () => {
const noPosition = { roles: [{ key: 'staff' }], employee: { position: {} } };
expect(await service().getScopedYardIds(noPosition)).toBeNull();
expect(yardIdsForPositions).not.toHaveBeenCalled();
});
it('narrows nothing for an anonymous caller but grants nothing either', async () => {
expect(await service().getScopedYardIds(null)).toEqual([]);
});
it('returns unrestricted only for super admins and view_all holders', async () => {
const superAdmin = { roles: [{ key: 'super_admin' }] };
const hqDesk = staff('pos-occ', ['edr_freight_app:yards:view_all']);
expect(await service().getScopedYardIds(superAdmin)).toBeNull();
expect(await service().getScopedYardIds(hqDesk)).toBeNull();
expect(yardIdsForPositions).not.toHaveBeenCalled();
});
it('includes delegated positions — standing in must not lose the yard', async () => {
yardIdsForPositions.mockResolvedValue(['yard-kality']);
await service().getScopedYardIds({
roles: [{ key: 'staff' }],
employee: {
position: { id: 'pos-own' },
delegatedPositions: [{ id: 'pos-gelan-director' }],
},
});
expect(yardIdsForPositions).toHaveBeenCalledWith([
'pos-own',
'pos-gelan-director',
]);
});
describe('listFilterYardIds', () => {
it('narrows nothing while shadow-logging', async () => {
yardIdsForPositions.mockResolvedValue(['yard-kality']);
expect(
await service().listFilterYardIds(staff('pos-officer'), undefined, 'list'),
).toBeNull();
});
it('narrows to the mapped yards once enforcing', async () => {
process.env.YARD_SCOPE_ENFORCE = 'true';
yardIdsForPositions.mockResolvedValue(['yard-kality', 'yard-mojo']);
expect(
await service().listFilterYardIds(staff('pos-officer'), undefined, 'list'),
).toEqual(['yard-kality', 'yard-mojo']);
});
it('keeps an in-scope yard filter as the caller asked', async () => {
process.env.YARD_SCOPE_ENFORCE = 'true';
yardIdsForPositions.mockResolvedValue(['yard-kality', 'yard-mojo']);
expect(
await service().listFilterYardIds(staff('pos-officer'), 'yard-mojo', 'list'),
).toEqual(['yard-mojo']);
});
it('returns an empty set — not everything — for an out-of-scope yard filter', async () => {
process.env.YARD_SCOPE_ENFORCE = 'true';
yardIdsForPositions.mockResolvedValue(['yard-kality']);
expect(
await service().listFilterYardIds(staff('pos-officer'), 'yard-djibouti', 'list'),
).toEqual([]);
});
it('never narrows an unmapped desk', async () => {
process.env.YARD_SCOPE_ENFORCE = 'true';
yardIdsForPositions.mockResolvedValue([]);
expect(
await service().listFilterYardIds(staff('pos-unmapped'), undefined, 'list'),
).toBeNull();
});
});
it('only logs an out-of-scope yard until YARD_SCOPE_ENFORCE is set', async () => {
yardIdsForPositions.mockResolvedValue(['yard-kality']);
const shadow = service();
await expect(
shadow.assertYardInScope(staff('pos-officer'), 'yard-mojo', 'test'),
).resolves.toBeUndefined();
process.env.YARD_SCOPE_ENFORCE = 'true';
const enforcing = service();
await expect(
enforcing.assertYardInScope(staff('pos-officer'), 'yard-mojo', 'test'),
).rejects.toBeInstanceOf(ForbiddenException);
});
});

View File

@@ -0,0 +1,186 @@
import { ForbiddenException, Injectable, Logger } from "@nestjs/common";
import { hasFreightPermission, isSuperAdmin } from "../../../common/freight-permission.util";
import { FREIGHT_PERMS } from "../../../seed/freight-permissions.registry";
import { YardPositionsService } from "./yard-positions.service";
/**
* Caller shape the resolver reads — the `/auth/me` user in either of its two
* shapes. Structurally compatible with what `freight-permission.util` accepts,
* so the same object serves both the permission checks and the position walk.
*/
type PositionLike = {
id?: string;
permissions?: { key?: string }[];
positionType?: { key?: string } | null;
};
type ScopeUser = {
roles?: { key?: string }[];
permissions?: { key?: string }[];
employee?:
| {
position?: PositionLike;
delegatedPositions?: PositionLike[];
}
| { positions?: PositionLike[] }[]
| null;
};
/**
* Which yards a caller may touch.
*
* Scope follows the caller's ACTIVE position, not a union of every position they
* have ever held: the frontends already send `x-current-position-id` and the
* token snapshots that one position, so switching desks switches yards — which
* is what staff covering two yards actually do. Delegated positions are added on
* top, otherwise standing in for the Gelan director silently loses Gelan.
*
* `null` means unrestricted, and an UNMAPPED caller gets it. Scoping narrows a
* desk that has been given yards; it does not hand out access. Whether the
* caller may perform the action at all is the permission guard's job — this
* resolver only answers "which yards", so a desk with the permission and no
* mapping keeps the reach it had before the mapping existed.
*
* The trade-off is deliberate and worth knowing: an accidentally-cleared
* mapping widens access rather than blocking work, so the mapping is not a
* containment barrier on its own — the permission keys still are. Super admins
* and holders of `yards:view_all` are unrestricted regardless of mapping.
*
* ENFORCEMENT IS OFF until `YARD_SCOPE_ENFORCE=true`. Until then
* {@link assertYardInScope} logs what it would have blocked and returns. Flip it
* only once the mapping table is populated and the log is quiet — on an empty
* table, enforcing locks out every staff member at once.
*/
@Injectable()
export class YardScopeService {
private readonly logger = new Logger(YardScopeService.name);
// ponytail: 60s cache keyed by the position-id set, no invalidation hook. A
// mapping change takes up to a minute to reach the resolver. Call
// `invalidate()` from the mutation if that lag ever matters.
private static readonly CACHE_TTL_MS = 60_000;
private readonly cache = new Map<string, { yardIds: string[]; at: number }>();
constructor(private readonly yardPositions: YardPositionsService) {}
/** True when the deny path is live; false while shadow-logging. */
get enforced(): boolean {
return process.env.YARD_SCOPE_ENFORCE === "false";
}
/** Yard ids the caller is scoped to, or `null` for unrestricted. */
async getScopedYardIds(user: ScopeUser | null | undefined): Promise<string[] | null> {
// No user at all is an unauthenticated call the guards should already have
// rejected — narrow to nothing rather than trusting it.
if (!user) return [];
if (isSuperAdmin(user)) return null;
if (hasFreightPermission(user, FREIGHT_PERMS.yards.viewAll)) return null;
const positionIds = this.effectivePositionIds(user);
// No resolvable position — nothing to narrow by, so nothing is narrowed.
if (!positionIds.length) return null;
const key = positionIds.join(",");
const hit = this.cache.get(key);
if (hit && Date.now() - hit.at < YardScopeService.CACHE_TTL_MS) {
return hit.yardIds.length ? hit.yardIds : null;
}
const yardIds = await this.yardPositions.yardIdsForPositions(positionIds);
this.cache.set(key, { yardIds, at: Date.now() });
// Unmapped desk → unrestricted. Mapping narrows; absence of one does not.
return yardIds.length ? yardIds : null;
}
async isYardInScope(
user: ScopeUser | null | undefined,
yardId: string | null | undefined,
): Promise<boolean> {
if (!yardId) return true;
const scope = await this.getScopedYardIds(user);
return scope === null || scope.includes(yardId);
}
/**
* Gate an action on a yard. While `YARD_SCOPE_ENFORCE` is unset this only
* logs — wire it into write paths first and read filters second, so the
* shadow log shows what enforcement would break before it breaks it.
*/
async assertYardInScope(
user: ScopeUser | null | undefined,
yardId: string | null | undefined,
context: string,
): Promise<void> {
if (await this.isYardInScope(user, yardId)) return;
const positions = this.effectivePositionIds(user).join(",") || "none";
if (!this.enforced) {
this.logger.warn(
`[yard-scope shadow] would block ${context}: yard=${yardId} positions=${positions}`,
);
return;
}
throw new ForbiddenException("This yard is outside your assigned yards");
}
/**
* Yard ids a list query should be narrowed to, or `null` for no narrowing.
*
* Returns an EMPTY array only when the caller explicitly asked for a yard
* outside their scope and enforcement is on — the caller should answer with an
* empty result rather than silently widening back to everything.
*
* While `YARD_SCOPE_ENFORCE` is unset this always returns `null` and logs what
* it would have narrowed, so the mapping can be populated against real traffic
* before it starts hiding rows.
*/
async listFilterYardIds(
user: ScopeUser | null | undefined,
requestedYardId: string | null | undefined,
context: string,
): Promise<string[] | null> {
const scope = await this.getScopedYardIds(user);
if (scope === null) return null;
const outOfScope = !!requestedYardId && !scope.includes(requestedYardId);
if (!this.enforced) {
this.logger.warn(
`[yard-scope shadow] would narrow ${context} to [${scope.join(", ")}]` +
(outOfScope ? ` and reject yard=${requestedYardId}` : ""),
);
return null;
}
if (outOfScope) return [];
return requestedYardId ? [requestedYardId] : scope;
}
/** Drops the memoised scopes — call after editing the mapping. */
invalidate(): void {
this.cache.clear();
}
/** Active position plus any delegated ones, across both `employee` shapes. */
private effectivePositionIds(user: ScopeUser | null | undefined): string[] {
const ids = new Set<string>();
const employee = user?.employee;
if (!employee) return [];
if (Array.isArray(employee)) {
for (const emp of employee) {
for (const position of emp.positions ?? []) {
if (position?.id) ids.add(position.id);
}
}
return [...ids];
}
if (employee.position?.id) ids.add(employee.position.id);
for (const delegated of employee.delegatedPositions ?? []) {
if (delegated?.id) ids.add(delegated.id);
}
return [...ids];
}
}