mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
fix: close the findings the test suite surfaced
The suite that landed in #43/#44 was written against existing behaviour, so a number of tests pinned bugs rather than asserting correct behaviour. This fixes the production code and moves each of those tests onto the fixed behaviour in the same change. Security: - project-download: derive the archive entry extension from the last path segment and restrict it to a short alphanumeric run, so an extensionless allowlisted url can no longer contribute a path separator; validate the r2 branch against the strict proxy-path pattern instead of a `startsWith`, which let `/api/upload/video/clip.mp4/../../etc/passwd` through verbatim. - rate-limit: hash a key or action wider than its column instead of skipping the query. Both the guard and the failing INSERT used to answer "allowed", so the limit stopped applying entirely. Warn at startup when TRUSTED_PROXY_MODE is unset in production. - video uploads: the file name decides the content type; a client-declared video mime no longer makes `payload.exe` acceptable. - email templates: escape in the helpers rather than relying on every caller, with an explicit `rawEmailHtml()` opt-out for the one call site that builds markup. `escapeHtml` now covers the single quote. - CSP: allow loopback object storage outside production only. - route-access: reach the billing redirect only for the workspace owner. Keying it off the owner's billing status alone made the redirect target an oracle for whose subscription had lapsed, and sent members to a page they cannot act on. - search: carry the same billing condition every other read path carries. - logger: check `err.name` as well as `err.constructor.name`, so a re-thrown, deserialised or minified Prisma error is still redacted. - upload tokens: resolve the signing secret outside the try, so a server booted without one fails loudly instead of reporting every grant as a forgery. - invitations: never downgrade an existing membership, and report a scoped invitation that points at nothing as not_found rather than accepted. - auth: resolve the workspace role for every signed-in caller, so checkProjectAccess and computeProjectAccess stop disagreeing about the owner who also owns the workspace. The `intent` option is gone with it. - r2-media-proxy: validate the object key inside the proxy so the guard travels with the function; delete the unused, unanchored `mediaUrlToR2Key`. - r2: sign the content type into presigned PUT grants. Correctness: - frame rate snapping picks the nearest standard, not the first within tolerance, so 24, 30 and 60 fps are reachable at all. - a version upload registers its Bunny cleanup as soon as bunny-init answers, so a failed tus upload no longer leaves a billed video behind. - deleting videos clears storage before the rows, so a refused DELETE leaves a retryable row rather than an orphaned object. - an expired upload session can be cancelled, which is what releases its quota. - `voice/` joins the delete allowlist, so a voice note can be removed by the module that wrote it. - a failed CORS write propagates instead of being mistaken for an empty config and replacing the bucket's rules. - filtering projects by workspace no longer hides projects the unfiltered call returns. - upload retries skip aborts and permanent 4xx; progress no longer divides by zero. - reply edits no longer clear the comment's tag; optimistic resolve rolls back to the state it replaced; the delete snapshot is captured once. - assorted UI fixes: duplicate React keys, double-click guards reading stale closures, the tag list fetched twice per load, a failed member list rendering as an empty one, a stale "Initializing upload..." beside a failure, and a registration banner pointing at an email that never arrives. Consistency and access: - the two download routes answer 404 for an id belonging to another tenant, as the comment export route already did. A caller who does belong still gets 403. - accessible names for the share-link password field, the guest name gates, the version dialog inputs and the comment-tag controls. Repository health: - the runner image installs production dependencies only. - a setup file for the unit project restores stubbed env centrally. - native tsconfig path resolution replaces vite-tsconfig-paths. - `uploadBytesWithProgress` exists once. - admin stats bill Bunny storage to the workspace owner like every other quota, gate on the configured flag, wire up the single-flight guard and count the statuses that belonged to no bucket. - `r2Client.destroy()` releases the presign client too. - `prepare` tolerates a production install, where husky is absent.
This commit is contained in:
@@ -243,19 +243,19 @@ describe('CommentRichText asset mentions', () => {
|
||||
expect(screen.getByRole('button', { name: '@https://evil.test/x' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// KNOWN BUG, pinned rather than fixed. `renderUrls` keys its fragments by the
|
||||
// index within its own slice, and CommentRichText calls it once per gap
|
||||
// between mentions, so the same key ("txt-0") is emitted for several
|
||||
// siblings. React logs "Encountered two children with the same key" and warns
|
||||
// that children may be duplicated or omitted. The output happens to be
|
||||
// correct today; the text assertion locks that in, and the warning assertion
|
||||
// is the thing to delete once the keys are made unique.
|
||||
it('produces duplicate React keys when text surrounds a mention', () => {
|
||||
// `renderUrls` used to key its fragments by the index within its own slice, and
|
||||
// CommentRichText calls it once per gap between mentions, so the same key ("txt-0") was
|
||||
// emitted for several siblings and React warned that children may be duplicated or
|
||||
// omitted. The keys carry the slice offset now.
|
||||
it('emits no duplicate React keys when text surrounds a mention', () => {
|
||||
const { container } = render(
|
||||
<CommentRichText text="Before @[One](asset:aaa111) middle @[Two](asset:bbb222) after" />
|
||||
);
|
||||
|
||||
expect(container).toHaveTextContent('Before @One middle @Two after');
|
||||
expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('same key'), 'txt-0');
|
||||
expect(consoleError).not.toHaveBeenCalledWith(
|
||||
expect.stringContaining('same key'),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -733,15 +733,12 @@ describe('useCommentActions editing', () => {
|
||||
expect(findComment(harness, 'c1')?.content).toBe('Existing note');
|
||||
});
|
||||
|
||||
// KNOWN BUG, pinned rather than fixed. `editTagId` is typed `string | null`
|
||||
// and initialised to `null`, so the `editTagId !== undefined` guard in the
|
||||
// hook can never be false: every edit PATCH carries a `tagId`, and every
|
||||
// successful edit overwrites the comment's tag with whatever `editTagId`
|
||||
// happens to hold. The comment editor in comments-pane.tsx seeds it from the
|
||||
// comment, but the REPLY editor (comments-pane.tsx, "Edit" on a reply) sets
|
||||
// only editingCommentId and editText, so editing a reply's text silently
|
||||
// sends tagId: null.
|
||||
it('always sends a tagId, and clears the tag, even when the caller never set one', async () => {
|
||||
// `editTagId` was initialised to `null`, so the `editTagId !== undefined` guard could
|
||||
// never be false: every edit PATCH carried a `tagId` and every success overwrote the
|
||||
// comment's tag. The comment editor seeds the value from the comment, but the reply
|
||||
// editor sets only editingCommentId and editText, so editing a reply's text silently
|
||||
// cleared its tag or applied a stale one. `undefined` now means "not managed here".
|
||||
it('sends no tagId when the caller never set one, and leaves the tag alone', async () => {
|
||||
const harness = renderActions();
|
||||
|
||||
act(() => harness.result.current.actions.setEditText('Reworded note'));
|
||||
@@ -749,6 +746,23 @@ describe('useCommentActions editing', () => {
|
||||
await harness.result.current.actions.handleEditComment('c1');
|
||||
});
|
||||
|
||||
expect(bodyOf(callsTo('/api/comments/c1', 'PATCH')[0])).toEqual({
|
||||
content: 'Reworded note',
|
||||
});
|
||||
expect(findComment(harness, 'c1')?.tag).toEqual(TAGS[0]);
|
||||
});
|
||||
|
||||
it('sends tagId: null when the editor explicitly clears the tag', async () => {
|
||||
const harness = renderActions();
|
||||
|
||||
act(() => {
|
||||
harness.result.current.actions.setEditText('Reworded note');
|
||||
harness.result.current.actions.setEditTagId(null);
|
||||
});
|
||||
await act(async () => {
|
||||
await harness.result.current.actions.handleEditComment('c1');
|
||||
});
|
||||
|
||||
expect(bodyOf(callsTo('/api/comments/c1', 'PATCH')[0])).toEqual({
|
||||
content: 'Reworded note',
|
||||
tagId: null,
|
||||
|
||||
@@ -619,18 +619,19 @@ describe('useDownloadActions repeated clicks', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// KNOWN FRAGILITY, pinned rather than fixed. The in-flight guard reads
|
||||
// `isDownloadingVideo` out of the closure the callback was created in, so two
|
||||
// calls made from the SAME render (a double click landing before React
|
||||
// commits the state update) both get through and the file is fetched twice.
|
||||
it('lets two calls from the same render both through', async () => {
|
||||
// The in-flight guard used to read `isDownloadingVideo` out of the closure the callback
|
||||
// was created in, so two calls made from the SAME render (a double click landing before
|
||||
// React commits the state update) both got through and the file was fetched twice. It
|
||||
// reads a ref now.
|
||||
it('refuses a second call from the same render', async () => {
|
||||
const startDownload = renderDownload().result.current.startDownload;
|
||||
|
||||
await act(async () => {
|
||||
await Promise.all([startDownload(), startDownload()]);
|
||||
});
|
||||
|
||||
expect(urlsFetched().filter((url) => url.includes('prepare=1'))).toHaveLength(2);
|
||||
expect(urlsFetched().filter((url) => url.includes('prepare=1'))).toHaveLength(1);
|
||||
expect(clicked).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('is ready to download again after a failure', async () => {
|
||||
|
||||
@@ -522,18 +522,18 @@ describe('useVersionActions uploading a file to Bunny', () => {
|
||||
expect(callsTo(BUNNY_INIT_URL, 'DELETE')).toHaveLength(0);
|
||||
});
|
||||
|
||||
// BUG, pinned rather than fixed. bunny-init has already created a video on
|
||||
// Bunny by the time tus runs, but `pendingCleanup` is only assigned after
|
||||
// uploadNewVersionFile returns. A tus failure therefore leaks that video:
|
||||
// nothing ever calls the DELETE branch below it in the catch.
|
||||
it('leaks the Bunny video when the tus upload itself fails', async () => {
|
||||
// bunny-init has already created a video on Bunny by the time tus runs. `pendingCleanup`
|
||||
// used to be assigned only after uploadNewVersionFile returned, so a tus failure threw
|
||||
// past the assignment and left that video behind: billed, and invisible in the app. It
|
||||
// is registered as soon as bunny-init answers now.
|
||||
it('deletes the Bunny video when the tus upload itself fails', async () => {
|
||||
tusFailure = 'connection reset';
|
||||
const harness = renderVersionActions({ directUploadsEnabled: true });
|
||||
|
||||
await createFromFile(harness);
|
||||
|
||||
expect(toastError).toHaveBeenCalledWith('Upload failed: connection reset');
|
||||
expect(callsTo(BUNNY_INIT_URL, 'DELETE')).toHaveLength(0);
|
||||
expect(callsTo(BUNNY_INIT_URL, 'DELETE')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -580,7 +580,7 @@ describe('useVideoAssets deleting', () => {
|
||||
expect(callsTo(`/api/videos/${VIDEO_ID}/assets/a1`, 'DELETE')).toHaveLength(1);
|
||||
expect(deleted).toBe(true);
|
||||
expect(assetIds(harness)).toEqual(['a2']);
|
||||
expect(harness.result.current.activeDeleteAssetId).toBeNull();
|
||||
expect(harness.result.current.deletingAssetIds).toEqual([]);
|
||||
});
|
||||
|
||||
it('marks which row is being deleted while the request runs', async () => {
|
||||
@@ -592,13 +592,13 @@ describe('useVideoAssets deleting', () => {
|
||||
act(() => {
|
||||
removal = harness.result.current.deleteAsset('a1');
|
||||
});
|
||||
expect(harness.result.current.activeDeleteAssetId).toBe('a1');
|
||||
expect(harness.result.current.deletingAssetIds).toEqual(['a1']);
|
||||
|
||||
await act(async () => {
|
||||
pending.resolve(jsonResponse(true, {}));
|
||||
await removal;
|
||||
});
|
||||
expect(harness.result.current.activeDeleteAssetId).toBeNull();
|
||||
expect(harness.result.current.deletingAssetIds).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the row when the server refuses the delete', async () => {
|
||||
@@ -615,7 +615,7 @@ describe('useVideoAssets deleting', () => {
|
||||
expect(deleted).toBe(false);
|
||||
expect(assetIds(harness)).toEqual(['a1']);
|
||||
expect(toastError).toHaveBeenCalledWith('Only the uploader can delete');
|
||||
expect(harness.result.current.activeDeleteAssetId).toBeNull();
|
||||
expect(harness.result.current.deletingAssetIds).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the row when the delete throws', async () => {
|
||||
@@ -644,7 +644,35 @@ describe('useVideoAssets deleting', () => {
|
||||
});
|
||||
|
||||
expect(assetIds(harness)).toEqual([]);
|
||||
expect(harness.result.current.activeDeleteAssetId).toBeNull();
|
||||
expect(harness.result.current.deletingAssetIds).toEqual([]);
|
||||
});
|
||||
|
||||
// A single slot meant the second delete cleared the first one's spinner, so the first
|
||||
// row stopped indicating progress while its request was still in flight.
|
||||
it('marks both rows while two deletes overlap', async () => {
|
||||
listed = listResponse({ assets: [makeAsset(), makeAsset({ id: 'a2' })] });
|
||||
const harness = await renderAssets();
|
||||
const first = deferred<unknown>();
|
||||
const second = deferred<unknown>();
|
||||
fetchMock.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
|
||||
|
||||
let removals: Promise<boolean[]> | undefined;
|
||||
act(() => {
|
||||
removals = Promise.all([
|
||||
harness.result.current.deleteAsset('a1'),
|
||||
harness.result.current.deleteAsset('a2'),
|
||||
]);
|
||||
});
|
||||
|
||||
expect(harness.result.current.deletingAssetIds).toEqual(['a1', 'a2']);
|
||||
|
||||
await act(async () => {
|
||||
first.resolve(jsonResponse(true, {}));
|
||||
second.resolve(jsonResponse(true, {}));
|
||||
await removals;
|
||||
});
|
||||
|
||||
expect(harness.result.current.deletingAssetIds).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -477,14 +477,14 @@ describe('useVideoPageData loading tags', () => {
|
||||
expect(harness.result.current.selectedTagId).toBe('tag-colour');
|
||||
});
|
||||
|
||||
// KNOWN INEFFICIENCY, pinned rather than fixed. selectedTagId is in the
|
||||
// effect's dependency list purely so the auto-select can read it, so the
|
||||
// moment the first tag is selected the whole effect re-runs and the tag list
|
||||
// is fetched a second time on every page load.
|
||||
it('reads the tag list twice because selecting a tag re-runs the effect', async () => {
|
||||
await renderPage();
|
||||
// selectedTagId used to be in the effect's dependency list purely so the auto-select
|
||||
// could read it, so the moment the first tag was selected the whole effect re-ran and
|
||||
// the tag list was fetched a second time on every page load. It is read from a ref now.
|
||||
it('reads the tag list once even though the auto-select sets a tag', async () => {
|
||||
const harness = await renderPage();
|
||||
|
||||
expect(callsMatching((url) => url === TAGS_URL)).toHaveLength(2);
|
||||
expect(harness.result.current.selectedTagId).toBe('tag-audio');
|
||||
expect(callsMatching((url) => url === TAGS_URL)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('selects nothing when the project has no tags', async () => {
|
||||
|
||||
@@ -21,13 +21,13 @@ vi.mock('next/link', () => ({
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
/**
|
||||
* ACCESSIBILITY FINDING: the password field has no <label>, no aria-label and
|
||||
* no aria-labelledby, only a placeholder. A password input has no ARIA role
|
||||
* either, so there is no `getByRole` route to it at all. Reported, not papered
|
||||
* over: this helper documents that the placeholder is the only handle we have.
|
||||
* A password input has no ARIA role, so `getByRole` cannot reach it whatever the
|
||||
* markup does. `getByLabelText` can, and it only works because the field now has a
|
||||
* visually hidden <label> associated by id: it used to have no label, no aria-label and
|
||||
* no aria-labelledby, which left the placeholder as the only handle anything had.
|
||||
*/
|
||||
function passwordField() {
|
||||
return screen.getByPlaceholderText('Password');
|
||||
return screen.getByLabelText('Password');
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -177,14 +177,13 @@ describe('ShareLinkUnlock', () => {
|
||||
render(<ShareLinkUnlock videoId="vid1" />);
|
||||
|
||||
await userEvent.type(passwordField(), 'hunter2');
|
||||
// Capture the node first: while submitting, the label is swapped for a
|
||||
// spinner, which leaves the button with no accessible name to query by.
|
||||
// ACCESSIBILITY FINDING, reported rather than worked around.
|
||||
const submit = screen.getByRole('button', { name: 'Continue' });
|
||||
await userEvent.click(submit);
|
||||
|
||||
expect(submit).toBeDisabled();
|
||||
expect(submit).toHaveAccessibleName('');
|
||||
// The spinner that replaces the label carries a visually hidden name, so the button
|
||||
// stays findable and announceable while it submits.
|
||||
expect(submit).toHaveAccessibleName('Unlocking');
|
||||
|
||||
release({ ok: true, json: () => Promise.resolve({}) });
|
||||
await waitFor(() => expect(replace).toHaveBeenCalledTimes(1));
|
||||
|
||||
Reference in New Issue
Block a user