Skip to content

Beautiful Open-Source Form Builder

Fix anonymous respondent PDF downloads (#1329)

Julien Nahum151f0c432c63
diff --git a/api/app/Http/Controllers/Forms/PublicFormController.php b/api/app/Http/Controllers/Forms/PublicFormController.php
index 6cdc53858..b348ef60e 100644
--- a/api/app/Http/Controllers/Forms/PublicFormController.php
+++ b/api/app/Http/Controllers/Forms/PublicFormController.php
@@ -160,7 +160,17 @@ class PublicFormController extends Controller
if ($formSubmissionProcessor->shouldProcessSynchronously($form)) {
$job->handle();
- $encodedSubmissionId = SubmissionUrlService::getSubmissionIdentifierById($form, $job->getSubmissionId());
+ $submission = $form->submissions()->findOrFail($job->getSubmissionId());
+ $encodedSubmissionId = SubmissionUrlService::getSubmissionIdentifier($submission);
+
+ // Only the completed submission response grants its respondent a download URL.
+ // The owner-only signed-URL endpoint remains authenticated.
+ if ($form->pdf_download_enabled) {
+ $template = $form->pdfTemplates()->find($form->pdf_template_id);
+ if ($template) {
+ $pdfDownloadUrl = SubmissionUrlService::buildPdfDownloadUrl($form, $template, $submission);
+ }
+ }
// Update submission data with generated values for redirect URL
$submissionData = $job->getProcessedData();
@@ -172,6 +182,7 @@ class PublicFormController extends Controller
return $this->success(array_merge([
'message' => 'Form submission saved.',
'submission_id' => $encodedSubmissionId ?? null,
+ 'pdf_download_url' => $pdfDownloadUrl ?? null,
'is_first_submission' => $isFirstSubmission,
], $formSubmissionProcessor->getRedirectData($form, $submissionData)));
}
diff --git a/api/app/Http/Controllers/Pdf/PdfGenerateController.php b/api/app/Http/Controllers/Pdf/PdfGenerateController.php
index baf586efd..c168a0bbe 100644
--- a/api/app/Http/Controllers/Pdf/PdfGenerateController.php
+++ b/api/app/Http/Controllers/Pdf/PdfGenerateController.php
@@ -172,17 +172,7 @@ class PdfGenerateController extends Controller
PdfTemplate $template,
FormSubmission $submission
): string {
- $submissionId = SubmissionUrlService::getSubmissionIdentifier($submission);
-
- return URL::temporaryPublicSignedRoute(
- 'open.forms.pdf-templates.download-submission',
- now()->addHours(24),
- [
- 'form' => $form->id,
- 'pdfTemplate' => $template->id,
- 'submission_id' => $submissionId,
- ]
- );
+ return SubmissionUrlService::buildPdfDownloadUrl($form, $template, $submission);
}
}
diff --git a/api/app/Service/Forms/SubmissionUrlService.php b/api/app/Service/Forms/SubmissionUrlService.php
index bb95520c9..806086cb9 100644
--- a/api/app/Service/Forms/SubmissionUrlService.php
+++ b/api/app/Service/Forms/SubmissionUrlService.php
@@ -4,6 +4,8 @@ namespace App\Service\Forms;
use App\Models\Forms\Form;
use App\Models\Forms\FormSubmission;
+use App\Models\PdfTemplate;
+use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
class SubmissionUrlService
@@ -65,6 +67,24 @@ class SubmissionUrlService
->first();
}
+ /**
+ * Issue a bounded download capability for one submission and template.
+ */
+ public static function buildPdfDownloadUrl(Form $form, PdfTemplate $template, FormSubmission $submission): string
+ {
+ abort_unless($template->form_id === $form->id && $submission->form_id === $form->id, 404);
+
+ return URL::temporaryPublicSignedRoute(
+ 'open.forms.pdf-templates.download-submission',
+ now()->addHours(24),
+ [
+ 'form' => $form->id,
+ 'pdfTemplate' => $template->id,
+ 'submission_id' => self::getSubmissionIdentifier($submission),
+ ]
+ );
+ }
+
/**
* Build the edit URL for a submission.
*
diff --git a/api/tests/Feature/Integrations/Pdf/RespondentPdfDownloadTest.php b/api/tests/Feature/Integrations/Pdf/RespondentPdfDownloadTest.php
new file mode 100644
index 000000000..30b74c9d5
--- /dev/null
+++ b/api/tests/Feature/Integrations/Pdf/RespondentPdfDownloadTest.php
@@ -0,0 +1,106 @@
+<?php
+
+use App\Models\PdfTemplate;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Facades\Storage;
+
+beforeEach(function () {
+ Storage::fake('local');
+ Queue::fake();
+ $owner = $this->createProUser();
+ $workspace = $this->createUserWorkspace($owner);
+ $this->pdfForm = $this->createForm($owner, $workspace, ['pdf_download_enabled' => true]);
+
+ $pdf = new \setasign\Fpdi\Fpdi();
+ $pdf->AddPage();
+ $pdf->SetFont('Helvetica', '', 12);
+ $pdf->Cell(0, 10, 'Respondent PDF regression');
+ $content = $pdf->Output('S');
+ $path = "pdf-templates/{$this->pdfForm->id}/respondent.pdf";
+ Storage::put($path, $content);
+ $this->pdfTemplate = PdfTemplate::create([
+ 'form_id' => $this->pdfForm->id,
+ 'name' => 'Respondent PDF',
+ 'filename' => 'respondent.pdf',
+ 'original_filename' => 'respondent.pdf',
+ 'file_path' => $path,
+ 'file_size' => strlen($content),
+ 'page_count' => 1,
+ 'zone_mappings' => [],
+ 'filename_pattern' => PdfTemplate::DEFAULT_FILENAME_PATTERN,
+ ]);
+ $this->pdfForm->update(['pdf_template_id' => $this->pdfTemplate->id]);
+});
+
+function submitForRespondentPdf($test)
+{
+ return $test->postJson(
+ route('forms.answer', $test->pdfForm->slug),
+ $test->generateFormSubmissionData($test->pdfForm)
+ )->assertSuccessful();
+}
+
+it('lets an anonymous respondent download the PDF returned by their completed submission', function () {
+ $response = submitForRespondentPdf($this);
+ $url = $response->json('pdf_download_url');
+ $submission = $this->pdfForm->submissions()->sole();
+
+ expect($url)->toBeString()->toContain($submission->public_id)->toContain('signature=');
+ $this->assertGuest();
+ $download = $this->get($url)->assertSuccessful()->assertHeader('content-type', 'application/pdf');
+ expect($download->streamedContent())->toStartWith('%PDF-');
+
+ // Knowing the submission UUID cannot mint additional unbounded download links.
+ $this->getJson(route('open.forms.pdf-templates.submission.signed-url', [
+ 'form' => $this->pdfForm,
+ 'pdfTemplate' => $this->pdfTemplate,
+ 'submission_id' => $submission->public_id,
+ ]))->assertUnauthorized();
+});
+
+it('rejects switching the signed URL to a different submission', function () {
+ $url = submitForRespondentPdf($this)->json('pdf_download_url');
+ $original = $this->pdfForm->submissions()->sole();
+ $other = $this->pdfForm->submissions()->create(['data' => []]);
+ $otherId = \App\Service\Forms\SubmissionUrlService::getSubmissionIdentifier($other);
+
+ $this->get(str_replace($original->public_id, $otherId, $url))->assertForbidden();
+});
+
+it('rejects the respondent download after its 24 hour lifetime', function () {
+ $url = submitForRespondentPdf($this)->json('pdf_download_url');
+ $this->travel(25)->hours();
+
+ $this->get($url)->assertForbidden();
+});
+
+it('does not issue a download URL when PDF download is disabled', function () {
+ $this->pdfForm->update(['pdf_download_enabled' => false]);
+
+ submitForRespondentPdf($this)->assertJsonPath('pdf_download_url', null);
+});
+
+it('does not issue a URL for a PDF template belonging to another form', function () {
+ $other = $this->createForm($this->pdfForm->creator, $this->pdfForm->workspace);
+ $this->pdfTemplate->update(['form_id' => $other->id]);
+
+ submitForRespondentPdf($this)->assertJsonPath('pdf_download_url', null);
+});
+
+it('does not issue a download URL for a partial draft', function () {
+ $business = $this->createBusinessUser();
+ $workspace = $this->createUserWorkspace($business);
+ $this->pdfForm->update([
+ 'creator_id' => $business->id,
+ 'workspace_id' => $workspace->id,
+ 'enable_partial_submissions' => true,
+ ]);
+ $this->pdfForm->refresh();
+ $data = $this->generateFormSubmissionData($this->pdfForm);
+ $data['is_partial'] = true;
+
+ $this->postJson(route('forms.answer', $this->pdfForm->slug), $data)
+ ->assertSuccessful()
+ ->assertJsonStructure(['submission_hash'])
+ ->assertJsonMissingPath('pdf_download_url');
+});
diff --git a/client/components/open/forms/OpenCompleteForm.vue b/client/components/open/forms/OpenCompleteForm.vue
index d72f970e0..71a7185ba 100644
--- a/client/components/open/forms/OpenCompleteForm.vue
+++ b/client/components/open/forms/OpenCompleteForm.vue
@@ -100,7 +100,7 @@
v-if="pdfDownloadEnabled"
:form="form"
icon="i-heroicons-document-arrow-down"
- :loading="pdfDownloading"
+ native-type="button"
@click="downloadPdf"
>
{{ form.pdf_download_button_text || t('forms.buttons.download_pdf', 'Download PDF') }}
@@ -151,7 +151,6 @@ import Loader from '~/components/global/Loader.vue'
import { tailwindcssPaletteGenerator } from '~/lib/colors.js'
import { useRouter } from 'vue-router'
import { clearFormatterCache } from '~/components/forms/components/FormSubmissionFormatter.js'
-import { formsApi } from '~/api'
import { clearLoadedMentionCache } from '~/lib/forms/mention-parser-loader.js'
const OpenForm = defineAsyncComponent(() => import('./OpenForm.vue'))
@@ -184,6 +183,7 @@ const passwordForm = useForm({ password: null })
// Removed unused hidePasswordDisabledMsg (was always false and unused)
// submission_id is a public UUID identifier
const submissionId = ref(route.query.submission_id || null)
+const pdfDownloadUrl = ref(null)
// Match SSR markup while keeping browser-only draft restoration non-interactive.
const isRestoringDraft = ref(!!props.form.auto_save && !submissionId.value)
const submittedData = ref(null)
@@ -431,6 +431,7 @@ const triggerSubmit = () => {
}).then(result => {
if (result) {
submittedData.value = formManager.form.data()
+ pdfDownloadUrl.value = result.pdf_download_url || null
if (result?.submission_id) {
submissionId.value = result.submission_id
@@ -480,6 +481,7 @@ const restart = async () => {
if (!formManager) return
submittedData.value = null
submissionId.value = null
+ pdfDownloadUrl.value = null
const urlParams = getUrlParams()
// Determine if we should clear the form completely for a fresh start
@@ -506,39 +508,16 @@ const restart = async () => {
emit('restarted', true)
}
-// PDF Download functionality
-const pdfDownloading = ref(false)
-const pdfDownloadEnabled = computed(() => {
- // Check if PDF download is enabled and we have a submission ID
- if (!props.form.pdf_download_enabled || !submissionId.value) return false
-
- // Check if we have a PDF template ID
- const templateId = props.form.pdf_template_id
- return !!templateId
-})
+// The completed submission response supplies a signed URL for this respondent.
+const pdfDownloadEnabled = computed(() => (
+ !!props.form.pdf_download_enabled && !!pdfDownloadUrl.value
+))
-const downloadPdf = async () => {
- if (!pdfDownloadEnabled.value || pdfDownloading.value) return
-
- const templateId = props.form.pdf_template_id
- if (!templateId) return
-
- pdfDownloading.value = true
- try {
- // Get signed URL from backend
- const response = await formsApi.pdfTemplates.getSubmissionSignedUrl(
- props.form.id,
- templateId,
- submissionId.value
- )
- // Open signed URL in new tab to trigger download
- window.open(response.url, '_blank')
- } catch (error) {
- console.error('PDF download failed:', error)
- alert.error('Failed to download PDF. Please try again.')
- } finally {
- pdfDownloading.value = false
- }
+const downloadPdf = () => {
+ if (!pdfDownloadEnabled.value) return
+
+ // Keep navigation synchronous with the click to avoid popup blocking.
+ window.open(pdfDownloadUrl.value, '_blank', 'noopener,noreferrer')
}
const editSubmission = () => {
diff --git a/client/test/nuxt/respondent-pdf-download.spec.ts b/client/test/nuxt/respondent-pdf-download.spec.ts
new file mode 100644
index 000000000..60399fdd7
--- /dev/null
+++ b/client/test/nuxt/respondent-pdf-download.spec.ts
@@ -0,0 +1,117 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { flushPromises } from '@vue/test-utils'
+import { mountSuspended } from '@nuxt/test-utils/runtime'
+import OpenCompleteForm from '~/components/open/forms/OpenCompleteForm.vue'
+
+const { submit, restart, ownerSignedUrl } = vi.hoisted(() => ({
+ submit: vi.fn(),
+ restart: vi.fn().mockResolvedValue(undefined),
+ ownerSignedUrl: vi.fn(),
+}))
+
+vi.mock('vue-i18n', () => ({
+ useI18n: () => ({ t: (key, fallback) => fallback || key, setLocale: vi.fn() }),
+}))
+vi.mock('~/composables/useForm', () => ({ useForm: () => ({ password: null }) }))
+vi.mock('~/composables/useAlert', () => ({ useAlert: () => ({ error: vi.fn() }) }))
+vi.mock('~/pages/index.vue', () => ({ default: { template: '<div />' } }))
+
+vi.mock('~/api', () => ({
+ formsApi: { pdfTemplates: { getSubmissionSignedUrl: ownerSignedUrl } },
+}))
+vi.mock('~/lib/forms/composables/useFormManager', async () => {
+ const { ref } = await import('vue')
+ return {
+ useFormManager: () => ({
+ initialize: vi.fn().mockResolvedValue(undefined),
+ form: { data: () => ({ name: 'TEST' }) },
+ state: { isProcessing: false },
+ strategy: ref({ display: { showFormCleanings: false, showFontLink: false }, admin: {} }),
+ structure: ref(null),
+ pendingSubmission: { enabled: ref(false) },
+ submit,
+ restart,
+ setDarkMode: vi.fn(),
+ updateConfig: vi.fn(),
+ }),
+ }
+})
+vi.mock('~/components/open/forms/OpenForm.vue', () => ({
+ default: {
+ emits: ['submit'],
+ template: '<div><button data-test="submit" @click="$emit(\'submit\')">Submit</button><slot name="after-submit" /></div>',
+ },
+}))
+vi.mock('~/components/forms/components/FormSubmissionFormatter.js', () => ({ clearFormatterCache: vi.fn() }))
+vi.mock('~/lib/forms/mention-parser-loader.js', () => ({ clearLoadedMentionCache: vi.fn() }))
+
+async function mountForm() {
+ return mountSuspended(OpenCompleteForm, {
+ route: '/__support_pdf_download',
+ props: {
+ form: { id: 4, slug: 'pdf-test', pdf_download_enabled: true, pdf_template_id: 3, language: 'en', re_fillable: true },
+ },
+ global: {
+ stubs: {
+ OpenForm: {
+ name: 'OpenForm',
+ emits: ['submit'],
+ template: '<div><button data-test="submit" @click="$emit(\'submit\')">Submit</button><slot name="after-submit" /></div>',
+ },
+ UAlert: true,
+ OpenFormButton: { template: '<button><slot /></button>' },
+ VTransition: { template: '<div><slot /></div>' },
+ },
+ },
+ })
+}
+
+describe('respondent PDF download', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
+ vi.spyOn(window, 'open').mockImplementation(() => null)
+ })
+
+ it('uses the signed URL from the submission response without calling an owner endpoint', async () => {
+ const signedUrl = 'https://api.example.test/open/forms/4/pdf-templates/3/submissions/test/download?expires=99&signature=test'
+ submit.mockResolvedValue({ submission_id: 'test', pdf_download_url: signedUrl })
+ const wrapper = await mountForm()
+ await wrapper.get('[data-test="submit"]').trigger('click')
+ await flushPromises()
+
+ const button = wrapper.findAll('button').find(button => button.text() === 'Download PDF')
+ expect(button).toBeDefined()
+ await button!.trigger('click')
+
+ expect(window.open).toHaveBeenCalledExactlyOnceWith(signedUrl, '_blank', 'noopener,noreferrer')
+ expect(ownerSignedUrl).not.toHaveBeenCalled()
+ wrapper.unmount()
+ }, 5000)
+
+ it('does not offer an unusable download when the server supplied no signed URL', async () => {
+ submit.mockResolvedValue({ submission_id: 'test', pdf_download_url: null })
+ const wrapper = await mountForm()
+ await wrapper.get('[data-test="submit"]').trigger('click')
+ await flushPromises()
+
+ expect(wrapper.findAll('button').some(button => button.text() === 'Download PDF')).toBe(false)
+ expect(ownerSignedUrl).not.toHaveBeenCalled()
+ wrapper.unmount()
+ }, 5000)
+ it('clears the previous respondent download when restarting the form', async () => {
+ submit.mockResolvedValue({ submission_id: 'test', pdf_download_url: 'https://api.example.test/download?signature=test' })
+ const wrapper = await mountForm()
+ await wrapper.get('[data-test="submit"]').trigger('click')
+ await flushPromises()
+ expect(wrapper.findAll('button').some(button => button.text() === 'Download PDF')).toBe(true)
+
+ await wrapper.findAll('button').find(button => button.text() === 'forms.buttons.re_fill')!.trigger('click')
+ await flushPromises()
+
+ expect(restart).toHaveBeenCalledOnce()
+ expect(wrapper.findAll('button').some(button => button.text() === 'Download PDF')).toBe(false)
+ wrapper.unmount()
+ }, 5000)
+
+})
diff --git a/docs/front-end/forms.mdx b/docs/front-end/forms.mdx
index a3bed4be5..a8392ed73 100644
--- a/docs/front-end/forms.mdx
+++ b/docs/front-end/forms.mdx
@@ -382,4 +382,14 @@ const handleLogin = () => {
<Check>
**Validation**: Combine client-side validation (required, email, etc.) with server-side validation for the best user experience.
-</Check>
\ No newline at end of file
+</Check>
+
+## Respondent PDF Downloads
+
+When PDF download is enabled and a template is selected for a public form, the completed submission response includes `pdf_download_url`. The URL is signed for that submission and template and expires after 24 hours. A partial draft, disabled PDF download, or a template outside the form does not receive a download URL.
+
+The completion screen uses this URL directly when the respondent clicks **Download PDF**. It does not call the authenticated template `signed-url` endpoint, which remains restricted to form administrators. Open the supplied URL synchronously from the click handler to avoid browser popup blocking.
+
+Keep the signed URL in the completion screen's memory and clear it when restarting the form. Treat it as a temporary credential: do not log it or place it in analytics events. Reopening a form with only a submission UUID does not grant a fresh download URL. Administrators can generate a new URL through the authenticated endpoint when needed.
+
+Deploy the API response addition and its completion-screen consumer together. An expired link, a failure to generate a PDF, and a missing email notification are separate issues; a successful signed download does not prove email delivery.