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
5 changes: 3 additions & 2 deletions frontend/lint/layers.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ const SLICES = {
publication: ['session', 'entities'],
nodes: ['session'],
audit: ['session'],
overrides: ['session', 'entities'],
pasted: ['session', 'entities', 'publication'],
overrides: ['session', 'entities', 'publication', 'pasted'],
overview: ['session', 'entities', 'publication', 'nodes', 'overrides'],
authsources: ['session', 'entities'],
authsources: ['session', 'entities', 'pasted'],
};

const types = (...names) => ({ element: { types: names } });
Expand Down
25 changes: 23 additions & 2 deletions frontend/src/app/adapters/memory/overrides.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { ExternalPage, ExternalSource, OverrideComparison, OverridesPort } from '../../../domain/overrides';
import type { ExternalPage, ExternalSource, ImportPreview, ImportSelection, OverrideComparison, OverridesPort } from '../../../domain/overrides';
import type { CreationReport } from '../../../domain/pasted';
import type { Failed } from '../../../lib/result';
import { boardSources, copiesOf, type SourceFixture } from './external';
import { boardImport } from './pastedSeveral';

const ACS = 'catalogue.library.example.edu/Shibboleth.sso/SAML2/POST';

Expand All @@ -26,6 +28,8 @@ export interface MemoryOverrides {
review?: Failed | 'pending';
sources?: SourceFixture[];
perPage?: number;
// What an Import answers; by default the ImportResult board.
imported?: CreationReport;
}

const PER_PAGE = 25;
Expand All @@ -36,7 +40,22 @@ function matches(q: string) {
return (row: { entityId: string; name: string | null }) => row.entityId.toLowerCase().includes(needle) || (row.name ?? '').toLowerCase().includes(needle);
}

