test(album,cabana,pier,surf,admin): add Phase 37 test suites and fail-closed check-phase37.sh gate
This commit is contained in:
134
admin/tests/form/MediaFinderField.test.ts
Normal file
134
admin/tests/form/MediaFinderField.test.ts
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||||
|
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { setBundle } from '../../src/app/i18n'
|
||||||
|
import MediaFinderField from '../../src/components/form/fields/MediaFinderField.vue'
|
||||||
|
import { langFixture } from '../fixtures/typed'
|
||||||
|
import { API, mockApi, resetState } from '../helpers'
|
||||||
|
|
||||||
|
const bundle = {
|
||||||
|
...langFixture.data,
|
||||||
|
'backend::lang.media.finder_choose': { other: 'Choose media' },
|
||||||
|
'backend::lang.media.finder_change': { other: 'Change' },
|
||||||
|
'backend::lang.media.finder_add': { other: 'Add media' },
|
||||||
|
'backend::lang.media.finder_remove': { other: 'Remove' },
|
||||||
|
'backend::lang.media.finder_empty': { other: 'No media selected' },
|
||||||
|
'backend::lang.media.picker_title': { other: 'Select media' },
|
||||||
|
'backend::lang.media.picker_select': { other: 'Select' },
|
||||||
|
'backend::lang.media.picker_select_count': { other: 'Select (:count)' },
|
||||||
|
'backend::lang.media.folders': { other: 'Folders' },
|
||||||
|
'backend::lang.media.all_files': { other: 'All files' },
|
||||||
|
'backend::lang.media.root_folder': { other: 'Unfiled' },
|
||||||
|
'backend::lang.media.search_placeholder': { other: 'Search media…' },
|
||||||
|
'backend::lang.form.cancel': { other: 'Cancel' },
|
||||||
|
}
|
||||||
|
|
||||||
|
const sampleItem = {
|
||||||
|
id: 21,
|
||||||
|
short_id: 'xyz123456789',
|
||||||
|
file_name: 'cover.png',
|
||||||
|
slug: 'cover',
|
||||||
|
content_type: 'image/png',
|
||||||
|
file_size: 2048,
|
||||||
|
sha256: 'b'.repeat(64),
|
||||||
|
alt: 'Cover',
|
||||||
|
title: 'Cover',
|
||||||
|
caption: '',
|
||||||
|
url: '/media/xyz123456789/cover.png',
|
||||||
|
thumb_url: '/media/xyz123456789/cover-480w.webp',
|
||||||
|
is_image: true,
|
||||||
|
variants: [],
|
||||||
|
created_at: '2026-11-27T10:00:00Z',
|
||||||
|
updated_at: '2026-11-27T10:00:00Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetState()
|
||||||
|
setBundle(bundle, 'en')
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
document.body.innerHTML = ''
|
||||||
|
})
|
||||||
|
|
||||||
|
enableAutoUnmount(afterEach)
|
||||||
|
|
||||||
|
describe('MediaFinderField', () => {
|
||||||
|
it('supports single image selection and clearing', async () => {
|
||||||
|
mockApi({
|
||||||
|
[`GET ${API}/media/folders`]: { body: { data: [] } },
|
||||||
|
[`GET ${API}/media/items`]: {
|
||||||
|
body: {
|
||||||
|
data: [sampleItem],
|
||||||
|
meta: { page: 1, per_page: 24, total: 1, last_page: 1, can_manage: false },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(MediaFinderField, {
|
||||||
|
props: {
|
||||||
|
field: { name: 'cover', label: 'Cover', type: 'mediafinder', mode: 'image' },
|
||||||
|
modelValue: null,
|
||||||
|
controlId: 'field-cover',
|
||||||
|
},
|
||||||
|
attachTo: document.body,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(wrapper.text()).toContain('No media selected')
|
||||||
|
|
||||||
|
await wrapper.find('[data-mediafinder-choose]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
document.querySelector<HTMLElement>('[data-media-item-id="21"]')!.click()
|
||||||
|
await flushPromises()
|
||||||
|
document.querySelector<HTMLButtonElement>('[data-media-picker-confirm]')!.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['/media/xyz123456789/cover.png'])
|
||||||
|
|
||||||
|
await wrapper.setProps({ modelValue: '/media/xyz123456789/cover.png' })
|
||||||
|
expect(wrapper.find('img').attributes('src')).toBe('/media/xyz123456789/cover.png')
|
||||||
|
|
||||||
|
await wrapper.find('[data-mediafinder-remove]').trigger('click')
|
||||||
|
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual([null])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('supports multiple mode with add and remove', async () => {
|
||||||
|
mockApi({
|
||||||
|
[`GET ${API}/media/folders`]: { body: { data: [] } },
|
||||||
|
[`GET ${API}/media/items`]: {
|
||||||
|
body: {
|
||||||
|
data: [sampleItem],
|
||||||
|
meta: { page: 1, per_page: 24, total: 1, last_page: 1, can_manage: false },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(MediaFinderField, {
|
||||||
|
props: {
|
||||||
|
field: { name: 'docs', label: 'Docs', type: 'mediafinder', mode: 'file', multiple: true },
|
||||||
|
modelValue: ['/media/aaa123456789/guide.pdf'],
|
||||||
|
controlId: 'field-docs',
|
||||||
|
},
|
||||||
|
attachTo: document.body,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(wrapper.findAll('[data-mediafinder-item]')).toHaveLength(1)
|
||||||
|
expect(wrapper.text()).toContain('guide.pdf')
|
||||||
|
|
||||||
|
// Add second item via picker
|
||||||
|
await wrapper.find('[data-mediafinder-choose]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
document.querySelector<HTMLElement>('[data-media-item-id="21"]')!.click()
|
||||||
|
await flushPromises()
|
||||||
|
document.querySelector<HTMLButtonElement>('[data-media-picker-confirm]')!.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual([
|
||||||
|
['/media/aaa123456789/guide.pdf', '/media/xyz123456789/cover.png'],
|
||||||
|
])
|
||||||
|
|
||||||
|
// Remove first item
|
||||||
|
await wrapper.find('[data-mediafinder-remove]').trigger('click')
|
||||||
|
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual([[]])
|
||||||
|
})
|
||||||
|
})
|
||||||
202
admin/tests/media/MediaBrowser.test.ts
Normal file
202
admin/tests/media/MediaBrowser.test.ts
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { setBundle } from '../../src/app/i18n'
|
||||||
|
import MediaBrowser from '../../src/components/media/MediaBrowser.vue'
|
||||||
|
import { langFixture } from '../fixtures/typed'
|
||||||
|
import { API, mockApi, resetState } from '../helpers'
|
||||||
|
|
||||||
|
const bundle = {
|
||||||
|
...langFixture.data,
|
||||||
|
'backend::lang.media.title': { other: 'Media' },
|
||||||
|
'backend::lang.media.folders': { other: 'Folders' },
|
||||||
|
'backend::lang.media.all_files': { other: 'All files' },
|
||||||
|
'backend::lang.media.root_folder': { other: 'Unfiled' },
|
||||||
|
'backend::lang.media.new_folder': { other: 'New folder' },
|
||||||
|
'backend::lang.media.rename_folder': { other: 'Rename folder' },
|
||||||
|
'backend::lang.media.delete_folder': { other: 'Delete folder' },
|
||||||
|
'backend::lang.media.folder_name': { other: 'Folder name' },
|
||||||
|
'backend::lang.media.folder_name_placeholder': { other: 'e.g. Press kit' },
|
||||||
|
'backend::lang.media.folder_created': { other: 'Folder created.' },
|
||||||
|
'backend::lang.media.folder_deleted': { other: 'Folder deleted.' },
|
||||||
|
'backend::lang.media.folder_delete_confirm': { other: 'Delete folder “:name”?' },
|
||||||
|
'backend::lang.media.folder_not_empty': { other: 'Move or delete all items first.' },
|
||||||
|
'backend::lang.media.search_placeholder': { other: 'Search media…' },
|
||||||
|
'backend::lang.media.filter_all': { other: 'All' },
|
||||||
|
'backend::lang.media.filter_images': { other: 'Images' },
|
||||||
|
'backend::lang.media.filter_files': { other: 'Files' },
|
||||||
|
'backend::lang.media.view_grid': { other: 'Grid view' },
|
||||||
|
'backend::lang.media.view_list': { other: 'List view' },
|
||||||
|
'backend::lang.media.upload': { other: 'Upload' },
|
||||||
|
'backend::lang.media.uploading': { other: 'Uploading…' },
|
||||||
|
'backend::lang.media.upload_done': { other: 'Uploaded.' },
|
||||||
|
'backend::lang.media.inspector_title': { other: 'Details' },
|
||||||
|
'backend::lang.media.copy_url': { other: 'Copy URL' },
|
||||||
|
'backend::lang.media.alt': { other: 'Alt text' },
|
||||||
|
'backend::lang.media.item_title': { other: 'Title' },
|
||||||
|
'backend::lang.media.caption': { other: 'Caption' },
|
||||||
|
'backend::lang.media.folder': { other: 'Folder' },
|
||||||
|
'backend::lang.media.no_folder': { other: 'Unfiled' },
|
||||||
|
'backend::lang.media.save': { other: 'Save' },
|
||||||
|
'backend::lang.media.saved': { other: 'Saved.' },
|
||||||
|
'backend::lang.media.delete': { other: 'Delete' },
|
||||||
|
'backend::lang.media.deleted': { other: 'Deleted.' },
|
||||||
|
'backend::lang.media.delete_confirm_title': { other: 'Delete media item?' },
|
||||||
|
'backend::lang.media.delete_confirm_body': {
|
||||||
|
other: 'Deleting “:name” permanently removes the file and breaks any published URLs referencing it.',
|
||||||
|
},
|
||||||
|
'backend::lang.media.empty_title': { other: 'No media files yet' },
|
||||||
|
'backend::lang.media.empty_body': { other: 'Upload images or files to get started.' },
|
||||||
|
'backend::lang.form.create': { other: 'Create' },
|
||||||
|
'backend::lang.form.save': { other: 'Save' },
|
||||||
|
'backend::lang.form.cancel': { other: 'Cancel' },
|
||||||
|
'backend::lang.form.close': { other: 'Close' },
|
||||||
|
}
|
||||||
|
|
||||||
|
const sampleFolder = {
|
||||||
|
id: 10,
|
||||||
|
name: 'Editorial',
|
||||||
|
slug: 'editorial',
|
||||||
|
created_at: '2026-11-27T10:00:00Z',
|
||||||
|
updated_at: '2026-11-27T10:00:00Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
const sampleItem = {
|
||||||
|
id: 1,
|
||||||
|
short_id: 'abc123456789',
|
||||||
|
folder_id: 10,
|
||||||
|
file_name: 'hero.png',
|
||||||
|
slug: 'hero',
|
||||||
|
content_type: 'image/png',
|
||||||
|
file_size: 4096,
|
||||||
|
width: 1200,
|
||||||
|
height: 800,
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
alt: 'Hero banner',
|
||||||
|
title: 'Hero',
|
||||||
|
caption: 'Front page',
|
||||||
|
url: '/media/abc123456789/hero.png',
|
||||||
|
thumb_url: '/media/abc123456789/hero-480w.webp',
|
||||||
|
srcset: '/media/abc123456789/hero-480w.webp 480w, /media/abc123456789/hero-960w.webp 960w',
|
||||||
|
is_image: true,
|
||||||
|
variants: [
|
||||||
|
{ width: 480, height: 320, url: '/media/abc123456789/hero-480w.webp', size: 1024, content_type: 'image/webp' },
|
||||||
|
],
|
||||||
|
created_at: '2026-11-27T10:00:00Z',
|
||||||
|
updated_at: '2026-11-27T10:00:00Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetState()
|
||||||
|
setBundle(bundle, 'en')
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
document.body.innerHTML = ''
|
||||||
|
})
|
||||||
|
|
||||||
|
enableAutoUnmount(afterEach)
|
||||||
|
|
||||||
|
describe('MediaBrowser', () => {
|
||||||
|
it('loads folders and items, navigates folders, and toggles grid/list view', async () => {
|
||||||
|
const calls = mockApi({
|
||||||
|
[`GET ${API}/media/folders`]: { body: { data: [sampleFolder] } },
|
||||||
|
[`GET ${API}/media/items`]: {
|
||||||
|
body: {
|
||||||
|
data: [sampleItem],
|
||||||
|
meta: { page: 1, per_page: 24, total: 1, last_page: 1, can_manage: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(MediaBrowser, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(wrapper.find('[data-media-folder="10"]').text()).toContain('Editorial')
|
||||||
|
expect(wrapper.find('[data-media-grid]').exists()).toBe(true)
|
||||||
|
|
||||||
|
// Switch to list view
|
||||||
|
await wrapper.find('[data-media-view="list"]').trigger('click')
|
||||||
|
expect(wrapper.find('[data-media-list]').exists()).toBe(true)
|
||||||
|
|
||||||
|
// Navigate into folder 10
|
||||||
|
await wrapper.find('[data-media-folder="10"]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(calls.some((c) => c.url.includes('folder_id=10'))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('debounces search input before requesting /media/items', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
const calls = mockApi({
|
||||||
|
[`GET ${API}/media/folders`]: { body: { data: [] } },
|
||||||
|
[`GET ${API}/media/items`]: {
|
||||||
|
body: {
|
||||||
|
data: [sampleItem],
|
||||||
|
meta: { page: 1, per_page: 24, total: 1, last_page: 1, can_manage: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(MediaBrowser, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
const initialItemCalls = calls.filter((c) => c.url.includes('/media/items')).length
|
||||||
|
|
||||||
|
const input = wrapper.find('[data-media-search]')
|
||||||
|
await input.setValue('hero')
|
||||||
|
await input.trigger('input')
|
||||||
|
expect(calls.filter((c) => c.url.includes('/media/items')).length).toBe(initialItemCalls)
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(310)
|
||||||
|
await flushPromises()
|
||||||
|
expect(calls.some((c) => c.url.includes('q=hero'))).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uploads a file, edits metadata in inspector, and warns before hard delete', async () => {
|
||||||
|
const calls = mockApi({
|
||||||
|
[`GET ${API}/media/folders`]: { body: { data: [sampleFolder] } },
|
||||||
|
[`GET ${API}/media/items`]: {
|
||||||
|
body: {
|
||||||
|
data: [sampleItem],
|
||||||
|
meta: { page: 1, per_page: 24, total: 1, last_page: 1, can_manage: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[`POST ${API}/media/items`]: {
|
||||||
|
status: 201,
|
||||||
|
body: { data: { ...sampleItem, id: 2, file_name: 'uploaded.png' } },
|
||||||
|
},
|
||||||
|
[`PUT ${API}/media/items/1`]: {
|
||||||
|
body: { data: { ...sampleItem, alt: 'Updated alt', title: 'Updated title' } },
|
||||||
|
},
|
||||||
|
[`DELETE ${API}/media/items/1`]: {
|
||||||
|
body: { data: { deleted: true } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(MediaBrowser, { attachTo: document.body })
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// Open inspector for item 1
|
||||||
|
await wrapper.find('[data-media-item-id="1"]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.find('[data-media-inspector]').exists()).toBe(true)
|
||||||
|
|
||||||
|
// Edit alt + title and save
|
||||||
|
await wrapper.find('[data-media-inspector-alt]').setValue('Updated alt')
|
||||||
|
await wrapper.find('[data-media-inspector-title]').setValue('Updated title')
|
||||||
|
await wrapper.find('[data-media-save]').trigger('submit')
|
||||||
|
await flushPromises()
|
||||||
|
expect(calls.some((c) => c.method === 'PUT' && c.url.includes('/media/items/1'))).toBe(true)
|
||||||
|
|
||||||
|
// Click Delete -> confirmation dialog warns about breaking published URLs (D-12)
|
||||||
|
await wrapper.find('[data-media-delete]').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
expect(document.body.textContent).toContain('breaks any published URLs referencing it')
|
||||||
|
|
||||||
|
// Confirm delete
|
||||||
|
const confirmBtn = document.querySelector<HTMLButtonElement>('[data-confirm-dialog] [data-action="confirm"]')
|
||||||
|
expect(confirmBtn).not.toBeNull()
|
||||||
|
confirmBtn!.click()
|
||||||
|
await flushPromises()
|
||||||
|
expect(calls.some((c) => c.method === 'DELETE' && c.url.includes('/media/items/1'))).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
134
admin/tests/media/MediaPickerModal.test.ts
Normal file
134
admin/tests/media/MediaPickerModal.test.ts
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||||
|
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||||
|
import { setBundle } from '../../src/app/i18n'
|
||||||
|
import MediaPickerModal from '../../src/components/media/MediaPickerModal.vue'
|
||||||
|
import { langFixture } from '../fixtures/typed'
|
||||||
|
import { API, mockApi, resetState } from '../helpers'
|
||||||
|
|
||||||
|
const bundle = {
|
||||||
|
...langFixture.data,
|
||||||
|
'backend::lang.media.picker_title': { other: 'Select media' },
|
||||||
|
'backend::lang.media.picker_select': { other: 'Select' },
|
||||||
|
'backend::lang.media.picker_select_count': { other: 'Select (:count)' },
|
||||||
|
'backend::lang.media.alt': { other: 'Alt text' },
|
||||||
|
'backend::lang.media.folders': { other: 'Folders' },
|
||||||
|
'backend::lang.media.all_files': { other: 'All files' },
|
||||||
|
'backend::lang.media.root_folder': { other: 'Unfiled' },
|
||||||
|
'backend::lang.media.search_placeholder': { other: 'Search media…' },
|
||||||
|
'backend::lang.form.cancel': { other: 'Cancel' },
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemA = {
|
||||||
|
id: 11,
|
||||||
|
short_id: 'aaa111222333',
|
||||||
|
file_name: 'alpha.png',
|
||||||
|
slug: 'alpha',
|
||||||
|
content_type: 'image/png',
|
||||||
|
file_size: 1024,
|
||||||
|
sha256: 'a'.repeat(64),
|
||||||
|
alt: 'Alpha alt',
|
||||||
|
title: 'Alpha',
|
||||||
|
caption: '',
|
||||||
|
url: '/media/aaa111222333/alpha.png',
|
||||||
|
thumb_url: '/media/aaa111222333/alpha-480w.webp',
|
||||||
|
is_image: true,
|
||||||
|
variants: [],
|
||||||
|
created_at: '2026-11-27T10:00:00Z',
|
||||||
|
updated_at: '2026-11-27T10:00:00Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemB = {
|
||||||
|
...itemA,
|
||||||
|
id: 12,
|
||||||
|
short_id: 'bbb111222333',
|
||||||
|
file_name: 'beta.pdf',
|
||||||
|
slug: 'beta',
|
||||||
|
content_type: 'application/pdf',
|
||||||
|
alt: '',
|
||||||
|
title: 'Beta PDF',
|
||||||
|
url: '/media/bbb111222333/beta.pdf',
|
||||||
|
thumb_url: '',
|
||||||
|
is_image: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
resetState()
|
||||||
|
setBundle(bundle, 'en')
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
document.body.innerHTML = ''
|
||||||
|
})
|
||||||
|
|
||||||
|
enableAutoUnmount(afterEach)
|
||||||
|
|
||||||
|
describe('MediaPickerModal', () => {
|
||||||
|
it('filters by defaultFolder slug and emits selected item with alt text', async () => {
|
||||||
|
const calls = mockApi({
|
||||||
|
[`GET ${API}/media/folders`]: {
|
||||||
|
body: {
|
||||||
|
data: [
|
||||||
|
{ id: 7, name: 'Journal', slug: 'journal', created_at: '', updated_at: '' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[`GET ${API}/media/items`]: {
|
||||||
|
body: {
|
||||||
|
data: [itemA],
|
||||||
|
meta: { page: 1, per_page: 24, total: 1, last_page: 1, can_manage: false },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(MediaPickerModal, {
|
||||||
|
props: { open: true, mode: 'image', defaultFolder: 'journal', showAlt: true },
|
||||||
|
attachTo: document.body,
|
||||||
|
})
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(calls.some((c) => c.url.includes('folder_id=7'))).toBe(true)
|
||||||
|
|
||||||
|
const confirm = document.querySelector<HTMLButtonElement>('[data-media-picker-confirm]')
|
||||||
|
expect(confirm?.disabled).toBe(true)
|
||||||
|
|
||||||
|
document.querySelector<HTMLElement>('[data-media-item-id="11"]')!.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(confirm?.disabled).toBe(false)
|
||||||
|
const altInput = document.querySelector<HTMLInputElement>('[data-media-picker-alt]')
|
||||||
|
expect(altInput?.value).toBe('Alpha alt')
|
||||||
|
|
||||||
|
confirm!.click()
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.emitted('select')?.at(-1)).toEqual([{ items: [itemA], alt: 'Alpha alt' }])
|
||||||
|
expect(wrapper.emitted('update:open')?.at(-1)).toEqual([false])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('supports multiple selection in file mode', async () => {
|
||||||
|
mockApi({
|
||||||
|
[`GET ${API}/media/folders`]: { body: { data: [] } },
|
||||||
|
[`GET ${API}/media/items`]: {
|
||||||
|
body: {
|
||||||
|
data: [itemA, itemB],
|
||||||
|
meta: { page: 1, per_page: 24, total: 2, last_page: 1, can_manage: false },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const wrapper = mount(MediaPickerModal, {
|
||||||
|
props: { open: true, mode: 'file', multiple: true },
|
||||||
|
attachTo: document.body,
|
||||||
|
})
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
document.querySelector<HTMLElement>('[data-media-item-id="11"]')!.click()
|
||||||
|
document.querySelector<HTMLElement>('[data-media-item-id="12"]')!.click()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const confirm = document.querySelector<HTMLButtonElement>('[data-media-picker-confirm]')
|
||||||
|
expect(confirm?.textContent).toContain('2')
|
||||||
|
confirm!.click()
|
||||||
|
await flushPromises()
|
||||||
|
expect(wrapper.emitted('select')?.at(-1)).toEqual([{ items: [itemA, itemB], alt: '' }])
|
||||||
|
})
|
||||||
|
})
|
||||||
610
modules/album/album_postgres_test.go
Normal file
610
modules/album/album_postgres_test.go
Normal file
@@ -0,0 +1,610 @@
|
|||||||
|
package album_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/album"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||||
|
"github.com/go-gormigrate/gormigrate/v2"
|
||||||
|
_ "github.com/jackc/pgx/v5/stdlib"
|
||||||
|
"github.com/testcontainers/testcontainers-go"
|
||||||
|
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||||
|
"gocloud.dev/blob"
|
||||||
|
"gocloud.dev/blob/memblob"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
pgTestDSN string
|
||||||
|
pgTestTerm func()
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
flag.Parse()
|
||||||
|
if !testing.Short() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||||
|
ctr, err := postgres.Run(ctx,
|
||||||
|
"postgres:16-alpine",
|
||||||
|
postgres.WithDatabase("album_test"),
|
||||||
|
postgres.WithUsername("album"),
|
||||||
|
postgres.WithPassword("album"),
|
||||||
|
postgres.BasicWaitStrategies(),
|
||||||
|
)
|
||||||
|
cancel()
|
||||||
|
if err == nil {
|
||||||
|
dsnCtx, dsnCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
|
dsn, dsnErr := ctr.ConnectionString(dsnCtx, "sslmode=disable")
|
||||||
|
dsnCancel()
|
||||||
|
if dsnErr == nil {
|
||||||
|
pgTestDSN = dsn
|
||||||
|
pgTestTerm = func() {
|
||||||
|
_ = testcontainers.TerminateContainer(ctr)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_ = testcontainers.TerminateContainer(ctr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
code := m.Run()
|
||||||
|
if pgTestTerm != nil {
|
||||||
|
pgTestTerm()
|
||||||
|
}
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func openAlbumDB(t *testing.T) *gorm.DB {
|
||||||
|
t.Helper()
|
||||||
|
if testing.Short() {
|
||||||
|
t.Skip("requires testcontainers postgres")
|
||||||
|
}
|
||||||
|
if pgTestDSN == "" {
|
||||||
|
t.Fatal("postgres testcontainer did not start; ensure Docker is reachable")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
raw, err := sql.Open("pgx", pgTestDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sql.Open: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = raw.Close() })
|
||||||
|
gdb, err := lagoon.Use(ctx, raw)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("lagoon.Use: %v", err)
|
||||||
|
}
|
||||||
|
if err := lagoon.Migrate(gdb, nil); err != nil {
|
||||||
|
t.Fatalf("lagoon.Migrate: %v", err)
|
||||||
|
}
|
||||||
|
// Reset album and system_files tables between tests for isolation.
|
||||||
|
if err := gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders, system_files RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||||
|
t.Fatalf("truncate tables: %v", err)
|
||||||
|
}
|
||||||
|
return gdb
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMigrationsUpDown(t *testing.T) {
|
||||||
|
gdb := openAlbumDB(t)
|
||||||
|
|
||||||
|
// Run album migrations inside an isolated schema so rolling them down and
|
||||||
|
// back up does not disturb the shared public tables.
|
||||||
|
const schema = "album_mig_test"
|
||||||
|
if err := gdb.Exec("DROP SCHEMA IF EXISTS " + schema + " CASCADE").Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := gdb.Exec("CREATE SCHEMA " + schema).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = gdb.Exec("DROP SCHEMA IF EXISTS " + schema + " CASCADE").Error })
|
||||||
|
|
||||||
|
tx := gdb.Begin()
|
||||||
|
defer tx.Rollback()
|
||||||
|
if err := tx.Exec("SET LOCAL search_path TO " + schema).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
opts := gormigrate.DefaultOptions
|
||||||
|
opts.TableName = "album_mig_history"
|
||||||
|
m := gormigrate.New(tx, opts, album.Migrations)
|
||||||
|
if err := m.Migrate(); err != nil {
|
||||||
|
t.Fatalf("Migrate up: %v", err)
|
||||||
|
}
|
||||||
|
for _, tbl := range []string{album.FoldersTable, album.ItemsTable, album.UploadTokensTable} {
|
||||||
|
if !tx.Migrator().HasTable(tbl) {
|
||||||
|
t.Fatalf("expected table %s after Migrate up", tbl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Roll back every migration down to the beginning.
|
||||||
|
for range album.Migrations {
|
||||||
|
if err := m.RollbackLast(); err != nil {
|
||||||
|
t.Fatalf("RollbackLast: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, tbl := range []string{album.FoldersTable, album.ItemsTable, album.UploadTokensTable} {
|
||||||
|
if tx.Migrator().HasTable(tbl) {
|
||||||
|
t.Fatalf("expected table %s to be dropped after rollback", tbl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-apply cleanly.
|
||||||
|
if err := m.Migrate(); err != nil {
|
||||||
|
t.Fatalf("re-Migrate up: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFolderCRUDAndNonEmptyDelete(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gdb := openAlbumDB(t)
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
svc := album.NewService(nil)
|
||||||
|
|
||||||
|
root, err := svc.CreateFolder(ctx, gdb, "Press Kit", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateFolder root: %v", err)
|
||||||
|
}
|
||||||
|
if root.Slug != "press-kit" {
|
||||||
|
t.Fatalf("root.Slug = %q, want press-kit", root.Slug)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureFolder is idempotent.
|
||||||
|
ensured, err := svc.EnsureFolder(ctx, gdb, "press-kit", "Press Kit", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("EnsureFolder: %v", err)
|
||||||
|
}
|
||||||
|
if ensured.ID != root.ID {
|
||||||
|
t.Fatalf("EnsureFolder created duplicate id %d != %d", ensured.ID, root.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duplicate sibling slug fails unique index.
|
||||||
|
if _, err := svc.CreateFolder(ctx, gdb, "Press Kit", nil); err == nil {
|
||||||
|
t.Fatal("expected duplicate sibling folder error")
|
||||||
|
}
|
||||||
|
|
||||||
|
child, err := svc.CreateFolder(ctx, gdb, "Logos", &root.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateFolder child: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cycle prevention: root cannot become a child of its own descendant.
|
||||||
|
if _, err := svc.UpdateFolder(ctx, gdb, root.ID, "", &child.ID, true); !errors.Is(err, album.ErrInvalidFolder) {
|
||||||
|
t.Fatalf("cycle UpdateFolder err = %v, want ErrInvalidFolder", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deleting a folder with a child folder returns ErrFolderNotEmpty.
|
||||||
|
if err := svc.DeleteFolder(ctx, gdb, root.ID); !errors.Is(err, album.ErrFolderNotEmpty) {
|
||||||
|
t.Fatalf("DeleteFolder with child err = %v, want ErrFolderNotEmpty", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload an item into child folder -> deleting child returns ErrFolderNotEmpty.
|
||||||
|
item, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "logo.png",
|
||||||
|
Body: bytes.NewReader(encodeTestPNG(t, makeTestPNG(t, 100, 100))),
|
||||||
|
FolderID: &child.ID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Upload into child: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.DeleteFolder(ctx, gdb, child.ID); !errors.Is(err, album.ErrFolderNotEmpty) {
|
||||||
|
t.Fatalf("DeleteFolder with item err = %v, want ErrFolderNotEmpty", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move item to root, delete child, then delete root.
|
||||||
|
if _, err := svc.UpdateItem(ctx, gdb, item.ID, album.UpdatePatch{ClearFolder: true}); err != nil {
|
||||||
|
t.Fatalf("UpdateItem ClearFolder: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.DeleteFolder(ctx, gdb, child.ID); err != nil {
|
||||||
|
t.Fatalf("DeleteFolder empty child: %v", err)
|
||||||
|
}
|
||||||
|
if err := svc.DeleteFolder(ctx, gdb, root.ID); err != nil {
|
||||||
|
t.Fatalf("DeleteFolder empty root: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUploadAndNoDedup(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gdb := openAlbumDB(t)
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
svc := album.NewService(nil)
|
||||||
|
|
||||||
|
pngBytes := encodeTestPNG(t, makeTestPNG(t, 1200, 600))
|
||||||
|
sum := sha256.Sum256(pngBytes)
|
||||||
|
wantSHA := hex.EncodeToString(sum[:])
|
||||||
|
|
||||||
|
first, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "Hero Photo.PNG",
|
||||||
|
Body: bytes.NewReader(pngBytes),
|
||||||
|
Alt: "Hero",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Upload first: %v", err)
|
||||||
|
}
|
||||||
|
if first.SHA256 != wantSHA {
|
||||||
|
t.Fatalf("first.SHA256 = %q, want %q", first.SHA256, wantSHA)
|
||||||
|
}
|
||||||
|
if first.Width == nil || *first.Width != 1200 || first.Height == nil || *first.Height != 600 {
|
||||||
|
t.Fatalf("dimensions = %v x %v, want 1200x600", first.Width, first.Height)
|
||||||
|
}
|
||||||
|
if len(first.Variants) != 2 {
|
||||||
|
t.Fatalf("variants = %d, want 2 (480w, 960w)", len(first.Variants))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Uploading identical bytes again must NOT deduplicate: distinct row & blob key.
|
||||||
|
second, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "Hero Photo.PNG",
|
||||||
|
Body: bytes.NewReader(pngBytes),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Upload second: %v", err)
|
||||||
|
}
|
||||||
|
if second.ID == first.ID || second.ShortID == first.ShortID || second.BlobKey == first.BlobKey {
|
||||||
|
t.Fatalf("duplicate upload was deduplicated: first=%+v second=%+v", first, second)
|
||||||
|
}
|
||||||
|
if second.SHA256 != wantSHA {
|
||||||
|
t.Fatalf("second.SHA256 = %q, want %q", second.SHA256, wantSHA)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Non-image PDF upload stores Content-Disposition: attachment and zero variants.
|
||||||
|
pdf, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "manual.pdf",
|
||||||
|
Body: bytes.NewReader([]byte("%PDF-1.4\nhello world")),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Upload pdf: %v", err)
|
||||||
|
}
|
||||||
|
if len(pdf.Variants) != 0 {
|
||||||
|
t.Fatalf("pdf variants = %d, want 0", len(pdf.Variants))
|
||||||
|
}
|
||||||
|
attrs, err := bucket.Attributes(ctx, pdf.BlobKey)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("bucket.Attributes(pdf): %v", err)
|
||||||
|
}
|
||||||
|
if attrs.ContentDisposition != "attachment" {
|
||||||
|
t.Fatalf("pdf ContentDisposition = %q, want attachment", attrs.ContentDisposition)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disallowed types (SVG, HTML, JS) and fake PNG rejected with no DB row.
|
||||||
|
badInputs := []album.UploadInput{
|
||||||
|
{FileName: "vector.svg", Body: strings.NewReader(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`)},
|
||||||
|
{FileName: "page.html", Body: strings.NewReader(`<html><body>hi</body></html>`)},
|
||||||
|
{FileName: "app.js", Body: strings.NewReader(`alert(1)`)},
|
||||||
|
{FileName: "fake.png", Body: strings.NewReader(`<html>not a png</html>`)},
|
||||||
|
}
|
||||||
|
for _, in := range badInputs {
|
||||||
|
if _, err := svc.Upload(ctx, gdb, bucket, in); err == nil {
|
||||||
|
t.Errorf("Upload(%q) unexpectedly succeeded", in.FileName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Oversized upload returns ErrTooLarge.
|
||||||
|
if _, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "big.pdf",
|
||||||
|
Body: bytes.NewReader(append([]byte("%PDF-1.4\n"), bytes.Repeat([]byte("x"), 2048)...)),
|
||||||
|
MaxBytes: 512,
|
||||||
|
}); !errors.Is(err, album.ErrTooLarge) {
|
||||||
|
t.Fatalf("oversized Upload err = %v, want ErrTooLarge", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConsumeUploadTokenSingleUse(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gdb := openAlbumDB(t)
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: t.TempDir()})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := backpack.New(cfg)
|
||||||
|
sqlDB, err := gdb.DB()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := app.Publish[*blob.Bucket](bucket); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
svc, err := album.Install(app)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. PrepareUpload stores only SHA-256 hash, never plaintext token.
|
||||||
|
prep, err := svc.PrepareUpload(ctx, gdb, album.PrepareUploadInput{
|
||||||
|
CreatedBy: 7,
|
||||||
|
ExpectedFilename: "signed-photo.png",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PrepareUpload: %v", err)
|
||||||
|
}
|
||||||
|
var stored album.UploadToken
|
||||||
|
if err := gdb.First(&stored, prep.TokenID).Error; err != nil {
|
||||||
|
t.Fatalf("load upload token row: %v", err)
|
||||||
|
}
|
||||||
|
if stored.TokenHash == prep.Token || len(stored.TokenHash) != 64 {
|
||||||
|
t.Fatalf("stored TokenHash = %q, want 64-char sha256 hash distinct from plaintext", stored.TokenHash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Concurrent consumption allows exactly one winner.
|
||||||
|
const workers = 6
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var wins int
|
||||||
|
var mu sync.Mutex
|
||||||
|
wg.Add(workers)
|
||||||
|
for i := 0; i < workers; i++ {
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
if _, cErr := svc.ConsumeUploadToken(ctx, gdb, prep.Token); cErr == nil {
|
||||||
|
mu.Lock()
|
||||||
|
wins++
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
if wins != 1 {
|
||||||
|
t.Fatalf("concurrent ConsumeUploadToken wins = %d, want 1", wins)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Replay returns ErrInvalidUploadToken.
|
||||||
|
if _, err := svc.ConsumeUploadToken(ctx, gdb, prep.Token); !errors.Is(err, album.ErrInvalidUploadToken) {
|
||||||
|
t.Fatalf("replay ConsumeUploadToken err = %v, want ErrInvalidUploadToken", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Expired token returns ErrInvalidUploadToken.
|
||||||
|
expired, err := svc.PrepareUpload(ctx, gdb, album.PrepareUploadInput{
|
||||||
|
CreatedBy: 7,
|
||||||
|
ExpectedFilename: "expired.png",
|
||||||
|
TTL: time.Minute,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := gdb.Model(&album.UploadToken{}).Where("id = ?", expired.TokenID).
|
||||||
|
Update("expires_at", time.Now().UTC().Add(-time.Minute)).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := svc.ConsumeUploadToken(ctx, gdb, expired.Token); !errors.Is(err, album.ErrInvalidUploadToken) {
|
||||||
|
t.Fatalf("expired ConsumeUploadToken err = %v, want ErrInvalidUploadToken", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. SignedUploadHandler end-to-end PUT succeeds once and rejects replay with 401.
|
||||||
|
prep2, err := svc.PrepareUpload(ctx, gdb, album.PrepareUploadInput{
|
||||||
|
CreatedBy: 7,
|
||||||
|
ExpectedFilename: "put-banner.png",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.Handle("PUT /media/upload/{token}", album.SignedUploadHandler(app, svc))
|
||||||
|
|
||||||
|
pngBytes := encodeTestPNG(t, makeTestPNG(t, 600, 300))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodPut, "/media/upload/"+prep2.Token+"?alt=Banner", bytes.NewReader(pngBytes))
|
||||||
|
mux.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("PUT signed upload status = %d, want 201, body=%s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var resp struct {
|
||||||
|
Data album.ItemResponse `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("decode response: %v", err)
|
||||||
|
}
|
||||||
|
if resp.Data.ID == 0 || resp.Data.Alt != "Banner" || len(resp.Data.Variants) != 1 {
|
||||||
|
t.Fatalf("unexpected ItemResponse: %+v", resp.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replay PUT returns 401.
|
||||||
|
rec2 := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec2, httptest.NewRequest(http.MethodPut, "/media/upload/"+prep2.Token, bytes.NewReader(pngBytes)))
|
||||||
|
if rec2.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("replay PUT status = %d, want 401", rec2.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteItemInTxAfterCommit(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gdb := openAlbumDB(t)
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
svc := album.NewService(nil)
|
||||||
|
|
||||||
|
item, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "sunset.png",
|
||||||
|
Body: bytes.NewReader(encodeTestPNG(t, makeTestPNG(t, 1000, 500))),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Upload: %v", err)
|
||||||
|
}
|
||||||
|
allKeys := item.AllBlobKeys()
|
||||||
|
if len(allKeys) != 3 { // original + 480w + 960w
|
||||||
|
t.Fatalf("AllBlobKeys = %v, want 3 keys", allKeys)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rolled-back transaction must NOT delete blobs or DB row.
|
||||||
|
sentinel := errors.New("abort tx")
|
||||||
|
err = lagoon.Transaction(ctx, gdb, func(txCtx context.Context, tx *gorm.DB) error {
|
||||||
|
keys, txErr := svc.DeleteItemInTx(txCtx, tx, item.ID)
|
||||||
|
if txErr != nil {
|
||||||
|
return txErr
|
||||||
|
}
|
||||||
|
lagoon.AfterCommit(txCtx, tx, func(acCtx context.Context, _ *gorm.DB) {
|
||||||
|
_ = album.DeleteBlobs(context.WithoutCancel(acCtx), bucket, keys)
|
||||||
|
})
|
||||||
|
return sentinel
|
||||||
|
})
|
||||||
|
if !errors.Is(err, sentinel) {
|
||||||
|
t.Fatalf("rolled-back Transaction err = %v, want sentinel", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.GetItem(ctx, gdb, item.ID); err != nil {
|
||||||
|
t.Fatalf("item missing after rollback: %v", err)
|
||||||
|
}
|
||||||
|
for _, k := range allKeys {
|
||||||
|
exists, bErr := bucket.Exists(ctx, k)
|
||||||
|
if bErr != nil || !exists {
|
||||||
|
t.Fatalf("blob %q was deleted on rollback (err=%v)", k, bErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Committed transaction deletes DB row + original + all WebP variant blobs.
|
||||||
|
err = lagoon.Transaction(ctx, gdb, func(txCtx context.Context, tx *gorm.DB) error {
|
||||||
|
keys, txErr := svc.DeleteItemInTx(txCtx, tx, item.ID)
|
||||||
|
if txErr != nil {
|
||||||
|
return txErr
|
||||||
|
}
|
||||||
|
lagoon.AfterCommit(txCtx, tx, func(acCtx context.Context, _ *gorm.DB) {
|
||||||
|
_ = album.DeleteBlobs(context.WithoutCancel(acCtx), bucket, keys)
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("committed Transaction: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := svc.GetItem(ctx, gdb, item.ID); !errors.Is(err, album.ErrNotFound) {
|
||||||
|
t.Fatalf("GetItem after commit err = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
for _, k := range allKeys {
|
||||||
|
exists, bErr := bucket.Exists(ctx, k)
|
||||||
|
if bErr != nil {
|
||||||
|
t.Fatalf("bucket.Exists(%q): %v", k, bErr)
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
t.Fatalf("blob %q still exists after committed delete", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetItemsByShortIDsAndListFilters(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gdb := openAlbumDB(t)
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
svc := album.NewService(nil)
|
||||||
|
|
||||||
|
folder, err := svc.CreateFolder(ctx, gdb, "Journal", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
imgItem, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "cover.png",
|
||||||
|
Body: bytes.NewReader(encodeTestPNG(t, makeTestPNG(t, 600, 400))),
|
||||||
|
FolderID: &folder.ID,
|
||||||
|
Title: "Cover Art",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pdfItem, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||||
|
FileName: "report.pdf",
|
||||||
|
Body: bytes.NewReader([]byte("%PDF-1.4\ncontent")),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
byID, err := svc.GetItemsByShortIDs(ctx, gdb, []string{imgItem.ShortID, pdfItem.ShortID, imgItem.ShortID, "nonexistent1"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetItemsByShortIDs: %v", err)
|
||||||
|
}
|
||||||
|
if len(byID) != 2 || byID[imgItem.ShortID].ID != imgItem.ID || byID[pdfItem.ShortID].ID != pdfItem.ID {
|
||||||
|
t.Fatalf("unexpected GetItemsByShortIDs result: %+v", byID)
|
||||||
|
}
|
||||||
|
|
||||||
|
imgs, total, err := svc.ListItems(ctx, gdb, album.ListFilter{Type: "image"})
|
||||||
|
if err != nil || total != 1 || len(imgs) != 1 || imgs[0].ID != imgItem.ID {
|
||||||
|
t.Fatalf("ListItems(type=image) = %d/%d err=%v", len(imgs), total, err)
|
||||||
|
}
|
||||||
|
files, total, err := svc.ListItems(ctx, gdb, album.ListFilter{Type: "file", RootOnly: true})
|
||||||
|
if err != nil || total != 1 || len(files) != 1 || files[0].ID != pdfItem.ID {
|
||||||
|
t.Fatalf("ListItems(type=file,root) = %d/%d err=%v", len(files), total, err)
|
||||||
|
}
|
||||||
|
bySHA, total, err := svc.ListItems(ctx, gdb, album.ListFilter{SHA256: imgItem.SHA256})
|
||||||
|
if err != nil || total != 1 || len(bySHA) != 1 || bySHA[0].ID != imgItem.ID {
|
||||||
|
t.Fatalf("ListItems(sha256) = %d/%d err=%v", len(bySHA), total, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updating metadata & folder never changes short_id, blob_key, or public URL.
|
||||||
|
origURL := imgItem.PublicURL(nil)
|
||||||
|
newAlt := "Updated alt"
|
||||||
|
updated, err := svc.UpdateItem(ctx, gdb, imgItem.ID, album.UpdatePatch{Alt: &newAlt, ClearFolder: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("UpdateItem: %v", err)
|
||||||
|
}
|
||||||
|
if updated.ShortID != imgItem.ShortID || updated.BlobKey != imgItem.BlobKey || updated.PublicURL(nil) != origURL {
|
||||||
|
t.Fatalf("UpdateItem mutated immutable URL/key: before=%q after=%q", origURL, updated.PublicURL(nil))
|
||||||
|
}
|
||||||
|
if updated.Alt != newAlt || updated.FolderID != nil {
|
||||||
|
t.Fatalf("UpdateItem did not apply patch: %+v", updated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBackfillMailImages(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
gdb := openAlbumDB(t)
|
||||||
|
|
||||||
|
title := "Brand Logo"
|
||||||
|
isPublic := true
|
||||||
|
legacy := attach.File{
|
||||||
|
DiskName: "abc123def456.png",
|
||||||
|
FileName: "brand-logo.png",
|
||||||
|
FileSize: 1024,
|
||||||
|
ContentType: "image/png",
|
||||||
|
Title: &title,
|
||||||
|
Field: "images",
|
||||||
|
AttachmentType: album.MailImageLibraryMorph,
|
||||||
|
IsPublic: &isPublic,
|
||||||
|
}
|
||||||
|
if err := gdb.Create(&legacy).Error; err != nil {
|
||||||
|
t.Fatalf("seed legacy mail image: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
n1, err := album.BackfillMailImages(ctx, gdb, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BackfillMailImages first run: %v", err)
|
||||||
|
}
|
||||||
|
if n1 != 1 {
|
||||||
|
t.Fatalf("BackfillMailImages first run = %d, want 1", n1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Second run is completely idempotent.
|
||||||
|
n2, err := album.BackfillMailImages(ctx, gdb, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BackfillMailImages second run: %v", err)
|
||||||
|
}
|
||||||
|
if n2 != 0 {
|
||||||
|
t.Fatalf("BackfillMailImages second run = %d, want 0", n2)
|
||||||
|
}
|
||||||
|
|
||||||
|
var item album.Item
|
||||||
|
if err := gdb.Where("legacy_file_id = ?", legacy.ID).First(&item).Error; err != nil {
|
||||||
|
t.Fatalf("load backfilled item: %v", err)
|
||||||
|
}
|
||||||
|
wantLegacyURL := attach.PublicURL(attach.BlobKey(legacy.DiskName))
|
||||||
|
if item.LegacyURL != wantLegacyURL || item.PublicURL(nil) != wantLegacyURL {
|
||||||
|
t.Fatalf("backfilled URL = %q / %q, want %q", item.LegacyURL, item.PublicURL(nil), wantLegacyURL)
|
||||||
|
}
|
||||||
|
if item.FolderID == nil {
|
||||||
|
t.Fatal("expected backfilled item to belong to virtual 'mail' folder")
|
||||||
|
}
|
||||||
|
}
|
||||||
327
modules/album/album_test.go
Normal file
327
modules/album/album_test.go
Normal file
@@ -0,0 +1,327 @@
|
|||||||
|
package album_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"hash/crc32"
|
||||||
|
"image"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/album"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach/webp"
|
||||||
|
"gocloud.dev/blob/memblob"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSlugAndShortID(t *testing.T) {
|
||||||
|
seen := make(map[string]struct{}, 64)
|
||||||
|
for i := 0; i < 64; i++ {
|
||||||
|
id, err := album.GenerateShortID()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateShortID: %v", err)
|
||||||
|
}
|
||||||
|
if len(id) != 12 {
|
||||||
|
t.Fatalf("short_id %q length = %d, want 12", id, len(id))
|
||||||
|
}
|
||||||
|
for _, r := range id {
|
||||||
|
if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'z')) {
|
||||||
|
t.Fatalf("short_id %q contains non-alphanumeric rune %q", id, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, dup := seen[id]; dup {
|
||||||
|
t.Fatalf("duplicate short_id %q", id)
|
||||||
|
}
|
||||||
|
seen[id] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
in string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"Hero Banner 2026!.png", "hero-banner-2026-png"},
|
||||||
|
{" ", "file"},
|
||||||
|
{"---___...", "file"},
|
||||||
|
{"Zażółć gęślą jaźń", "za-gl-ja"},
|
||||||
|
{"alpha---beta___gamma", "alpha-beta-gamma"},
|
||||||
|
{strings.Repeat("a", 120), strings.Repeat("a", 80)},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
if got := album.SanitizeSlug(tc.in); got != tc.want {
|
||||||
|
t.Errorf("SanitizeSlug(%q) = %q, want %q", tc.in, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWebPVariants(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
t.Run("large_image_generates_480_960_1600", func(t *testing.T) {
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
|
||||||
|
img := makeTestPNG(t, 2000, 1000)
|
||||||
|
variants, keys, err := album.GenerateWebPVariants(ctx, nil, bucket, "abc123456789", "hero", img, "png")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateWebPVariants: %v", err)
|
||||||
|
}
|
||||||
|
wantDims := [][2]int{{480, 240}, {960, 480}, {1600, 800}}
|
||||||
|
if len(variants) != len(wantDims) || len(keys) != len(wantDims) {
|
||||||
|
t.Fatalf("got %d variants (%d keys), want %d", len(variants), len(keys), len(wantDims))
|
||||||
|
}
|
||||||
|
for i, want := range wantDims {
|
||||||
|
v := variants[i]
|
||||||
|
if v.Width != want[0] || v.Height != want[1] {
|
||||||
|
t.Errorf("variant[%d] = %dx%d, want %dx%d", i, v.Width, v.Height, want[0], want[1])
|
||||||
|
}
|
||||||
|
if v.ContentType != webp.ContentType {
|
||||||
|
t.Errorf("variant[%d] content_type = %q, want %q", i, v.ContentType, webp.ContentType)
|
||||||
|
}
|
||||||
|
if v.Size <= 0 {
|
||||||
|
t.Errorf("variant[%d] size = %d, want > 0", i, v.Size)
|
||||||
|
}
|
||||||
|
exists, err := bucket.Exists(ctx, keys[i])
|
||||||
|
if err != nil || !exists {
|
||||||
|
t.Errorf("variant blob %q missing (err=%v)", keys[i], err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item := album.Item{
|
||||||
|
ShortID: "abc123456789",
|
||||||
|
BlobKey: "media/abc123456789/hero.png",
|
||||||
|
Variants: album.Variants(variants),
|
||||||
|
}
|
||||||
|
if got := len(item.AllBlobKeys()); got != 4 {
|
||||||
|
t.Fatalf("AllBlobKeys len = %d, want 4", got)
|
||||||
|
}
|
||||||
|
srcset := item.Srcset(nil)
|
||||||
|
for _, want := range []string{"480w", "960w", "1600w"} {
|
||||||
|
if !strings.Contains(srcset, want) {
|
||||||
|
t.Errorf("srcset %q missing %s", srcset, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("small_png_does_not_upscale", func(t *testing.T) {
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
|
||||||
|
img := makeTestPNG(t, 300, 150)
|
||||||
|
variants, keys, err := album.GenerateWebPVariants(ctx, nil, bucket, "abc123456789", "thumb", img, "png")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateWebPVariants: %v", err)
|
||||||
|
}
|
||||||
|
if len(variants) != 1 || len(keys) != 1 {
|
||||||
|
t.Fatalf("got %d variants, want 1 original-width webp", len(variants))
|
||||||
|
}
|
||||||
|
if variants[0].Width != 300 || variants[0].Height != 150 {
|
||||||
|
t.Fatalf("variant = %dx%d, want 300x150 (no upscaling)", variants[0].Width, variants[0].Height)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("small_webp_generates_zero_redundant_variants", func(t *testing.T) {
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
|
||||||
|
img := makeTestPNG(t, 300, 150)
|
||||||
|
variants, keys, err := album.GenerateWebPVariants(ctx, nil, bucket, "abc123456789", "icon", img, webp.Format)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateWebPVariants: %v", err)
|
||||||
|
}
|
||||||
|
if len(variants) != 0 || len(keys) != 0 {
|
||||||
|
t.Fatalf("small webp generated %d variants, want 0", len(variants))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStaticHandlerSecurity(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
|
||||||
|
pngBytes := encodeTestPNG(t, makeTestPNG(t, 16, 16))
|
||||||
|
if err := bucket.WriteAll(ctx, "media/abc123456789/photo.png", pngBytes, attach.UploadWriterOptions("image/png")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := bucket.WriteAll(ctx, "media/abc123456789/guide.pdf", []byte("%PDF-1.4\nhello"), attach.UploadWriterOptions("application/pdf")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
h := album.StaticHandler(bucket, "/assets")
|
||||||
|
|
||||||
|
t.Run("head_returns_headers_without_body", func(t *testing.T) {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodHead, "/assets/abc123456789/photo.png", nil))
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("HEAD status = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
if rec.Body.Len() != 0 {
|
||||||
|
t.Fatalf("HEAD body len = %d, want 0", rec.Body.Len())
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("Cache-Control"); got != album.MediaCacheControl {
|
||||||
|
t.Fatalf("Cache-Control = %q, want %q", got, album.MediaCacheControl)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
||||||
|
t.Fatalf("X-Content-Type-Options = %q", got)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("Content-Security-Policy"); got != album.MediaContentSecurityPolicy {
|
||||||
|
t.Fatalf("CSP = %q", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("non_get_method_returns_405", func(t *testing.T) {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/assets/abc123456789/photo.png", nil))
|
||||||
|
if rec.Code != http.StatusMethodNotAllowed {
|
||||||
|
t.Fatalf("POST status = %d, want 405", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("pdf_serves_as_attachment", func(t *testing.T) {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/assets/abc123456789/guide.pdf", nil))
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET pdf status = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("Content-Disposition"); got != "attachment" {
|
||||||
|
t.Fatalf("Content-Disposition = %q, want attachment", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("traversal_and_malformed_paths_rejected", func(t *testing.T) {
|
||||||
|
bad := []string{
|
||||||
|
"/assets",
|
||||||
|
"/assets/",
|
||||||
|
"/wrong/abc123456789/photo.png",
|
||||||
|
"/assets/abc123456789/../../etc/passwd",
|
||||||
|
"/assets/abc123456789/a\\b.png",
|
||||||
|
"/assets/abc123456789//photo.png",
|
||||||
|
"/assets/abc123456789/Photo.png",
|
||||||
|
}
|
||||||
|
for _, p := range bad {
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, p, nil))
|
||||||
|
if rec.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("GET %q status = %d, want 404", p, rec.Code)
|
||||||
|
}
|
||||||
|
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
|
||||||
|
t.Errorf("GET %q missing nosniff", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecompressionBombAndPolyglotGuards(t *testing.T) {
|
||||||
|
// Construct a valid PNG header claiming 20000x20000 pixels (400M > MaxImagePixels).
|
||||||
|
bomb := makeSyntheticPNGHeader(20000, 20000)
|
||||||
|
if attach.IsAllowedImage(bomb) {
|
||||||
|
t.Fatal("IsAllowedImage accepted 20000x20000 decompression bomb PNG")
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTML/SVG/JS bytes masquerading as .png must be rejected by IsAllowedImage.
|
||||||
|
polyglots := [][]byte{
|
||||||
|
[]byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`),
|
||||||
|
[]byte(`<!doctype html><html><body><script>alert(1)</script></body></html>`),
|
||||||
|
[]byte(`console.log("not a png")`),
|
||||||
|
}
|
||||||
|
for i, payload := range polyglots {
|
||||||
|
if attach.IsAllowedImage(payload) {
|
||||||
|
t.Errorf("polyglot[%d] unexpectedly accepted by IsAllowedImage", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal small PNG passes.
|
||||||
|
okPNG := encodeTestPNG(t, makeTestPNG(t, 32, 32))
|
||||||
|
if !attach.IsAllowedImage(okPNG) {
|
||||||
|
t.Fatal("valid 32x32 PNG rejected by IsAllowedImage")
|
||||||
|
}
|
||||||
|
var _ image.Image
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigAndInstallHelpers(t *testing.T) {
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: t.TempDir()})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("compass.Open: %v", err)
|
||||||
|
}
|
||||||
|
if got := album.MaxBytes(cfg); got != album.DefaultMaxBytes {
|
||||||
|
t.Fatalf("default MaxBytes = %d, want %d", got, album.DefaultMaxBytes)
|
||||||
|
}
|
||||||
|
if got := album.Base64MaxBytes(cfg); got != album.DefaultBase64MaxBytes {
|
||||||
|
t.Fatalf("default Base64MaxBytes = %d, want %d", got, album.DefaultBase64MaxBytes)
|
||||||
|
}
|
||||||
|
if got := album.PublicPathPrefix(cfg); got != album.DefaultPublicPathPrefix {
|
||||||
|
t.Fatalf("default PublicPathPrefix = %q, want %q", got, album.DefaultPublicPathPrefix)
|
||||||
|
}
|
||||||
|
if album.ServeEnabled(cfg) {
|
||||||
|
t.Fatal("ServeEnabled on empty config = true, want false")
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = cfg.Set(album.ConfigMaxBytes, 10<<20)
|
||||||
|
_ = cfg.Set(album.ConfigBase64MaxBytes, 2<<20)
|
||||||
|
_ = cfg.Set(album.ConfigPublicPathPrefix, "/cdn-media/")
|
||||||
|
_ = cfg.Set("storage.uploads.serve", true)
|
||||||
|
if got := album.MaxBytes(cfg); got != 10<<20 {
|
||||||
|
t.Fatalf("MaxBytes = %d, want %d", got, 10<<20)
|
||||||
|
}
|
||||||
|
if got := album.Base64MaxBytes(cfg); got != 2<<20 {
|
||||||
|
t.Fatalf("Base64MaxBytes = %d, want %d", got, 2<<20)
|
||||||
|
}
|
||||||
|
if got := album.PublicPathPrefix(cfg); got != "/cdn-media" {
|
||||||
|
t.Fatalf("PublicPathPrefix = %q, want /cdn-media", got)
|
||||||
|
}
|
||||||
|
if !album.ServeEnabled(cfg) {
|
||||||
|
t.Fatal("ServeEnabled should inherit storage.uploads.serve=true")
|
||||||
|
}
|
||||||
|
_ = cfg.Set(album.ConfigServe, false)
|
||||||
|
if album.ServeEnabled(cfg) {
|
||||||
|
t.Fatal("explicit media.serve=false must override storage.uploads.serve=true")
|
||||||
|
}
|
||||||
|
|
||||||
|
app := backpack.New(cfg)
|
||||||
|
svc1, err := album.Install(app)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Install: %v", err)
|
||||||
|
}
|
||||||
|
svc2, err := album.Install(app)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Install idempotent: %v", err)
|
||||||
|
}
|
||||||
|
if svc1 != svc2 {
|
||||||
|
t.Fatal("Install returned distinct *Service instances on second call")
|
||||||
|
}
|
||||||
|
gotSvc, ok := album.ServiceFrom(app)
|
||||||
|
if !ok || gotSvc != svc1 {
|
||||||
|
t.Fatal("ServiceFrom did not return installed *Service")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// makeSyntheticPNGHeader builds a minimal PNG byte sequence whose IHDR chunk
|
||||||
|
// declares the given width and height (for testing decompression-bomb guards).
|
||||||
|
func makeSyntheticPNGHeader(width, height uint32) []byte {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
// PNG signature
|
||||||
|
buf.Write([]byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a})
|
||||||
|
// IHDR chunk: 13 bytes payload
|
||||||
|
var ihdr [13]byte
|
||||||
|
binary.BigEndian.PutUint32(ihdr[0:4], width)
|
||||||
|
binary.BigEndian.PutUint32(ihdr[4:8], height)
|
||||||
|
ihdr[8] = 8 // bit depth
|
||||||
|
ihdr[9] = 6 // RGBA
|
||||||
|
var lenBuf [4]byte
|
||||||
|
binary.BigEndian.PutUint32(lenBuf[:], 13)
|
||||||
|
buf.Write(lenBuf[:])
|
||||||
|
buf.WriteString("IHDR")
|
||||||
|
buf.Write(ihdr[:])
|
||||||
|
crc := crc32.NewIEEE()
|
||||||
|
_, _ = crc.Write([]byte("IHDR"))
|
||||||
|
_, _ = crc.Write(ihdr[:])
|
||||||
|
var crcBuf [4]byte
|
||||||
|
binary.BigEndian.PutUint32(crcBuf[:], crc.Sum32())
|
||||||
|
buf.Write(crcBuf[:])
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
278
modules/cabana/media_postgres_test.go
Normal file
278
modules/cabana/media_postgres_test.go
Normal file
@@ -0,0 +1,278 @@
|
|||||||
|
package cabana_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/album"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||||
|
"gocloud.dev/blob"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mediaTestPNG(t *testing.T, w, h int) []byte {
|
||||||
|
t.Helper()
|
||||||
|
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||||
|
for y := 0; y < h; y++ {
|
||||||
|
for x := 0; x < w; x++ {
|
||||||
|
img.Set(x, y, color.RGBA{R: 120, G: 180, B: 220, A: 255})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := png.Encode(&buf, img); err != nil {
|
||||||
|
t.Fatalf("encode png: %v", err)
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
func mediaMultipartUpload(t *testing.T, h http.Handler, token string, data []byte, filename string, fields map[string]string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
var buf bytes.Buffer
|
||||||
|
mw := multipart.NewWriter(&buf)
|
||||||
|
fw, err := mw.CreateFormFile("file", filename)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := fw.Write(data); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for k, v := range fields {
|
||||||
|
if err := mw.WriteField(k, v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := mw.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/backend/api/v1/media/items", &buf)
|
||||||
|
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||||
|
if token != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
func mintPersonalToken(t *testing.T, env *mailEnv, jwtToken, name string, scopes []string) string {
|
||||||
|
t.Helper()
|
||||||
|
body := env.expect(t, http.StatusCreated, http.MethodPost, "/account/tokens", jwtToken, map[string]any{
|
||||||
|
"name": name,
|
||||||
|
"scopes": scopes,
|
||||||
|
})
|
||||||
|
tok, _ := dataOf(body)["token"].(string)
|
||||||
|
if tok == "" {
|
||||||
|
t.Fatalf("expected plaintext token in response: %v", body)
|
||||||
|
}
|
||||||
|
return tok
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaPermissionsMatrix(t *testing.T) {
|
||||||
|
env := newMailScreensEnv(t, nil)
|
||||||
|
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, viewerTok := env.admin(t, "media-viewer", false, `{"media.view_media":1}`)
|
||||||
|
_, managerTok := env.admin(t, "media-manager", false, `{"media.manage_media":1}`)
|
||||||
|
_, superTok := env.admin(t, "media-super", true, "")
|
||||||
|
_, noneTok := env.admin(t, "media-none", false, `{"acme.demo.access":1}`)
|
||||||
|
|
||||||
|
// Create a folder as manager so GET/PUT/DELETE have a target.
|
||||||
|
created := env.expect(t, http.StatusCreated, http.MethodPost, "/media/folders", managerTok, map[string]any{"name": "Campaigns"})
|
||||||
|
folderID := uint(dataOf(created)["id"].(float64))
|
||||||
|
|
||||||
|
// Viewer can read, cannot write.
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, "/media/folders", viewerTok, nil)
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", viewerTok, nil)
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/folders", viewerTok, map[string]any{"name": "Blocked"})
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodPut, fmt.Sprintf("/media/folders/%d", folderID), viewerTok, map[string]any{"name": "Blocked"})
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodDelete, fmt.Sprintf("/media/folders/%d", folderID), viewerTok, nil)
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/uploads/prepare", viewerTok, map[string]any{"filename": "x.png"})
|
||||||
|
if rec := mediaMultipartUpload(t, env.h, viewerTok, tinyPNG(), "v.png", nil); rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("viewer upload status = %d, want 403", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// None principal is denied read & write.
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodGet, "/media/folders", noneTok, nil)
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodGet, "/media/items", noneTok, nil)
|
||||||
|
|
||||||
|
// Manager and superuser can read and write.
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", managerTok, nil)
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", superTok, nil)
|
||||||
|
|
||||||
|
// Verify media permissions have no default role grants.
|
||||||
|
var granted int64
|
||||||
|
if err := env.gdb.Raw(`SELECT COUNT(*) FROM backend_user_roles WHERE permissions LIKE '%media.%' AND code NOT LIKE 'code-%'`).Scan(&granted).Error; err != nil || granted != 0 {
|
||||||
|
t.Fatalf("default roles granted media permissions: %d err=%v", granted, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaTokenScopes(t *testing.T) {
|
||||||
|
env := newMailScreensEnv(t, nil)
|
||||||
|
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, superTok := env.admin(t, "media-scope-super", true, "")
|
||||||
|
readToken := mintPersonalToken(t, env, superTok, "media-read-tok", []string{"media:read"})
|
||||||
|
writeToken := mintPersonalToken(t, env, superTok, "media-write-tok", []string{"media"})
|
||||||
|
|
||||||
|
// media:read allows GET, blocks POST/PUT/DELETE.
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, "/media/folders", readToken, nil)
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", readToken, nil)
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/folders", readToken, map[string]any{"name": "Denied"})
|
||||||
|
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/uploads/prepare", readToken, map[string]any{"filename": "x.png"})
|
||||||
|
|
||||||
|
// media scope allows GET, POST, PUT, DELETE.
|
||||||
|
folder := env.expect(t, http.StatusCreated, http.MethodPost, "/media/folders", writeToken, map[string]any{"name": "Scoped"})
|
||||||
|
fid := uint(dataOf(folder)["id"].(float64))
|
||||||
|
env.expect(t, http.StatusOK, http.MethodPut, fmt.Sprintf("/media/folders/%d", fid), writeToken, map[string]any{"name": "Scoped Renamed"})
|
||||||
|
env.expect(t, http.StatusOK, http.MethodDelete, fmt.Sprintf("/media/folders/%d", fid), writeToken, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaUploadLifecycleAndAfterCommitDelete(t *testing.T) {
|
||||||
|
env := newMailScreensEnv(t, nil)
|
||||||
|
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, managerTok := env.admin(t, "media-life-mgr", false, `{"media.manage_media":1}`)
|
||||||
|
bucket, ok := env.app.Lookup[*blob.Bucket]()
|
||||||
|
if !ok || bucket == nil {
|
||||||
|
t.Fatal("expected *blob.Bucket on app")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Create folder and upload a 1000x500 PNG via multipart.
|
||||||
|
folder := env.expect(t, http.StatusCreated, http.MethodPost, "/media/folders", managerTok, map[string]any{"name": "Heroes"})
|
||||||
|
fid := uint(dataOf(folder)["id"].(float64))
|
||||||
|
|
||||||
|
rec := mediaMultipartUpload(t, env.h, managerTok, mediaTestPNG(t, 1000, 500), "Hero Banner.png", map[string]string{
|
||||||
|
"folder_id": fmt.Sprintf("%d", fid),
|
||||||
|
"alt": "Initial alt",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("multipart upload status = %d, want 201, body=%s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var upResp struct {
|
||||||
|
Data cabana.AdminMediaItem `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &upResp); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
item := upResp.Data
|
||||||
|
if item.ID == 0 || len(item.Variants) != 2 || !strings.Contains(item.Srcset, "480w") || !strings.Contains(item.Srcset, "960w") {
|
||||||
|
t.Fatalf("unexpected uploaded item: %+v", item)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Non-empty folder delete returns 409 Conflict.
|
||||||
|
env.expect(t, http.StatusConflict, http.MethodDelete, fmt.Sprintf("/media/folders/%d", fid), managerTok, nil)
|
||||||
|
|
||||||
|
// 3. Metadata update keeps URL immutable.
|
||||||
|
updated := env.expect(t, http.StatusOK, http.MethodPut, fmt.Sprintf("/media/items/%d", item.ID), managerTok, map[string]any{
|
||||||
|
"alt": "Updated alt",
|
||||||
|
"title": "Hero",
|
||||||
|
"clear_folder": true,
|
||||||
|
})
|
||||||
|
if dataOf(updated)["url"] != item.URL {
|
||||||
|
t.Fatalf("URL changed on update: before=%q after=%v", item.URL, dataOf(updated)["url"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Base64 upload succeeds within 5 MB cap and rejects >5 MB with 413.
|
||||||
|
b64Small := base64.StdEncoding.EncodeToString(tinyPNG())
|
||||||
|
env.expect(t, http.StatusCreated, http.MethodPost, "/media/items/base64", managerTok, map[string]any{
|
||||||
|
"filename": "pixel.png",
|
||||||
|
"content_base64": b64Small,
|
||||||
|
})
|
||||||
|
// >5 MiB decoded payload -> 413 Payload Too Large.
|
||||||
|
bigDecoded := bytes.Repeat([]byte("a"), int(album.DefaultBase64MaxBytes)+1024)
|
||||||
|
b64TooBig := base64.StdEncoding.EncodeToString(bigDecoded)
|
||||||
|
env.expect(t, http.StatusRequestEntityTooLarge, http.MethodPost, "/media/items/base64", managerTok, map[string]any{
|
||||||
|
"filename": "huge.pdf",
|
||||||
|
"content_base64": b64TooBig,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 5. Delete item removes DB row and original + WebP variant blobs via AfterCommit.
|
||||||
|
var stored album.Item
|
||||||
|
if err := env.gdb.First(&stored, item.ID).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
keysBeforeDelete := stored.AllBlobKeys()
|
||||||
|
env.expect(t, http.StatusOK, http.MethodDelete, fmt.Sprintf("/media/items/%d", item.ID), managerTok, nil)
|
||||||
|
for _, k := range keysBeforeDelete {
|
||||||
|
exists, err := bucket.Exists(context.Background(), k)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("bucket.Exists(%q): %v", k, err)
|
||||||
|
}
|
||||||
|
if exists {
|
||||||
|
t.Fatalf("blob %q still exists after DELETE /media/items/%d", k, item.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMailImagesUnifiedOverAlbum(t *testing.T) {
|
||||||
|
env := newMailScreensEnv(t, nil)
|
||||||
|
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders, system_files RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, layoutsTok := env.admin(t, "mail-album-lay", false, `{"system.manage_mail_layouts":1}`)
|
||||||
|
|
||||||
|
// Seed a legacy Phase 35 system_files mail image.
|
||||||
|
title := "Legacy Logo"
|
||||||
|
isPublic := true
|
||||||
|
legacy := attach.File{
|
||||||
|
DiskName: "leg123456789.png",
|
||||||
|
FileName: "legacy-logo.png",
|
||||||
|
FileSize: 123,
|
||||||
|
ContentType: "image/png",
|
||||||
|
Title: &title,
|
||||||
|
Field: "images",
|
||||||
|
AttachmentType: album.MailImageLibraryMorph,
|
||||||
|
IsPublic: &isPublic,
|
||||||
|
}
|
||||||
|
if err := env.gdb.Create(&legacy).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload a new mail image via POST /mail/images -> stored in album's "mail" folder.
|
||||||
|
rec := mailUpload(t, env.h, layoutsTok, mediaTestPNG(t, 600, 300), "new-header.png")
|
||||||
|
if rec.Code != http.StatusOK && rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("POST /mail/images status = %d, body=%s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var postResp struct {
|
||||||
|
Data cabana.AdminMailImage `json:"data"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &postResp); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if postResp.Data.ID == 0 || !strings.Contains(postResp.Data.URL, "/media/") || len(postResp.Data.Variants) != 1 {
|
||||||
|
t.Fatalf("expected album-backed mail image with variants, got %+v", postResp.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /mail/images returns both the newly uploaded album item and the backfilled legacy item.
|
||||||
|
list := env.expect(t, http.StatusOK, http.MethodGet, "/mail/images", layoutsTok, nil)
|
||||||
|
rows, _ := list["data"].([]any)
|
||||||
|
if len(rows) != 2 {
|
||||||
|
t.Fatalf("GET /mail/images count = %d, want 2 (new + backfilled legacy)", len(rows))
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /mail/images/{id} resolves both the new album ID and the legacy system_files ID.
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("/mail/images/%d", postResp.Data.ID), layoutsTok, nil)
|
||||||
|
env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("/mail/images/%d", legacy.ID), layoutsTok, nil)
|
||||||
|
|
||||||
|
// MailBrandSetting.LogoFileID accepts the new album item ID.
|
||||||
|
env.expect(t, http.StatusOK, http.MethodPut, "/settings/mail_brand", layoutsTok, map[string]any{
|
||||||
|
"logo_file_id": postResp.Data.ID,
|
||||||
|
})
|
||||||
|
}
|
||||||
162
modules/cabana/media_routes_test.go
Normal file
162
modules/cabana/media_routes_test.go
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
package cabana_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMediaFinderFieldSchema(t *testing.T) {
|
||||||
|
t.Run("valid_defaults_and_options", func(t *testing.T) {
|
||||||
|
yaml := datepickerFields(` cover:
|
||||||
|
label: Cover
|
||||||
|
type: mediafinder
|
||||||
|
gallery:
|
||||||
|
label: Gallery
|
||||||
|
type: mediafinder
|
||||||
|
mode: file
|
||||||
|
multiple: true
|
||||||
|
folder: journal
|
||||||
|
`)
|
||||||
|
form, err := cabana.CompileForm("acme.conform", conformController{}, datepickerFS(yaml))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CompileForm: %v", err)
|
||||||
|
}
|
||||||
|
raw, err := form.CanonicalJSON()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CanonicalJSON: %v", err)
|
||||||
|
}
|
||||||
|
var doc struct {
|
||||||
|
Fields []map[string]any `json:"fields"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
byName := map[string]map[string]any{}
|
||||||
|
for _, f := range doc.Fields {
|
||||||
|
byName[f["name"].(string)] = f
|
||||||
|
}
|
||||||
|
cover := byName["cover"]
|
||||||
|
if cover == nil || cover["type"] != "mediafinder" || cover["mode"] != "image" {
|
||||||
|
t.Fatalf("cover field = %v, want type=mediafinder mode=image", cover)
|
||||||
|
}
|
||||||
|
gallery := byName["gallery"]
|
||||||
|
if gallery == nil || gallery["type"] != "mediafinder" || gallery["mode"] != "file" || gallery["multiple"] != true || gallery["folder"] != "journal" {
|
||||||
|
t.Fatalf("gallery field = %v, want type=mediafinder mode=file multiple=true folder=journal", gallery)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("invalid_options_rejected", func(t *testing.T) {
|
||||||
|
cases := map[string]struct {
|
||||||
|
field string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"invalid mode": {" cover:\n type: mediafinder\n mode: video\n", "must be image or file on type: mediafinder"},
|
||||||
|
"traversal folder": {" cover:\n type: mediafinder\n folder: ../etc\n", "must be a single folder slug"},
|
||||||
|
"nested slash folder": {" cover:\n type: mediafinder\n folder: a/b\n", "must be a single folder slug"},
|
||||||
|
"multiple on text": {" title:\n type: text\n multiple: true\n", "multiple is only valid on type: mediafinder"},
|
||||||
|
"folder on text": {" title:\n type: text\n folder: mail\n", "folder is only valid on type: mediafinder"},
|
||||||
|
"non-bool multiple": {" cover:\n type: mediafinder\n multiple: yes-please\n", "multiple:"},
|
||||||
|
}
|
||||||
|
for name, tc := range cases {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
err := activateFields(t, datepickerFields(tc.field))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||||
|
t.Fatalf("err = %v, want substring %q", err, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaMCPPluginSurfaceAndScopes(t *testing.T) {
|
||||||
|
plugin := cabana.MediaMCPPlugin("/admin")
|
||||||
|
if plugin.ID() != "summercms.media" {
|
||||||
|
t.Fatalf("ID = %q, want summercms.media", plugin.ID())
|
||||||
|
}
|
||||||
|
|
||||||
|
hasPerms, ok := plugin.(pact.HasPermissions)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("MediaMCPPlugin must implement pact.HasPermissions")
|
||||||
|
}
|
||||||
|
permCodes := map[string]bool{}
|
||||||
|
for _, p := range hasPerms.Permissions() {
|
||||||
|
permCodes[p.Code] = true
|
||||||
|
if len(p.Roles) > 0 {
|
||||||
|
t.Fatalf("media permission %q must not have default role grants: %v", p.Code, p.Roles)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !permCodes[cabana.PermissionViewMedia] || !permCodes[cabana.PermissionManageMedia] {
|
||||||
|
t.Fatalf("missing media permissions: %v", permCodes)
|
||||||
|
}
|
||||||
|
|
||||||
|
hasScopes, ok := plugin.(pact.HasTokenScopes)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("MediaMCPPlugin must implement pact.HasTokenScopes")
|
||||||
|
}
|
||||||
|
scopes := map[string]pact.TokenScope{}
|
||||||
|
for _, s := range hasScopes.TokenScopes() {
|
||||||
|
scopes[s.Name] = s
|
||||||
|
}
|
||||||
|
readScope, ok := scopes["media:read"]
|
||||||
|
if !ok || readScope.Group != "backend::lang.api_tokens.group_media" {
|
||||||
|
t.Fatalf("media:read scope = %+v", readScope)
|
||||||
|
}
|
||||||
|
writeScope, ok := scopes["media"]
|
||||||
|
if !ok || writeScope.Group != "backend::lang.api_tokens.group_media" {
|
||||||
|
t.Fatalf("media scope = %+v", writeScope)
|
||||||
|
}
|
||||||
|
|
||||||
|
hasMCP, ok := plugin.(pact.HasMCP)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("MediaMCPPlugin must implement pact.HasMCP")
|
||||||
|
}
|
||||||
|
tools := hasMCP.MCP().Tools
|
||||||
|
if len(tools) != 7 {
|
||||||
|
t.Fatalf("MediaMCPPlugin tools = %d, want 7", len(tools))
|
||||||
|
}
|
||||||
|
wantTools := map[string]bool{
|
||||||
|
"prepare_upload": false,
|
||||||
|
"upload": false,
|
||||||
|
"list": false,
|
||||||
|
"get": false,
|
||||||
|
"update": false,
|
||||||
|
"delete": false,
|
||||||
|
"create_folder": false,
|
||||||
|
}
|
||||||
|
for _, tool := range tools {
|
||||||
|
if _, exists := wantTools[tool.Name]; !exists {
|
||||||
|
t.Errorf("unexpected MCP tool %q", tool.Name)
|
||||||
|
}
|
||||||
|
wantTools[tool.Name] = true
|
||||||
|
if tool.Guard != "backend" {
|
||||||
|
t.Errorf("tool %q Guard = %q, want backend", tool.Name, tool.Guard)
|
||||||
|
}
|
||||||
|
if tool.Name == "delete" && (tool.Destructive == nil || !*tool.Destructive) {
|
||||||
|
t.Errorf("delete tool must be marked Destructive=true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, seen := range wantTools {
|
||||||
|
if !seen {
|
||||||
|
t.Errorf("missing expected MCP tool %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify Allows helper respects media.view_media vs media.manage_media.
|
||||||
|
viewer := &bouncer.Principal{ID: 1, Backend: true, PermissionGrants: map[string]bool{cabana.PermissionViewMedia: true}}
|
||||||
|
manager := &bouncer.Principal{ID: 2, Backend: true, PermissionGrants: map[string]bool{cabana.PermissionManageMedia: true}}
|
||||||
|
none := &bouncer.Principal{ID: 3, Backend: true, PermissionGrants: map[string]bool{"acme.demo.access": true}}
|
||||||
|
if !cabana.Allows(viewer, []string{cabana.PermissionViewMedia}) || cabana.Allows(viewer, []string{cabana.PermissionManageMedia}) {
|
||||||
|
t.Fatal("viewer permission check mismatch")
|
||||||
|
}
|
||||||
|
if !cabana.Allows(manager, []string{cabana.PermissionManageMedia}) {
|
||||||
|
t.Fatal("manager permission check mismatch")
|
||||||
|
}
|
||||||
|
if cabana.Allows(none, []string{cabana.PermissionViewMedia}) || cabana.Allows(none, []string{cabana.PermissionManageMedia}) {
|
||||||
|
t.Fatal("none principal unexpectedly allowed media permissions")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1167,9 +1167,9 @@ func newConformEnv(t *testing.T) *conformEnv {
|
|||||||
login := "conform-" + stamp
|
login := "conform-" + stamp
|
||||||
insertAdmin(t, gdb, login, login+"@example.test", adminTestPassword, true, false)
|
insertAdmin(t, gdb, login, login+"@example.test", adminTestPassword, true, false)
|
||||||
// The Plugins screen needs backend.view_plugins, which no role holds.
|
// The Plugins screen needs backend.view_plugins, which no role holds.
|
||||||
// Mail image routes need either mail permission (conform is not a superuser).
|
// Mail image and Media Library routes need their respective permissions (conform is not a superuser).
|
||||||
if err := gdb.Exec(`UPDATE backend_users SET permissions = ? WHERE login = ?`,
|
if err := gdb.Exec(`UPDATE backend_users SET permissions = ? WHERE login = ?`,
|
||||||
`{"backend.view_plugins":1,"system.manage_mail_templates":1,"system.manage_mail_layouts":1}`, login).Error; err != nil {
|
`{"backend.view_plugins":1,"system.manage_mail_templates":1,"system.manage_mail_layouts":1,"media.view_media":1,"media.manage_media":1}`, login).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
519
modules/pier/media_mcp_test.go
Normal file
519
modules/pier/media_mcp_test.go
Normal file
@@ -0,0 +1,519 @@
|
|||||||
|
//go:build summercms_mcp
|
||||||
|
|
||||||
|
package pier_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/album"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mediaBackendGuard implements pact.MCPGuardProvider for the "backend" guard
|
||||||
|
// with real scope-to-permission enforcement (media:read vs media) matching cabana.
|
||||||
|
type mediaBackendGuard struct{}
|
||||||
|
|
||||||
|
func (mediaBackendGuard) MCPGuardName() string { return "backend" }
|
||||||
|
|
||||||
|
func (mediaBackendGuard) MCPTokenGuarded(mw []string) bool {
|
||||||
|
return slices.Contains(mw, "backend")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mediaBackendGuard) MCPRequirements(perms []string) (pact.MCPRequirements, error) {
|
||||||
|
return pact.MCPRequirements{Permissions: perms}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mediaBackendGuard) MCPAllows(_ context.Context, subject pact.MCPSubject, _ pact.MCPRequirements, permissions []string) (bool, error) {
|
||||||
|
if slices.Contains(subject.Scopes, "media") {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if slices.Contains(subject.Scopes, "media:read") {
|
||||||
|
for _, p := range permissions {
|
||||||
|
if p != cabana.PermissionViewMedia {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mediaBackendGuard) MCPDispatch(_ context.Context, subject pact.MCPSubject, _ string) (pact.MCPDispatch, error) {
|
||||||
|
return pact.MCPDispatch{
|
||||||
|
Principal: &bouncer.Principal{
|
||||||
|
ID: subject.UserID,
|
||||||
|
Backend: true,
|
||||||
|
PermissionGrants: map[string]bool{
|
||||||
|
cabana.PermissionViewMedia: true,
|
||||||
|
cabana.PermissionManageMedia: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Guards: []string{"backend"},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// mediaTokenVerifier issues two bearer tokens: one with "media:read" and one with "media".
|
||||||
|
type mediaTokenVerifier struct{}
|
||||||
|
|
||||||
|
func (mediaTokenVerifier) MCPVerifyToken(_ context.Context, raw string) (pact.MCPGrant, error) {
|
||||||
|
switch raw {
|
||||||
|
case "oas_at_media_read":
|
||||||
|
return pact.MCPGrant{
|
||||||
|
Subject: pact.MCPGrantSubjectBackend,
|
||||||
|
BackendUserID: 11,
|
||||||
|
ClientID: "c-read",
|
||||||
|
TokenID: 1,
|
||||||
|
Scopes: []string{"media:read"},
|
||||||
|
ExpiresAt: time.Now().Add(time.Hour),
|
||||||
|
}, nil
|
||||||
|
case "oas_at_media_write":
|
||||||
|
return pact.MCPGrant{
|
||||||
|
Subject: pact.MCPGrantSubjectBackend,
|
||||||
|
BackendUserID: 12,
|
||||||
|
ClientID: "c-write",
|
||||||
|
TokenID: 2,
|
||||||
|
Scopes: []string{"media"},
|
||||||
|
ExpiresAt: time.Now().Add(time.Hour),
|
||||||
|
}, nil
|
||||||
|
default:
|
||||||
|
return pact.MCPGrant{}, pact.ErrMCPTokenInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mediaTokenVerifier) MCPResource() string { return "http://acme.test/mcp" }
|
||||||
|
|
||||||
|
// mediaStubRoutesPlugin mounts the /admin/api/v1/media/* routes behind the
|
||||||
|
// "backend" middleware plus raw PUT /media/upload/{token} in memory so
|
||||||
|
// TestMediaMCPTools exercises all 7 media_* tools, signed PUT upload, and the
|
||||||
|
// 5 MB base64 cap end-to-end without requiring Docker.
|
||||||
|
type mediaStubRoutesPlugin struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
nextID uint
|
||||||
|
folders map[uint]map[string]any
|
||||||
|
items map[uint]map[string]any
|
||||||
|
tokens map[string]string // token -> filename
|
||||||
|
baseURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newMediaStubRoutesPlugin() *mediaStubRoutesPlugin {
|
||||||
|
return &mediaStubRoutesPlugin{
|
||||||
|
nextID: 1,
|
||||||
|
folders: map[uint]map[string]any{},
|
||||||
|
items: map[uint]map[string]any{},
|
||||||
|
tokens: map[string]string{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*mediaStubRoutesPlugin) ID() string { return "test.media_stub" }
|
||||||
|
func (*mediaStubRoutesPlugin) Requires() []string { return nil }
|
||||||
|
func (*mediaStubRoutesPlugin) Register(*backpack.App) error { return nil }
|
||||||
|
func (*mediaStubRoutesPlugin) Boot(*backpack.App) error { return nil }
|
||||||
|
|
||||||
|
func (*mediaStubRoutesPlugin) Middlewares() map[string]pact.Middleware {
|
||||||
|
return map[string]pact.Middleware{
|
||||||
|
"backend": func(next http.Handler) http.Handler { return next },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) Routes(r pact.Router) error {
|
||||||
|
r.Group("/admin/api/v1", []string{"backend"}, func(g pact.Router) {
|
||||||
|
g.Post("/media/folders", p.createFolder)
|
||||||
|
g.Post("/media/uploads/prepare", p.prepareUpload)
|
||||||
|
g.Post("/media/items/base64", p.uploadBase64)
|
||||||
|
g.Get("/media/items", p.listItems)
|
||||||
|
g.Get("/media/items/{id}", p.getItem)
|
||||||
|
g.Put("/media/items/{id}", p.updateItem)
|
||||||
|
g.Delete("/media/items/{id}", p.deleteItem)
|
||||||
|
})
|
||||||
|
r.GroupRaw("/media", nil, func(g pact.Router) {
|
||||||
|
g.Put("/upload/{token}", p.signedUpload)
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) createFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
ParentID *uint `json:"parent_id"`
|
||||||
|
}
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||||
|
p.mu.Lock()
|
||||||
|
id := p.nextID
|
||||||
|
p.nextID++
|
||||||
|
f := map[string]any{"id": id, "name": req.Name, "slug": album.SanitizeSlug(req.Name), "parent_id": req.ParentID}
|
||||||
|
p.folders[id] = f
|
||||||
|
p.mu.Unlock()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": f})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) prepareUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
}
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||||
|
p.mu.Lock()
|
||||||
|
tok := fmt.Sprintf("tok-%d", p.nextID)
|
||||||
|
p.nextID++
|
||||||
|
p.tokens[tok] = req.Filename
|
||||||
|
base := p.baseURL
|
||||||
|
p.mu.Unlock()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"data": map[string]any{
|
||||||
|
"upload_url": base + "/media/upload/" + tok,
|
||||||
|
"method": http.MethodPut,
|
||||||
|
"expires_at": time.Now().Add(5 * time.Minute).UTC().Format(time.RFC3339),
|
||||||
|
"max_bytes": album.DefaultMaxBytes,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) signedUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
tok := r.PathValue("token")
|
||||||
|
p.mu.Lock()
|
||||||
|
filename, ok := p.tokens[tok]
|
||||||
|
if ok {
|
||||||
|
delete(p.tokens, tok)
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
if !ok {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
_, _ = w.Write([]byte(`{"error":"invalid token"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, _ := io.ReadAll(r.Body)
|
||||||
|
p.mu.Lock()
|
||||||
|
id := p.nextID
|
||||||
|
p.nextID++
|
||||||
|
item := map[string]any{
|
||||||
|
"id": id,
|
||||||
|
"file_name": filename,
|
||||||
|
"file_size": len(raw),
|
||||||
|
"url": fmt.Sprintf("/media/abc123456789/%s", filename),
|
||||||
|
"alt": "",
|
||||||
|
}
|
||||||
|
p.items[id] = item
|
||||||
|
p.mu.Unlock()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": item})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) uploadBase64(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
ContentBase64 string `json:"content_base64"`
|
||||||
|
Alt string `json:"alt"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||||
|
_, _ = w.Write([]byte(`{"error":{"code":"validation_failed","message":"invalid json"}}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
decoded, err := base64.StdEncoding.DecodeString(req.ContentBase64)
|
||||||
|
if err != nil {
|
||||||
|
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||||
|
_, _ = w.Write([]byte(`{"error":{"code":"validation_failed","message":"invalid base64"}}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if int64(len(decoded)) > album.DefaultBase64MaxBytes {
|
||||||
|
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
||||||
|
_, _ = w.Write([]byte(`{"error":{"code":"payload_too_large","message":"file exceeds 5 MB base64 cap"}}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.mu.Lock()
|
||||||
|
id := p.nextID
|
||||||
|
p.nextID++
|
||||||
|
item := map[string]any{
|
||||||
|
"id": id,
|
||||||
|
"file_name": req.Filename,
|
||||||
|
"file_size": len(decoded),
|
||||||
|
"alt": req.Alt,
|
||||||
|
"url": fmt.Sprintf("/media/def123456789/%s", req.Filename),
|
||||||
|
}
|
||||||
|
p.items[id] = item
|
||||||
|
p.mu.Unlock()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": item})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) listItems(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
p.mu.Lock()
|
||||||
|
out := make([]map[string]any, 0, len(p.items))
|
||||||
|
for _, it := range p.items {
|
||||||
|
out = append(out, it)
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": out, "meta": map[string]any{"total": len(out)}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) getItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, _ := strconv.Atoi(r.PathValue("id"))
|
||||||
|
p.mu.Lock()
|
||||||
|
it, ok := p.items[uint(id)]
|
||||||
|
p.mu.Unlock()
|
||||||
|
if !ok {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
_, _ = w.Write([]byte(`{"error":{"code":"not_found"}}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": it})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) updateItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, _ := strconv.Atoi(r.PathValue("id"))
|
||||||
|
var req map[string]any
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||||
|
p.mu.Lock()
|
||||||
|
it, ok := p.items[uint(id)]
|
||||||
|
if ok {
|
||||||
|
if alt, has := req["alt"].(string); has {
|
||||||
|
it["alt"] = alt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
if !ok {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": it})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *mediaStubRoutesPlugin) deleteItem(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, _ := strconv.Atoi(r.PathValue("id"))
|
||||||
|
p.mu.Lock()
|
||||||
|
_, ok := p.items[uint(id)]
|
||||||
|
delete(p.items, uint(id))
|
||||||
|
p.mu.Unlock()
|
||||||
|
if !ok {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"deleted": true}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func callMCPToolJSON(t *testing.T, session *mcp.ClientSession, name string, args map[string]any) (map[string]any, bool) {
|
||||||
|
t.Helper()
|
||||||
|
res, err := session.CallTool(context.Background(), &mcp.CallToolParams{
|
||||||
|
Name: name,
|
||||||
|
Arguments: args,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CallTool(%s): %v", name, err)
|
||||||
|
}
|
||||||
|
var text string
|
||||||
|
for _, c := range res.Content {
|
||||||
|
if tc, ok := c.(*mcp.TextContent); ok {
|
||||||
|
text += tc.Text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var out map[string]any
|
||||||
|
_ = json.Unmarshal([]byte(text), &out)
|
||||||
|
return out, res.IsError
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaMCPTools(t *testing.T) {
|
||||||
|
logBuf := captureLogs(t)
|
||||||
|
stub := newMediaStubRoutesPlugin()
|
||||||
|
dir := t.TempDir()
|
||||||
|
for name, body := range map[string]string{
|
||||||
|
"app.yaml": "name: acme\nurl: http://acme.test\n",
|
||||||
|
"http.yaml": "body_limits:\n default_bytes: 10485760\n upload_bytes: 10485760\n",
|
||||||
|
"mcp.yaml": "enabled: false\n",
|
||||||
|
} {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := backpack.New(cfg)
|
||||||
|
if err := app.Publish[pact.MCPTokenVerifier](mediaTokenVerifier{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
reg := pact.NewMCPGuards()
|
||||||
|
if err := reg.Register(mediaBackendGuard{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := app.Publish(reg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
plugins := []party.Plugin{stub, cabana.MediaMCPPlugin("/admin")}
|
||||||
|
host, err := mountPier(t, app, plugins)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("mountPier: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = host.pier.Close() })
|
||||||
|
|
||||||
|
// Assert zero warnUncoveredBackendWriteTools warnings at boot.
|
||||||
|
if n := countWarningLines(logBuf.String()); n != 0 {
|
||||||
|
t.Fatalf("expected 0 uncovered-write-tool boot warnings, got %d:\n%s", n, logBuf.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve both MCP endpoints (host) and raw /media/upload/{token} (stub router).
|
||||||
|
uploadHandler, ok := host.r.Handler(http.MethodPut, "/media/upload/{token}")
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("expected PUT /media/upload/{token} on router")
|
||||||
|
}
|
||||||
|
uploadMux := http.NewServeMux()
|
||||||
|
uploadMux.Handle("PUT /media/upload/{token}", uploadHandler)
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if strings.HasPrefix(r.URL.Path, "/media/upload/") {
|
||||||
|
uploadMux.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
host.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
stub.baseURL = srv.URL
|
||||||
|
|
||||||
|
// 1. Scope filtering: media:read sees only media_list and media_get.
|
||||||
|
readSession := sdkClient(t, context.Background(), srv.URL+host.path, "oas_at_media_read", clientOpts{})
|
||||||
|
readTools, err := readSession.ListTools(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListTools(media:read): %v", err)
|
||||||
|
}
|
||||||
|
var readNames []string
|
||||||
|
for _, tool := range readTools.Tools {
|
||||||
|
readNames = append(readNames, tool.Name)
|
||||||
|
}
|
||||||
|
slices.Sort(readNames)
|
||||||
|
if !slices.Equal(readNames, []string{"media_get", "media_list"}) {
|
||||||
|
t.Fatalf("media:read tools = %v, want [media_get media_list]", readNames)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Scope filtering: media sees all 7 media_* tools.
|
||||||
|
writeSession := sdkClient(t, context.Background(), srv.URL+host.path, "oas_at_media_write", clientOpts{})
|
||||||
|
writeTools, err := writeSession.ListTools(context.Background(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListTools(media): %v", err)
|
||||||
|
}
|
||||||
|
var writeNames []string
|
||||||
|
for _, tool := range writeTools.Tools {
|
||||||
|
writeNames = append(writeNames, tool.Name)
|
||||||
|
}
|
||||||
|
slices.Sort(writeNames)
|
||||||
|
wantAll := []string{
|
||||||
|
"media_create_folder",
|
||||||
|
"media_delete",
|
||||||
|
"media_get",
|
||||||
|
"media_list",
|
||||||
|
"media_prepare_upload",
|
||||||
|
"media_update",
|
||||||
|
"media_upload",
|
||||||
|
}
|
||||||
|
if !slices.Equal(writeNames, wantAll) {
|
||||||
|
t.Fatalf("media tools = %v, want %v", writeNames, wantAll)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. media_create_folder
|
||||||
|
folderRes, isErr := callMCPToolJSON(t, writeSession, "media_create_folder", map[string]any{"name": "Editorial"})
|
||||||
|
if isErr {
|
||||||
|
t.Fatalf("media_create_folder error: %v", folderRes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. media_prepare_upload -> HTTP PUT /media/upload/{token} end-to-end
|
||||||
|
prepRes, isErr := callMCPToolJSON(t, writeSession, "media_prepare_upload", map[string]any{"filename": "hero.png"})
|
||||||
|
if isErr {
|
||||||
|
t.Fatalf("media_prepare_upload error: %v", prepRes)
|
||||||
|
}
|
||||||
|
dataMap, _ := prepRes["data"].(map[string]any)
|
||||||
|
uploadURL, _ := dataMap["upload_url"].(string)
|
||||||
|
if !strings.Contains(uploadURL, "/media/upload/") {
|
||||||
|
t.Fatalf("unexpected upload_url: %q", uploadURL)
|
||||||
|
}
|
||||||
|
putReq, err := http.NewRequest(http.MethodPut, uploadURL, bytes.NewReader([]byte("binary-image-bytes")))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
putResp, err := http.DefaultClient.Do(putReq)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("PUT signed upload: %v", err)
|
||||||
|
}
|
||||||
|
_ = putResp.Body.Close()
|
||||||
|
if putResp.StatusCode != http.StatusCreated {
|
||||||
|
t.Fatalf("PUT %s status = %d, want 201", uploadURL, putResp.StatusCode)
|
||||||
|
}
|
||||||
|
// Replay of same signed URL returns 401.
|
||||||
|
putReq2, _ := http.NewRequest(http.MethodPut, uploadURL, bytes.NewReader([]byte("replay")))
|
||||||
|
putResp2, err := http.DefaultClient.Do(putReq2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = putResp2.Body.Close()
|
||||||
|
if putResp2.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("replay PUT status = %d, want 401", putResp2.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. media_upload base64: exact 5 MB payload succeeds (proves 8 MiB pier.maxRequestBody).
|
||||||
|
fiveMB := bytes.Repeat([]byte("A"), int(album.DefaultBase64MaxBytes))
|
||||||
|
upRes, isErr := callMCPToolJSON(t, writeSession, "media_upload", map[string]any{
|
||||||
|
"filename": "exact-5mb.pdf",
|
||||||
|
"content_base64": base64.StdEncoding.EncodeToString(fiveMB),
|
||||||
|
"alt": "Five MB",
|
||||||
|
})
|
||||||
|
if isErr {
|
||||||
|
t.Fatalf("5 MB media_upload failed: %v", upRes)
|
||||||
|
}
|
||||||
|
itemData, _ := upRes["data"].(map[string]any)
|
||||||
|
itemID := uint(itemData["id"].(float64))
|
||||||
|
|
||||||
|
// >5 MB decoded payload is rejected.
|
||||||
|
overFiveMB := bytes.Repeat([]byte("B"), int(album.DefaultBase64MaxBytes)+1024)
|
||||||
|
if _, isErr := callMCPToolJSON(t, writeSession, "media_upload", map[string]any{
|
||||||
|
"filename": "over-5mb.pdf",
|
||||||
|
"content_base64": base64.StdEncoding.EncodeToString(overFiveMB),
|
||||||
|
}); !isErr {
|
||||||
|
t.Fatal(">5 MB decoded media_upload must fail")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. media_list, media_get, media_update, media_delete
|
||||||
|
listRes, isErr := callMCPToolJSON(t, readSession, "media_list", map[string]any{})
|
||||||
|
if isErr {
|
||||||
|
t.Fatalf("media_list error: %v", listRes)
|
||||||
|
}
|
||||||
|
getRes, isErr := callMCPToolJSON(t, readSession, "media_get", map[string]any{"id": itemID})
|
||||||
|
if isErr {
|
||||||
|
t.Fatalf("media_get error: %v", getRes)
|
||||||
|
}
|
||||||
|
updRes, isErr := callMCPToolJSON(t, writeSession, "media_update", map[string]any{"id": itemID, "alt": "New Alt"})
|
||||||
|
if isErr {
|
||||||
|
t.Fatalf("media_update error: %v", updRes)
|
||||||
|
}
|
||||||
|
delRes, isErr := callMCPToolJSON(t, writeSession, "media_delete", map[string]any{"id": itemID})
|
||||||
|
if isErr {
|
||||||
|
t.Fatalf("media_delete error: %v", delRes)
|
||||||
|
}
|
||||||
|
}
|
||||||
174
modules/surf/media_test.go
Normal file
174
modules/surf/media_test.go
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
package surf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/album"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
"gocloud.dev/blob"
|
||||||
|
"gocloud.dev/blob/memblob"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mediaConfig(t *testing.T, keys map[string]any) *compass.Config {
|
||||||
|
t.Helper()
|
||||||
|
cfg := writeHTTPConfig(t, "body_limits:\n default_bytes: 1024\n upload_bytes: 1024\n")
|
||||||
|
for k, v := range keys {
|
||||||
|
if err := cfg.Set(k, v); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func mediaRoutes(t *testing.T, app *backpack.App, plugins []party.Plugin) []RouteInfo {
|
||||||
|
t.Helper()
|
||||||
|
rt, err := BuildRouter(app, plugins)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out []RouteInfo
|
||||||
|
for _, info := range rt.Routes() {
|
||||||
|
if info.PluginID == mediaPluginID {
|
||||||
|
out = append(out, info)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMediaMount(t *testing.T) {
|
||||||
|
t.Run("off_registers_no_static_route", func(t *testing.T) {
|
||||||
|
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": false}))
|
||||||
|
routes := mediaRoutes(t, app, nil)
|
||||||
|
for _, rt := range routes {
|
||||||
|
if rt.Method == http.MethodGet {
|
||||||
|
t.Fatalf("unexpected static GET route when media.serve=false: %+v", rt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := album.ServiceFrom(app); !ok {
|
||||||
|
t.Fatal("expected *album.Service to be published on app")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("static_zero_db_serving_and_headers", func(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
bucket := memblob.OpenBucket(nil)
|
||||||
|
defer bucket.Close()
|
||||||
|
|
||||||
|
if err := bucket.WriteAll(ctx, "media/abc123456789/hero.png", []byte("png-data"), attach.UploadWriterOptions("image/png")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := bucket.WriteAll(ctx, "media/abc123456789/spec.pdf", []byte("%PDF-1.4\n"), attach.UploadWriterOptions("application/pdf")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Intentionally do NOT publish *gorm.DB: proves zero-DB-hit serving.
|
||||||
|
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": true}))
|
||||||
|
if err := app.Publish[*blob.Bucket](bucket); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h, err := Assemble(app, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Assemble: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Raster image served inline with immutable Cache-Control, nosniff, CSP.
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/hero.png", nil))
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET image status = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
if rec.Body.String() != "png-data" {
|
||||||
|
t.Fatalf("body = %q, want png-data", rec.Body.String())
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("Cache-Control"); got != album.MediaCacheControl {
|
||||||
|
t.Fatalf("Cache-Control = %q, want %q", got, album.MediaCacheControl)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
||||||
|
t.Fatalf("X-Content-Type-Options = %q", got)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("Content-Security-Policy"); got != album.MediaContentSecurityPolicy {
|
||||||
|
t.Fatalf("CSP = %q", got)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("Content-Disposition"); got != "" {
|
||||||
|
t.Fatalf("image Content-Disposition = %q, want empty", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PDF served with Content-Disposition: attachment.
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/spec.pdf", nil))
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("GET pdf status = %d, want 200", rec.Code)
|
||||||
|
}
|
||||||
|
if got := rec.Header().Get("Content-Disposition"); got != "attachment" {
|
||||||
|
t.Fatalf("pdf Content-Disposition = %q, want attachment", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Traversal path rejected with 404.
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/..%2Fsecret.png", nil))
|
||||||
|
if rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("traversal status = %d, want 404", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("prefix_collision_rejected", func(t *testing.T) {
|
||||||
|
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": true}))
|
||||||
|
_, err := BuildRouter(app, []party.Plugin{uploadsPathPlugin{path: "/media/custom"}})
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "media prefix") {
|
||||||
|
t.Fatalf("BuildRouter collision err = %v, want media prefix collision", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("invalid_prefix_rejected", func(t *testing.T) {
|
||||||
|
app := backpack.New(mediaConfig(t, map[string]any{
|
||||||
|
"media.serve": true,
|
||||||
|
"media.public_path_prefix": "https://cdn.example.com/media",
|
||||||
|
}))
|
||||||
|
if _, err := BuildRouter(app, nil); err == nil {
|
||||||
|
t.Fatal("expected invalid media.public_path_prefix to fail BuildRouter")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("signed_upload_route_mounted_raw_without_admin_cookie", func(t *testing.T) {
|
||||||
|
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": true}))
|
||||||
|
routes := mediaRoutes(t, app, nil)
|
||||||
|
var sawPut, sawPost bool
|
||||||
|
for _, rt := range routes {
|
||||||
|
if rt.Pattern == "/media/upload/{token}" {
|
||||||
|
if rt.Method == http.MethodPut {
|
||||||
|
sawPut = true
|
||||||
|
}
|
||||||
|
if rt.Method == http.MethodPost {
|
||||||
|
sawPost = true
|
||||||
|
}
|
||||||
|
for _, mw := range rt.Middleware {
|
||||||
|
if mw == "backend" || mw == "csrf" {
|
||||||
|
t.Fatalf("signed upload route must not require %q middleware: %+v", mw, rt.Middleware)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !sawPut || !sawPost {
|
||||||
|
t.Fatalf("expected PUT and POST /media/upload/{token}, got routes: %+v", routes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calling PUT /media/upload/tok without any cookie/CSRF reaches the handler
|
||||||
|
// (returns 503 because no DB is published, rather than 401/403 CSRF).
|
||||||
|
h, err := Assemble(app, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodPut, "/media/upload/some-token", strings.NewReader("bytes")))
|
||||||
|
if rec.Code != http.StatusServiceUnavailable {
|
||||||
|
t.Fatalf("PUT /media/upload/some-token without DB status = %d, want 503", rec.Code)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
488
scripts/check-phase37.sh
Executable file
488
scripts/check-phase37.sh
Executable file
@@ -0,0 +1,488 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# check-phase37: fail-closed verification gate for Phase 37 (Media Library: modules/album).
|
||||||
|
#
|
||||||
|
# Stages:
|
||||||
|
# go go vet (default + summercms_mcp), go test -short ./..., and required
|
||||||
|
# Phase 37 unit tests across album, cabana, pier (-tags summercms_mcp), and surf.
|
||||||
|
# docker Docker host only: required Postgres integration tests in album and cabana.
|
||||||
|
# admin npm run test (requiring Phase 37 Vitest files), typecheck,
|
||||||
|
# scripts/check-admin-openapi.sh --check, and scripts/check-admin-dist.sh.
|
||||||
|
# docs TestDocsTree and summer docs:build --check.
|
||||||
|
# consumers Read-only local proofs against ../sm-journal-plugin (scratch modfile
|
||||||
|
# pointing to this checkout + go vet + Go media/enrichment tests + Vitest)
|
||||||
|
# and ../vue-journal-layer (Vitest), verifying clean sibling git status
|
||||||
|
# before and after.
|
||||||
|
# marker No framework lines added since PHASE37_BASE_TAG under modules/, cmd/,
|
||||||
|
# internal/, or docs/ name a consuming application.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# scripts/check-phase37.sh [--go] [--docker] [--admin] [--docs] [--consumers] [--marker]
|
||||||
|
# scripts/check-phase37.sh --all
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
unset FORCE_COLOR
|
||||||
|
export NO_COLOR=1
|
||||||
|
|
||||||
|
ROOT="${PHASE37_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
|
||||||
|
SIBLINGS="${PHASE37_SIBLINGS:-$(dirname "$ROOT")}"
|
||||||
|
JOURNAL_PLUGIN="${JOURNAL_PLUGIN:-$SIBLINGS/sm-journal-plugin}"
|
||||||
|
VUE_JOURNAL_LAYER="${VUE_JOURNAL_LAYER:-$SIBLINGS/vue-journal-layer}"
|
||||||
|
PHASE37_BASE_TAG="${PHASE37_BASE_TAG:-v0.6.9}"
|
||||||
|
|
||||||
|
GO_TESTS=(
|
||||||
|
./modules/album:TestSlugAndShortID
|
||||||
|
./modules/album:TestWebPVariants
|
||||||
|
./modules/album:TestStaticHandlerSecurity
|
||||||
|
./modules/album:TestDecompressionBombAndPolyglotGuards
|
||||||
|
./modules/album:TestConfigAndInstallHelpers
|
||||||
|
./modules/cabana:TestMediaFinderFieldSchema
|
||||||
|
./modules/cabana:TestMediaMCPPluginSurfaceAndScopes
|
||||||
|
./modules/cabana:TestTokenRouteGates
|
||||||
|
./modules/cabana:TestPhase10ConformanceInventory
|
||||||
|
./modules/surf:TestMediaMount
|
||||||
|
)
|
||||||
|
|
||||||
|
GO_MCP_TESTS=(
|
||||||
|
./modules/pier:TestMediaMCPTools
|
||||||
|
)
|
||||||
|
|
||||||
|
DOCKER_TESTS=(
|
||||||
|
./modules/album:TestMigrationsUpDown
|
||||||
|
./modules/album:TestFolderCRUDAndNonEmptyDelete
|
||||||
|
./modules/album:TestUploadAndNoDedup
|
||||||
|
./modules/album:TestConsumeUploadTokenSingleUse
|
||||||
|
./modules/album:TestDeleteItemInTxAfterCommit
|
||||||
|
./modules/album:TestGetItemsByShortIDsAndListFilters
|
||||||
|
./modules/album:TestBackfillMailImages
|
||||||
|
./modules/cabana:TestMediaPermissionsMatrix
|
||||||
|
./modules/cabana:TestMediaTokenScopes
|
||||||
|
./modules/cabana:TestMediaUploadLifecycleAndAfterCommitDelete
|
||||||
|
./modules/cabana:TestMailImagesUnifiedOverAlbum
|
||||||
|
./modules/cabana:TestPhase10OpenAPIConformance
|
||||||
|
)
|
||||||
|
|
||||||
|
ADMIN_FILES=(
|
||||||
|
tests/media/MediaBrowser.test.ts
|
||||||
|
tests/media/MediaPickerModal.test.ts
|
||||||
|
tests/form/MediaFinderField.test.ts
|
||||||
|
tests/form/MailImagePicker.test.ts
|
||||||
|
)
|
||||||
|
|
||||||
|
APP_NAMES=("grzy""by" "fono""teka" "p[lł]yta""rium" "summercms""io" "sm-demo""-app" "sm-bm""-app")
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
cat >&2 <<'EOF'
|
||||||
|
usage:
|
||||||
|
check-phase37.sh [--go] [--docker] [--admin] [--docs] [--consumers] [--marker]
|
||||||
|
check-phase37.sh --all
|
||||||
|
EOF
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
|
||||||
|
detect_go() {
|
||||||
|
python3 - "$1" <<'PY'
|
||||||
|
import json, os, sys
|
||||||
|
path = sys.argv[1]
|
||||||
|
require = [n for n in os.environ.get("REQUIRE_TESTS", "").split() if n]
|
||||||
|
passed = set()
|
||||||
|
failed = []
|
||||||
|
with open(path, encoding="utf-8", errors="replace") as fh:
|
||||||
|
for raw in fh:
|
||||||
|
line = raw.strip()
|
||||||
|
if not line.startswith("{"):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ev = json.loads(line)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
print("refuse: non-json test output", file=sys.stderr)
|
||||||
|
sys.exit(4)
|
||||||
|
action = ev.get("Action")
|
||||||
|
test = ev.get("Test") or ""
|
||||||
|
pkg = ev.get("Package") or ev.get("ImportPath") or ""
|
||||||
|
if action == "build-fail" or (action == "fail" and ev.get("FailedBuild")):
|
||||||
|
print(f"refuse: build failed {pkg}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
text = ev.get("Output") or ""
|
||||||
|
if action == "output" and "no tests to run" in text:
|
||||||
|
print(f"refuse: no tests to run in {pkg}", file=sys.stderr)
|
||||||
|
sys.exit(3)
|
||||||
|
if action == "skip" and test:
|
||||||
|
print(f"refuse: skipped {pkg} {test}", file=sys.stderr)
|
||||||
|
sys.exit(2)
|
||||||
|
if action == "fail":
|
||||||
|
failed.append(f"{pkg} {test}".strip())
|
||||||
|
if action == "pass" and test:
|
||||||
|
passed.add(test)
|
||||||
|
if failed:
|
||||||
|
print("refuse: failed " + ", ".join(failed), file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
if not passed:
|
||||||
|
print("refuse: zero tests", file=sys.stderr)
|
||||||
|
sys.exit(3)
|
||||||
|
missing = [n for n in require if n not in passed]
|
||||||
|
if missing:
|
||||||
|
print("refuse: required tests did not pass: " + ", ".join(missing), file=sys.stderr)
|
||||||
|
sys.exit(5)
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
detect_vitest() {
|
||||||
|
python3 - "$1" <<'PY'
|
||||||
|
import os, re, sys
|
||||||
|
text = open(sys.argv[1], encoding="utf-8", errors="replace").read()
|
||||||
|
text = re.sub(r"\x1b\[[0-9;]*m", "", text)
|
||||||
|
need = os.environ.get("REQUIRE_FILES", "").split()
|
||||||
|
summary = re.findall(r"^\s*(Test Files|Tests)\s+(.*)$", text, re.M)
|
||||||
|
if any(re.search(r"\b(failed|skipped|todo)\b", rest) for _, rest in summary) or re.search(r"^\s*(FAIL|×)\s", text, re.M):
|
||||||
|
print("refuse: vitest reports failed, skipped or todo tests", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
m = re.search(r"^\s*Tests\s+(\d+) passed \((\d+)\)\s*$", text, re.M)
|
||||||
|
if not m or m.group(1) != m.group(2) or m.group(1) == "0":
|
||||||
|
print("refuse: no all-passing vitest summary", file=sys.stderr)
|
||||||
|
sys.exit(3)
|
||||||
|
missing = [f for f in need if not re.search(r"^\s*✓ (?:\|\w+\| )?" + re.escape(f) + r" \(\d+ tests?\)", text, re.M)]
|
||||||
|
if missing:
|
||||||
|
print("refuse: did not pass: " + ", ".join(missing), file=sys.stderr)
|
||||||
|
sys.exit(5)
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
detect_tap() {
|
||||||
|
python3 - "$1" <<'PY'
|
||||||
|
import re, sys
|
||||||
|
text = open(sys.argv[1], encoding="utf-8", errors="replace").read()
|
||||||
|
counts = dict((k, int(v)) for k, v in re.findall(r"^# (pass|fail|skipped|todo|cancelled) (\d+)\s*$", text, re.M))
|
||||||
|
if re.search(r"^\s*not ok\b", text, re.M) or any(counts.get(k, 0) for k in ("fail", "skipped", "todo", "cancelled")):
|
||||||
|
print("refuse: TAP reports failed, skipped, todo or cancelled tests", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
if counts.get("pass", 0) == 0:
|
||||||
|
print("refuse: TAP reports no passing test", file=sys.stderr)
|
||||||
|
sys.exit(3)
|
||||||
|
PY
|
||||||
|
}
|
||||||
|
|
||||||
|
go_json() {
|
||||||
|
local dir="$1"
|
||||||
|
shift
|
||||||
|
local log err rc=0 dc=0
|
||||||
|
log="$(mktemp)"
|
||||||
|
err="$(mktemp)"
|
||||||
|
(cd "$dir" && go test -json "$@") >"$log" 2>"$err" || rc=$?
|
||||||
|
detect_go "$log" || dc=$?
|
||||||
|
if [[ "$rc" -ne 0 || "$dc" -ne 0 ]]; then
|
||||||
|
cat "$err" >&2 || true
|
||||||
|
python3 -c 'import json,sys
|
||||||
|
for raw in open(sys.argv[1], errors="replace"):
|
||||||
|
try: ev = json.loads(raw)
|
||||||
|
except ValueError: continue
|
||||||
|
out = ev.get("Output", "")
|
||||||
|
if ev.get("Action") == "output" and ("FAIL" in out or "SKIP" in out or "_test.go:" in out):
|
||||||
|
sys.stderr.write(out)' "$log" 2>&1 | tail -n 40 >&2 || true
|
||||||
|
rm -f "$log" "$err"
|
||||||
|
echo "refuse: FAIL go test $* in $dir (test=$rc detect=$dc)" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "go: $(grep -c '"Action":"pass","Package":"[^"]*","Test":"[^"/]*","Elapsed"' "$log") top-level tests passed in $dir ($*)"
|
||||||
|
rm -f "$log" "$err"
|
||||||
|
}
|
||||||
|
|
||||||
|
go_named() {
|
||||||
|
local dir="$1" pkg="$2" flags="$3"
|
||||||
|
shift 3
|
||||||
|
local names=("$@") regex
|
||||||
|
regex="^($(IFS='|'; echo "${names[*]}"))\$"
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
REQUIRE_TESTS="${names[*]}" go_json "$dir" $flags -count=1 -run "$regex" "$pkg"
|
||||||
|
}
|
||||||
|
|
||||||
|
go_pkg_named() {
|
||||||
|
local dir="$1" flags="$2"
|
||||||
|
shift 2
|
||||||
|
local entry pkg name pkgs=()
|
||||||
|
declare -A by=()
|
||||||
|
for entry in "$@"; do
|
||||||
|
pkg="${entry%%:*}"
|
||||||
|
name="${entry#*:}"
|
||||||
|
if [[ -z "${by[$pkg]+x}" ]]; then
|
||||||
|
pkgs+=("$pkg")
|
||||||
|
by[$pkg]="$name"
|
||||||
|
else
|
||||||
|
by[$pkg]="${by[$pkg]} $name"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
for pkg in "${pkgs[@]}"; do
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
go_named "$dir" "$pkg" "$flags" ${by[$pkg]}
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
require_dir() {
|
||||||
|
[[ -d "$1" ]] || {
|
||||||
|
echo "refuse: missing $1 ($2)" >&2
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sibling_clean() {
|
||||||
|
local dir="$1" when="$2" status
|
||||||
|
if ! status="$(git -c safe.directory='*' -C "$dir" status --porcelain 2>&1)"; then
|
||||||
|
printf '%s\n' "$status" >&2
|
||||||
|
echo "refuse: git status failed in $dir ($when)" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if [[ -n "$status" ]]; then
|
||||||
|
printf '%s\n' "$status" | head -n 20 >&2
|
||||||
|
echo "refuse: $dir is not clean $when the consumers stage" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "clean: $dir ($when)"
|
||||||
|
}
|
||||||
|
|
||||||
|
SCRATCH=""
|
||||||
|
scratch_cleanup() {
|
||||||
|
if [[ -n "$SCRATCH" && -d "$SCRATCH" ]]; then
|
||||||
|
chmod -R u+w -- "${SCRATCH:?}" 2>/dev/null || true
|
||||||
|
rm -rf -- "${SCRATCH:?}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
scratch_init() {
|
||||||
|
SCRATCH="$(mktemp -d)"
|
||||||
|
trap scratch_cleanup EXIT
|
||||||
|
}
|
||||||
|
|
||||||
|
consumer_modfile() {
|
||||||
|
local dir="$1" name="$2" out
|
||||||
|
out="$SCRATCH/modfile/$name"
|
||||||
|
mkdir -p "$out"
|
||||||
|
cp -- "$dir/go.mod" "$out/go.mod"
|
||||||
|
if ! grep -q "replace git.golem15.com/golem15/summercms =>" "$out/go.mod"; then
|
||||||
|
printf '\nreplace git.golem15.com/golem15/summercms => %s\n' "$ROOT" >>"$out/go.mod"
|
||||||
|
else
|
||||||
|
python3 - "$out/go.mod" "$ROOT" <<'PY'
|
||||||
|
import re, sys
|
||||||
|
p, root = sys.argv[1], sys.argv[2]
|
||||||
|
text = open(p, encoding="utf-8").read()
|
||||||
|
text = re.sub(r"replace\s+git\.golem15\.com/golem15/summercms\s+=>\s+\S+", f"replace git.golem15.com/golem15/summercms => {root}", text)
|
||||||
|
open(p, "w", encoding="utf-8").write(text)
|
||||||
|
PY
|
||||||
|
fi
|
||||||
|
{
|
||||||
|
[[ -f "$dir/go.sum" ]] && cat -- "$dir/go.sum"
|
||||||
|
[[ -f "$ROOT/go.sum" ]] && cat -- "$ROOT/go.sum"
|
||||||
|
} | LC_ALL=C sort -u >"$out/go.sum"
|
||||||
|
printf '%s\n' "$out/go.mod"
|
||||||
|
}
|
||||||
|
|
||||||
|
workspace_check() {
|
||||||
|
local dir="$1" flags="${2:-}" got rgot rwant
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
got="$( (cd "$dir" && go list $flags -m -f '{{if .Replace}}{{.Replace.Dir}}{{else}}{{.Dir}}{{end}}' git.golem15.com/golem15/summercms 2>/dev/null) || true)"
|
||||||
|
rgot="$(realpath -e -- "$got" 2>/dev/null || true)"
|
||||||
|
rwant="$(realpath -e -- "$ROOT" 2>/dev/null || true)"
|
||||||
|
if [[ -z "$got" || -z "$rgot" || "$rgot" != "$rwant" ]]; then
|
||||||
|
echo "refuse: $dir resolves git.golem15.com/golem15/summercms to ${got:-<nothing>}, not $ROOT" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "workspace: $dir resolves framework to $rwant"
|
||||||
|
}
|
||||||
|
|
||||||
|
docker_up() {
|
||||||
|
command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
run_go() {
|
||||||
|
(cd "$ROOT" && go vet ./...)
|
||||||
|
echo "vet: $ROOT (./...)"
|
||||||
|
(cd "$ROOT" && go vet -tags summercms_mcp ./...)
|
||||||
|
echo "vet: $ROOT (-tags summercms_mcp ./...)"
|
||||||
|
(cd "$ROOT" && go test -short -count=1 ./...)
|
||||||
|
echo "short: $ROOT (./...)"
|
||||||
|
go_pkg_named "$ROOT" "-short" "${GO_TESTS[@]}"
|
||||||
|
go_pkg_named "$ROOT" "-short -tags summercms_mcp" "${GO_MCP_TESTS[@]}"
|
||||||
|
echo "phase37 go passed"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_docker() {
|
||||||
|
if ! docker_up; then
|
||||||
|
echo "refuse: the docker stage needs a reachable Docker daemon (testcontainers)" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
go_pkg_named "$ROOT" "-timeout 15m" "${DOCKER_TESTS[@]}"
|
||||||
|
echo "phase37 docker passed"
|
||||||
|
}
|
||||||
|
|
||||||
|
docker_gate() {
|
||||||
|
if docker_up; then
|
||||||
|
if bash "${BASH_SOURCE[0]}" --docker; then
|
||||||
|
echo "PASS docker"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
echo "FAIL docker"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "NOT RUN docker: no reachable Docker daemon on this host" >&2
|
||||||
|
if [[ "${PHASE37_ALLOW_NO_DOCKER:-0}" != "1" ]]; then
|
||||||
|
echo "FAIL docker: set PHASE37_ALLOW_NO_DOCKER=1 or run --docker on a Docker host" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
run_admin() {
|
||||||
|
require_dir "$ROOT/admin" "admin"
|
||||||
|
local log rc=0 dc=0
|
||||||
|
log="$(mktemp)"
|
||||||
|
npm --prefix "$ROOT/admin" run test >"$log" 2>&1 || rc=$?
|
||||||
|
REQUIRE_FILES="${ADMIN_FILES[*]}" detect_vitest "$log" || dc=$?
|
||||||
|
if [[ "$rc" -ne 0 || "$dc" -ne 0 ]]; then
|
||||||
|
grep -E '(FAIL|×|Error|expected)' "$log" | head -n 40 >&2 || true
|
||||||
|
tail -n 20 "$log" >&2
|
||||||
|
rm -f "$log"
|
||||||
|
echo "refuse: FAIL npm run test in admin (test=$rc detect=$dc)" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "vitest (admin): $(grep -E '^\s*Tests\s' "$log" | tr -s ' ')"
|
||||||
|
rm -f "$log"
|
||||||
|
npm --prefix "$ROOT/admin" run typecheck >/dev/null
|
||||||
|
echo "typecheck: admin"
|
||||||
|
(cd "$ROOT" && bash scripts/check-admin-openapi.sh --check)
|
||||||
|
(cd "$ROOT" && bash scripts/check-admin-dist.sh)
|
||||||
|
echo "phase37 admin passed"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_docs() {
|
||||||
|
go_named "$ROOT" ./cmd/summer "" TestDocsTree
|
||||||
|
(cd "$ROOT" && go run ./cmd/summer docs:build --check)
|
||||||
|
echo "phase37 docs passed"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_consumers() {
|
||||||
|
require_dir "$JOURNAL_PLUGIN" "sm-journal-plugin"
|
||||||
|
require_dir "$VUE_JOURNAL_LAYER" "vue-journal-layer"
|
||||||
|
scratch_init
|
||||||
|
sibling_clean "$JOURNAL_PLUGIN" before
|
||||||
|
sibling_clean "$VUE_JOURNAL_LAYER" before
|
||||||
|
|
||||||
|
export GOWORK=off GOPROXY=off
|
||||||
|
local jmod mflags
|
||||||
|
jmod="$(consumer_modfile "$JOURNAL_PLUGIN" sm-journal-plugin)"
|
||||||
|
mflags="-mod=mod -modfile=$jmod"
|
||||||
|
workspace_check "$JOURNAL_PLUGIN" "$mflags"
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
(cd "$JOURNAL_PLUGIN" && go vet $mflags ./...)
|
||||||
|
echo "vet: $JOURNAL_PLUGIN"
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
(cd "$JOURNAL_PLUGIN" && go test $mflags -short -count=1 ./...)
|
||||||
|
echo "short: $JOURNAL_PLUGIN"
|
||||||
|
|
||||||
|
local log rc=0 dc=0
|
||||||
|
log="$(mktemp)"
|
||||||
|
npm --prefix "$JOURNAL_PLUGIN" test >"$log" 2>&1 || rc=$?
|
||||||
|
detect_vitest "$log" || dc=$?
|
||||||
|
if [[ "$rc" -ne 0 || "$dc" -ne 0 ]]; then
|
||||||
|
tail -n 30 "$log" >&2
|
||||||
|
rm -f "$log"
|
||||||
|
echo "refuse: FAIL npm test in $JOURNAL_PLUGIN" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "vitest (sm-journal-plugin): $(grep -E '^\s*Tests\s' "$log" | tr -s ' ')"
|
||||||
|
rm -f "$log"
|
||||||
|
|
||||||
|
log="$(mktemp)"
|
||||||
|
rc=0
|
||||||
|
dc=0
|
||||||
|
npm --prefix "$VUE_JOURNAL_LAYER" test >"$log" 2>&1 || rc=$?
|
||||||
|
detect_tap "$log" || dc=$?
|
||||||
|
if [[ "$rc" -ne 0 || "$dc" -ne 0 ]]; then
|
||||||
|
tail -n 30 "$log" >&2
|
||||||
|
rm -f "$log"
|
||||||
|
echo "refuse: FAIL npm test in $VUE_JOURNAL_LAYER" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "tap (vue-journal-layer): $(grep -E '^# pass ' "$log" | tail -n 1)"
|
||||||
|
rm -f "$log"
|
||||||
|
|
||||||
|
sibling_clean "$JOURNAL_PLUGIN" after
|
||||||
|
sibling_clean "$VUE_JOURNAL_LAYER" after
|
||||||
|
echo "phase37 consumers passed"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_marker() {
|
||||||
|
if ! git -C "$ROOT" rev-parse --verify -q "$PHASE37_BASE_TAG^{commit}" >/dev/null; then
|
||||||
|
echo "refuse: missing tag $PHASE37_BASE_TAG in $ROOT" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
local pattern hits
|
||||||
|
pattern="$(IFS='|'; echo "${APP_NAMES[*]}")"
|
||||||
|
hits="$(git -C "$ROOT" diff -U0 "$PHASE37_BASE_TAG" HEAD -- \
|
||||||
|
'modules/*.go' 'modules/**/*.go' 'cmd/**/*.go' 'internal/**/*.go' \
|
||||||
|
'modules/**/README.md' 'cmd/**/README.md' 'internal/**/README.md' 'docs' \
|
||||||
|
':(exclude)*_test.go' ':(exclude)**/*_test.go' ':(exclude)**/testdata/**' |
|
||||||
|
PATTERN="$pattern" python3 -c '
|
||||||
|
import os, re, sys
|
||||||
|
pat = re.compile(os.environ["PATTERN"], re.I)
|
||||||
|
path, line = "", 0
|
||||||
|
for raw in sys.stdin:
|
||||||
|
if raw.startswith("+++ "):
|
||||||
|
path = raw[6:].rstrip("\n") if raw.startswith("+++ b/") else ""
|
||||||
|
continue
|
||||||
|
m = re.match(r"^@@ -\S+ \+(\d+)", raw)
|
||||||
|
if m:
|
||||||
|
line = int(m.group(1))
|
||||||
|
continue
|
||||||
|
if raw.startswith("+") and not raw.startswith("+++"):
|
||||||
|
if path and pat.search(raw[1:]):
|
||||||
|
print(f"{path}:{line}: {raw[1:].strip()[:120]}")
|
||||||
|
line += 1
|
||||||
|
')"
|
||||||
|
if [[ -n "$hits" ]]; then
|
||||||
|
printf '%s\n' "$hits" | head -n 40 >&2
|
||||||
|
echo "refuse: framework lines added since $PHASE37_BASE_TAG name a consuming application" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "marker: no consuming-app names added since $PHASE37_BASE_TAG"
|
||||||
|
echo "phase37 marker passed"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_all() {
|
||||||
|
local stage
|
||||||
|
for stage in go admin docs consumers marker; do
|
||||||
|
if bash "${BASH_SOURCE[0]}" "--$stage"; then
|
||||||
|
echo "PASS $stage"
|
||||||
|
else
|
||||||
|
echo "FAIL $stage"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
docker_gate || exit 1
|
||||||
|
echo "Phase 37 gate passed"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_stage() {
|
||||||
|
case "$1" in
|
||||||
|
--go | go) run_go ;;
|
||||||
|
--docker | docker) run_docker ;;
|
||||||
|
--docker-gate) docker_gate ;;
|
||||||
|
--admin | admin) run_admin ;;
|
||||||
|
--docs | docs) run_docs ;;
|
||||||
|
--consumers | consumers) run_consumers ;;
|
||||||
|
--marker | marker) run_marker ;;
|
||||||
|
--all | all) run_all ;;
|
||||||
|
*) usage ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ "$#" -eq 0 ]]; then
|
||||||
|
usage
|
||||||
|
fi
|
||||||
|
if [[ "$#" -eq 1 ]]; then
|
||||||
|
run_stage "$1"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
for arg in "$@"; do
|
||||||
|
if bash "${BASH_SOURCE[0]}" "$arg"; then
|
||||||
|
echo "PASS ${arg#--}"
|
||||||
|
else
|
||||||
|
echo "FAIL ${arg#--}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
Reference in New Issue
Block a user