Skip to content

[LiveComponent] Update CSRF token after component request #2022

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 1 commit into from
Sep 12, 2024
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
2 changes: 2 additions & 0 deletions src/LiveComponent/assets/dist/Backend/Backend.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface BackendInterface {
}, files: {
[key: string]: FileList;
}): BackendRequest;
updateCsrfToken(csrfToken: string): void;
}
export interface BackendAction {
name: string;
Expand All @@ -28,4 +29,5 @@ export default class implements BackendInterface {
}, files: {
[key: string]: FileList;
}): BackendRequest;
updateCsrfToken(csrfToken: string): void;
}
3 changes: 2 additions & 1 deletion src/LiveComponent/assets/dist/Backend/RequestBuilder.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { BackendAction, ChildrenFingerprints } from './Backend';
export default class {
private url;
private method;
private readonly csrfToken;
private csrfToken;
constructor(url: string, method?: 'get' | 'post', csrfToken?: string | null);
buildRequest(props: any, actions: BackendAction[], updated: {
[key: string]: any;
Expand All @@ -15,4 +15,5 @@ export default class {
fetchOptions: RequestInit;
};
private willDataFitInUrl;
updateCsrfToken(csrfToken: string): void;
}
9 changes: 9 additions & 0 deletions src/LiveComponent/assets/dist/live_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2052,6 +2052,9 @@ class Component {
return response;
}
this.processRerender(html, backendResponse);
if (this.element.dataset.liveCsrfValue) {
this.backend.updateCsrfToken(this.element.dataset.liveCsrfValue);
}
this.backendRequest = null;
thisPromiseResolve(backendResponse);
if (this.isRequestPending) {
Expand Down Expand Up @@ -2325,6 +2328,9 @@ class RequestBuilder {
const urlEncodedJsonData = new URLSearchParams(propsJson + updatedJson + childrenJson + propsFromParentJson).toString();
return (urlEncodedJsonData + params.toString()).length < 1500;
}
updateCsrfToken(csrfToken) {
this.csrfToken = csrfToken;
}
}

class Backend {
Expand All @@ -2335,6 +2341,9 @@ class Backend {
const { url, fetchOptions } = this.requestBuilder.buildRequest(props, actions, updated, children, updatedPropsFromParent, files);
return new BackendRequest(fetch(url, fetchOptions), actions.map((backendAction) => backendAction.name), Object.keys(updated));
}
updateCsrfToken(csrfToken) {
this.requestBuilder.updateCsrfToken(csrfToken);
}
}

class StimulusElementDriver {
Expand Down
5 changes: 5 additions & 0 deletions src/LiveComponent/assets/src/Backend/Backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface BackendInterface {
updatedPropsFromParent: { [key: string]: any },
files: { [key: string]: FileList }
): BackendRequest;
updateCsrfToken(csrfToken: string): void;
}

export interface BackendAction {
Expand Down Expand Up @@ -52,4 +53,8 @@ export default class implements BackendInterface {
Object.keys(updated)
);
}

updateCsrfToken(csrfToken: string) {
this.requestBuilder.updateCsrfToken(csrfToken);
}
}
6 changes: 5 additions & 1 deletion src/LiveComponent/assets/src/Backend/RequestBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { BackendAction, ChildrenFingerprints } from './Backend';
export default class {
private url: string;
private method: 'get' | 'post';
private readonly csrfToken: string | null;
private csrfToken: string | null;

constructor(url: string, method: 'get' | 'post' = 'post', csrfToken: string | null = null) {
this.url = url;
Expand Down Expand Up @@ -117,4 +117,8 @@ export default class {
// if the URL gets remotely close to 2000 chars, it may not fit
return (urlEncodedJsonData + params.toString()).length < 1500;
}

updateCsrfToken(csrfToken: string) {
this.csrfToken = csrfToken;
}
}
5 changes: 5 additions & 0 deletions src/LiveComponent/assets/src/Component/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,11 @@ export default class Component {

this.processRerender(html, backendResponse);

// Store updated csrf token
if (this.element.dataset.liveCsrfValue) {
this.backend.updateCsrfToken(this.element.dataset.liveCsrfValue);
}

// finally resolve this promise
this.backendRequest = null;
thisPromiseResolve(backendResponse);
Expand Down
19 changes: 19 additions & 0 deletions src/LiveComponent/assets/test/controller/render.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,4 +630,23 @@ describe('LiveController rendering Tests', () => {
// verify the selectedIndex of the select option 2 is 0
expect(selectOption2.selectedIndex).toBe(0);
});

it('backend will have a new csrf token', async () => {
const test = await createTest(
{},
(data: any) => `
<div ${initComponent(data)} data-live-csrf-value="${data.csrf}">
</div>
`
);

test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change csrf token
data.csrf = 'Hello';
});

await test.component.render();

expect(test.mockedBackend.csrfToken).toEqual('Hello');
});
});
6 changes: 6 additions & 0 deletions src/LiveComponent/assets/test/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ class FunctionalTest {
class MockedBackend implements BackendInterface {
private expectedMockedAjaxCalls: Array<MockedAjaxCall> = [];

public csrfToken: string | null = null;

addMockedAjaxCall(mock: MockedAjaxCall) {
this.expectedMockedAjaxCalls.push(mock);
}
Expand Down Expand Up @@ -139,6 +141,10 @@ class MockedBackend implements BackendInterface {
return matchedMock.createBackendRequest();
}

updateCsrfToken(csrfToken: string) {
this.csrfToken = csrfToken;
}

getExpectedMockedAjaxCalls(): Array<MockedAjaxCall> {
return this.expectedMockedAjaxCalls;
}
Expand Down