export function memoryOverrides({ comparison = boardComparison, failure, review, sources = boardSources, perPage = PER_PAGE }: MemoryOverrides = {}): OverridesPort {
// The ticked entities of each source, the managed ones left out as Import leaves them.
function preview(sources: SourceFixture[], { set, sources: picked }: ImportSelection): ImportPreview {
return {
sources: picked.flatMap(({ position, all, entityIds }) => {
const fixture = sources[position];
const rows = (fixture?.sets[set] ?? []).filter((row) => !row.managed && (all || entityIds.includes(row.entityId)));

return fixture && rows.length > 0
? [{ heading: fixture.heading, location: fixture.location, entities: rows.map(({ entityId, name }) => ({ entityId, name })) }]
: [];
}),
};
}

export function memoryOverrides(more: MemoryOverrides = {}): OverridesPort {
const { comparison = boardComparison, failure, review, sources = boardSources, perPage = PER_PAGE, imported = boardImport } = more;
const answer = async <T>(data: () => T) => (failure ? { ok: false as const, ...failure } : { ok: true as const, data: data() });

return {
Expand All @@ -62,6 +81,8 @@ export function memoryOverrides({ comparison = boardComparison, failure, review,
return answer(() => ({ set, entityId, name, copies }));
},
compare: () => answer(() => comparison),
importPreview: (selection) => answer(() => preview(sources, selection)),
runImport: () => answer(() => imported),
markReviewed: async () => {
if (review === 'pending') {
return new Promise(() => undefined);
Expand Down
92 changes: 92 additions & 0 deletions frontend/src/app/adapters/memory/pasted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import type { PastedObject, PastedPort, Reading, Target } from '../../../domain/pasted';
import type { Failed, Result } from '../../../lib/result';
import { boardSources, copiesOf } from './external';
import { hrSelfService, noReport, travelbooker } from './pastedBoards';
import { HOSPITAL, moodleReplacement, severalCandidates } from './pastedSeveral';

export interface MemoryPasted {
// What reading answers in place of what the text gives.
reading?: Reading;
failure?: Failed;
}

const AUTHSOURCE: PastedObject = {
id: 'university-ldap',
name: null,
php: "$config['university-ldap'] = [\n 'ldap:Ldap',\n 'hostname' => 'ldaps://ldap.example.edu',\n];",
report: { ...noReport, understood: ['0', 'hostname'] },
};

// The boards' readings, told apart by what the text holds.
export function boardReading(target: Target, text: string, entityId?: string): Reading {
if (target.kind === 'authsource') {
return { kind: 'one', object: AUTHSOURCE };
}
const line = text.split('\n').findIndex((at) => at.includes('file_get_contents('));
if (line >= 0) {
return { kind: 'unreadable', problems: [{ line: line + 1, message: 'file_get_contents(…) is a function call. Paste the certificate itself, as a string.' }] };
}
if (text.includes('IDPSSODescriptor') && target.set === 'saml20-sp-remote') {
return { kind: 'other-set', set: 'saml20-idp-remote', entityId: HOSPITAL };
}
const picked = severalCandidates.find((candidate) => candidate.entityId === entityId);
if (picked) {
const php = `$metadata['${picked.entityId}'] = [\n 'name' => ['en' => '${picked.name ?? ''}'],\n];`;

return { kind: 'one', object: { id: picked.entityId, name: picked.name, php, report: { ...noReport, understood: ['entityid', 'name'] } } };
}
if ((text.match(/\$metadata\s*\[|<(?:md:)?EntityDescriptor\b/g) ?? []).length > 1) {
return { kind: 'several', candidates: severalCandidates };
}
if (text.includes('sharedkey')) {
return { kind: 'one', object: hrSelfService };
}

return { kind: 'one', object: travelbooker };
}

function copyOf(set: Parameters<PastedPort['copy']>[0], entityId: string, source: number): PastedObject | null {
const copy = copiesOf(boardSources, set, entityId).copies.find(({ position }) => position === source);

return copy
? {
id: entityId,
name: copiesOf(boardSources, set, entityId).name,
php: copy.php,
report: { ...noReport, converted: [{ option: 'expire', note: 'Dropped: managed entities do not expire' }] },
}
: null;
}

export function memoryPasted({ reading, failure }: MemoryPasted = {}): PastedPort {
const answer = <T>(data: T): Result<T> => (failure ? { ok: false, ...failure } : { ok: true, data });

return {
read: async (target, text, _format, entityId) => answer(reading ?? boardReading(target, text, entityId)),
copy: async (set, entityId, source) => {
const found = copyOf(set, entityId, source);

return found ? answer(found) : { ok: false, status: 404, body: null };
},
createSeveral: async (set, _text, _format, entityIds) =>
answer({
set,
created: severalCandidates
.filter((candidate) => entityIds.includes(candidate.entityId))
.map(({ entityId, name, collision }) => ({ entityId, name, collision })),
skipped: [],
converted: [],
removable: [],
shadowing: [],
pending: 7 + entityIds.length,
}),
replace: async (_set, entityId, xml) =>
answer<Reading>(
reading ??
(xml.includes(`entityID="${entityId}"`)
? { kind: 'replaced', replacement: moodleReplacement }
: { kind: 'mismatch', entityId: /entityID="([^"]*)"/.exec(xml)?.[1] ?? '' }),
),
createAuthsource: async () => answer({ id: AUTHSOURCE.id }),
};
}
97 changes: 97 additions & 0 deletions frontend/src/app/adapters/memory/pastedBoards.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import type { PastedObject, PastedReport } from '../../../domain/pasted';

const TRAVELBOOKER = 'https://sso.travelbooker.example.com/saml2/metadata/7f3a9c21';
const POST = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST';
const PERSISTENT = 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent';

export const noReport: PastedReport = { needs: [], understood: [], converted: [], extra: [], ignored: [] };

// The metadata the AddReview board reads.
export const travelbookerXml = [
`<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" entityID="${TRAVELBOOKER}" validUntil="2027-01-31T00:00:00Z">`,
' <md:SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">',
` <md:NameIDFormat>${PERSISTENT}</md:NameIDFormat>`,
` <md:AssertionConsumerService index="0" Binding="${POST}" Location="https://sso.travelbooker.example.com/saml2/acs/7f3a9c21"/>`,
' </md:SPSSODescriptor>',
'</md:EntityDescriptor>',
].join('\n');

// AddReview.
export const travelbooker: PastedObject = {
id: TRAVELBOOKER,
name: 'Travelbooker',
php: [
`$metadata['${TRAVELBOOKER}'] = [`,
" 'name' => ['en' => 'Travelbooker'],",
" 'AssertionConsumerService' => [",
' [',
` 'Binding' => '${POST}',`,
" 'Location' => 'https://sso.travelbooker.example.com/saml2/acs/7f3a9c21',",
' ],',
' ],',
` 'NameIDFormat' => '${PERSISTENT}',`,
" 'certData' => 'MIIDXTCCAkWgAwIBAgIJAL3f…',",
" 'validate.authnrequest' => true,",
" 'OrganizationName' => ['en' => 'Travelbooker'],",
'];',
].join('\n'),
report: {
...noReport,
understood: ['entityid', 'AssertionConsumerService', 'NameIDFormat', 'certData', 'validate.authnrequest', 'OrganizationName'],
converted: [
{ option: 'name', note: 'Taken from OrganizationName' },
{ option: 'certData', note: 'Line breaks removed' },
],
ignored: [
{ option: 'validUntil', note: 'Managed entities do not expire' },
{ option: 'index="0"', note: 'Single endpoint' },
],
},
};

const HR = 'https://hr.example.edu/sp';

// The PHP the AddUnreadable board pastes; line 5 is a function call.
export const hrPhp = [
`$metadata['${HR}'] = [`,
" 'name' => ['en' => 'HR self-service'],",
" 'AssertionConsumerService' => 'https://hr.example.edu/saml/acs',",
" 'NameIDFormat' => Constants::NAMEID_PERSISTENT,",
" 'certData' => file_get_contents('/etc/ssl/hr.pem'),",
" 'attributes' => ['uid', 'mail'],",
'];',
].join('\n');

// ReviewNeeds.
export const hrSelfService: PastedObject = {
id: HR,
name: 'HR self-service',
php: [
`$metadata['${HR}'] = [`,
" 'name' => ['en' => 'HR self-service'],",
" 'AssertionConsumerService' => [",
' [',
` 'Binding' => '${POST}',`,
" 'Location' => 'https://hr.example.edu/saml/acs',",
' ],',
' ],',
` 'NameIDFormat' => '${PERSISTENT}',`,
" 'attributes' => ['uid', 'mail'],",
" 'sharedkey' => 'k3y-in-clear-text',",
" 'vendor.tenant' => 'example-edu',",
'];',
].join('\n'),
report: {
needs: [
{ option: 'sharedkey', note: 'Secret in clear text. Use a Secret reference.', severity: 'warning' },
{ option: 'certData', note: 'Was a function call. Paste the certificate.', severity: 'error' },
],
understood: ['entityid', 'name', 'NameIDFormat', 'attributes'],
converted: [
{ option: 'AssertionConsumerService', note: 'One URL became an endpoint list' },
{ option: 'NameIDFormat', note: 'Constant became its value' },
],
extra: [{ option: 'vendor.tenant', note: 'Not a known option' }],
ignored: [{ option: '// comments', note: 'Comments are not kept' }],
},
};
79 changes: 79 additions & 0 deletions frontend/src/app/adapters/memory/pastedSeveral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import type { Candidate, CreationReport, Replacement } from '../../../domain/pasted';
import { MOODLE } from './edited';

// The four entities the AddSeveral board pastes.
export const severalCandidates: Candidate[] = [
{ entityId: 'https://hr.example.edu/sp', name: 'HR self-service', managed: true, collision: null },
{ entityId: 'https://print.example.edu/saml2/service-provider-metadata/campus', name: 'Print service', managed: true, collision: null },
{ entityId: 'https://timetable.example.edu/sp', name: 'Timetable', managed: false, collision: 'override' },
{ entityId: 'https://parking.example.edu/saml/metadata', name: 'Parking permits', managed: false, collision: null },
];

export const severalPhp = severalCandidates
.map(({ entityId, name }) => `$metadata['${entityId}'] = [\n 'name' => ['en' => '${name ?? ''}'],\n];`)
.join('\n');

// The identity provider the AddWrongKind board pastes as a service provider.
export const HOSPITAL = 'https://idp.hospital.example.org/idp/shibboleth';

export const hospitalXml = [
`<md:EntityDescriptor entityID="${HOSPITAL}">`,
' <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">',
' …',
' </md:IDPSSODescriptor>',
'</md:EntityDescriptor>',
].join('\n');

const CERT_OLD = " 'certData' => 'MIIDXTCCAkWgAwIBAgIJAL3f…',";
const CERT_NEW = " 'certData' => 'MIIDdzCCAl+gAwIBAgIEbq9…',";

// ReplaceFrom: Moodle from its new metadata.
export const moodleReplacement: Replacement = {
entityId: MOODLE,
name: 'Moodle',
version: 4,
removed: 4,
php: [
`$metadata['${MOODLE}'] = [`,
" 'name' => ['en' => 'Moodle'],",
" 'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent',",
" 'certData' => 'MIIDdzCCAl+gAwIBAgIEbq9…',",
" 'validate.authnrequest' => true,",
'];',
].join('\n'),
diff: [
{ kind: 'same', text: " 'name' => [" },
{ kind: 'same', text: " 'en' => 'Moodle'," },
{ kind: 'del', text: " 'es' => 'Campus virtual'," },
{ kind: 'same', text: ' ],' },
{ kind: 'same', text: " 'AssertionConsumerService' => [ … ]," },
{ kind: 'del', text: " 'SingleLogoutService' => [ … ]," },
{ kind: 'same', text: " 'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent'," },
{ kind: 'del', text: " 'attributes' => ['uid', 'mail', 'displayName']," },
{ kind: 'del', text: " 'attributes.NameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri'," },
{ kind: 'del', text: CERT_OLD },
{ kind: 'add', text: CERT_NEW },
{ kind: 'same', text: " 'validate.authnrequest' => true," },
{ kind: 'del', text: " 'assertion.encryption' => false," },
],
};

export const moodleXml = `<md:EntityDescriptor entityID="${MOODLE}">\n <md:SPSSODescriptor>…</md:SPSSODescriptor>\n</md:EntityDescriptor>`;

// ImportResult.
export const boardImport: CreationReport = {
set: 'saml20-sp-remote',
created: [
{ entityId: 'https://journals.publisher.example.com/shibboleth', name: 'E-journals', collision: 'override' },
{ entityId: 'https://labs.partner.example.org/Shibboleth.sso/Metadata', name: 'Lab booking', collision: 'override' },
{ entityId: 'https://meet.vendor.example.com/saml2/sp', name: 'Video conferencing', collision: 'override' },
],
skipped: [{ entityId: 'https://card.example.edu/sp', name: 'Campus card', reason: 'Already managed' }],
converted: [
{ option: 'expire', note: 'Dropped: managed entities do not expire' },
{ option: 'certFingerprint', note: 'Kept as an extra option' },
],
removable: [{ location: 'metadata/saml20-sp-remote.php', entityIds: [] }],
shadowing: [],
pending: 10,
};
8 changes: 4 additions & 4 deletions frontend/src/app/test/StoryMessages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { ReportMessage } from '../../domain/session';

// The Console's one-shot message in a story: shown on the page it moves to, which loads afresh.
export function StoryMessages({ children }: { children: ReactNode }) {
const [said, setSaid] = useState<{ text: string; round: number } | null>(null);
const [said, setSaid] = useState<{ text: string; shown: ReactNode; round: number } | null>(null);
const navigate = useNavigate();
const announce = useCallback(
(text: string, to?: string) => {
setSaid((last) => ({ text, round: (last?.round ?? 0) + 1 }));
(text: string, to?: string, shown?: ReactNode) => {
setSaid((last) => ({ text, shown, round: (last?.round ?? 0) + 1 }));
if (to !== undefined) {
void navigate(to, { replace: true });
}
Expand All @@ -20,7 +20,7 @@ export function StoryMessages({ children }: { children: ReactNode }) {

return (
<ReportMessage value={announce}>
<PageNotice value={said && <Callout kind="success" title={said.text} />}>
<PageNotice value={said && (said.shown ?? <Callout kind="success" title={said.text} />)}>
<Fragment key={said?.round ?? 0}>{children}</Fragment>
</PageNotice>
</ReportMessage>
Expand Down
Loading