diff --git a/assets/src/admin/logs/apiService.ts b/assets/src/admin/logs/apiService.ts index 1a774f3..14d29a5 100644 --- a/assets/src/admin/logs/apiService.ts +++ b/assets/src/admin/logs/apiService.ts @@ -1,17 +1,18 @@ +/** + * WordPress dependencies + */ +import apiFetch from '@wordpress/api-fetch'; + +/** + * Internal dependencies + */ import type { APIResponse, fetchReturn, FilterOptions, - OneLogsDataType, + SharedSite, } from './types'; -import apiFetch from '@wordpress/api-fetch'; -import { NONCE, API_KEY } from '../../js/constants'; - -declare global { - interface Window { - OneLogsData?: OneLogsDataType; - } -} +import { REST_NAMESPACE, SHARED_SITES } from '../../js/constants'; type FetchOptions = { filters?: { @@ -19,7 +20,6 @@ type FetchOptions = { }; queryParams?: URLSearchParams; returnKey?: string; - headers?: Record< string, string >; }; export const fetchLogs = async ( filters: FilterOptions ) => { @@ -31,39 +31,23 @@ export const fetchLogs = async ( filters: FilterOptions ) => { date_to: filters.date_to ? `${ filters.date_to } 23:59:59` : undefined, }; - if ( filters.site_url === 'governing-site' ) { - formattedFilters.current_site_logs = true; + const isBrandSite = + !! filters.site_url && filters.site_url !== 'governing-site'; + + // The governing site fetches a selected brand site's logs for the browser. + formattedFilters.current_site_logs = ! isBrandSite; + formattedFilters.include_shared_sites = isBrandSite; + if ( ! isBrandSite ) { formattedFilters.site_url = undefined; - formattedFilters.include_shared_sites = false; - } else { - formattedFilters.current_site_logs = false; - formattedFilters.include_shared_sites = true; } - if ( ! formattedFilters.current_site_logs ) { - const queryParams = new URLSearchParams(); - formattedFilters.include_shared_sites = true; - - Object.entries( formattedFilters ).forEach( ( [ key, value ] ) => { - if ( value !== undefined && value !== null && key !== 'site_id' ) { - queryParams.append( key, String( value ) ); - } - } ); - - const apiResponse = await oneLogsFetch< APIResponse >( 'logs', { - queryParams, - } ); - - return { - logs: apiResponse?.data || [], - total: apiResponse?.meta.total || 0, - pages: apiResponse?.meta.total_pages || 1, - errors: apiResponse?.meta.errors, - }; - } const queryParams = new URLSearchParams(); Object.entries( formattedFilters ).forEach( ( [ key, value ] ) => { - if ( value !== undefined && value !== null ) { + if ( + value !== undefined && + value !== null && + ! ( isBrandSite && key === 'site_id' ) + ) { queryParams.append( key, String( value ) ); } } ); @@ -73,10 +57,11 @@ export const fetchLogs = async ( filters: FilterOptions ) => { } ); return { - logs: apiResponse.data, - total: apiResponse.meta.total, - pages: apiResponse.meta.total_pages, - errors: null, + // A missing list is no logs, never a crash. + logs: Array.isArray( apiResponse?.data ) ? apiResponse.data : [], + total: apiResponse?.meta?.total || 0, + pages: apiResponse?.meta?.total_pages || 1, + errors: isBrandSite ? apiResponse?.meta?.errors : null, }; }; @@ -104,12 +89,21 @@ export const fetchUsers = async ( filters: FilterOptions ): Promise< APIResponse > => oneLogsFetch( 'logs/users', { filters } ); -export const fetchSharedSites = async () => - oneLogsFetch( 'shared-sites', { returnKey: 'shared_sites' } ); - -export const fetchSiteType = async () => - oneLogsFetch( 'site-type', { returnKey: 'site_type' } ); - +/** + * Gets the governing site's brand sites, which the page already has. + */ +export const fetchSharedSites = async (): Promise< SharedSite[] > => + SHARED_SITES; + +/** + * Requests a OneLogs route on this site. + * + * WordPress sets up apiFetch with the REST root and nonce, so requests only need the path. + * Rejects with the REST error, like `{ code, message }`, when the route fails. + * + * @param endpoint The route, relative to the OneLogs namespace. + * @param options The query, and the key of the response to return. + */ const oneLogsFetch = async < T extends fetchReturn >( endpoint: string, options: FetchOptions = {} @@ -121,25 +115,15 @@ const oneLogsFetch = async < T extends fetchReturn >( if ( queryParams ) { query = `?${ queryParams.toString() }`; } else if ( filters?.site_url && filters.site_url !== 'governing-site' ) { - query = `?site_url=${ filters.site_url }`; + query = `?${ new URLSearchParams( { + site_url: filters.site_url, + } ).toString() }`; } - apiFetch.use( apiFetch.createNonceMiddleware( NONCE ) ); - - apiFetch.use( ( fetchOptions, next ) => { - fetchOptions.headers = { - ...( fetchOptions.headers || {} ), - 'X-OneLogs-Token': API_KEY, - }; - return next( fetchOptions ); - } ); - - const apiResponse = await apiFetch( { - path: `/onelogs/v1/${ endpoint }${ query }`, + const result = await apiFetch< APIResponse >( { + path: `/${ REST_NAMESPACE }/${ endpoint }${ query }`, method: 'GET', } ); - const result = apiResponse as APIResponse; - - return ( returnKey ? result[ returnKey ] ?? [] : result ) as T; + return ( returnKey ? result?.[ returnKey ] ?? [] : result ) as T; }; diff --git a/assets/src/admin/logs/components/FiltersPanel.tsx b/assets/src/admin/logs/components/FiltersPanel.tsx index f08cbc8..22963a0 100644 --- a/assets/src/admin/logs/components/FiltersPanel.tsx +++ b/assets/src/admin/logs/components/FiltersPanel.tsx @@ -1,14 +1,9 @@ -import React, { useEffect, useRef, useState } from 'react'; +import React, { useEffect, useRef } from 'react'; import { __ } from '@wordpress/i18n'; import { Button, SelectControl, TextControl } from '@wordpress/components'; import { debounce } from '@wordpress/compose'; -import { fetchSiteType } from '../apiService'; -import type { - fetchReturn, - FilterOptions, - SharedSite, - UserOption, -} from '../types'; +import { SITE_TYPE } from '../../../js/constants'; +import type { FilterOptions, SharedSite, UserOption } from '../types'; interface FiltersPanelProps { localSearch: string; @@ -51,21 +46,9 @@ export const FiltersPanel: React.FC< FiltersPanelProps > = ( { ( ( searchValue: string | undefined ) => void ) | null >( null ); - const [ siteType, setSiteType ] = useState< string | fetchReturn >( '' ); const today = new Date().toISOString().split( 'T' )[ 0 ]; - const loadSiteType = async () => { - try { - const data = await fetchSiteType(); - setSiteType( data ); - } catch ( err ) { - // eslint-disable-next-line no-console - console.log( err ); - } - }; - useEffect( () => { - loadSiteType(); const debouncedFn = debounce( ( searchValue: unknown ) => { handleFilterChange( 'search', searchValue as string ); }, 500 ); @@ -76,7 +59,7 @@ export const FiltersPanel: React.FC< FiltersPanelProps > = ( { return (
- { siteType && siteType === 'governing-site' && ( + { SITE_TYPE === 'governing-site' && ( { const [ logs, setLogs ] = useState< LogEntry[] >( [] ); @@ -55,7 +56,7 @@ const LogsDashboard: React.FC = () => { try { const result = await apiFetchLogs( filters ); - setLogs( result.logs as LogEntry[] ); + setLogs( ( result.logs ?? [] ) as LogEntry[] ); setTotalLogs( result.total ); setTotalPages( result.pages ); @@ -69,10 +70,15 @@ const LogsDashboard: React.FC = () => { ); } } catch ( err ) { + // Clear the previous site's logs, so they're not shown under this error. + setLogs( [] ); + setTotalLogs( 0 ); + setTotalPages( 1 ); setError( - err instanceof Error - ? err.message - : __( 'An error occurred while fetching logs', 'onelogs' ) + getErrorMessage( + err, + __( 'An error occurred while fetching logs', 'onelogs' ) + ) ); } finally { setLoading( false ); @@ -164,27 +170,46 @@ const LogsDashboard: React.FC = () => { const loadContexts = useCallback( async () => { try { const data = await apiFetchContexts( filters ); - setContexts( data ); - } catch { - setError( __( 'Error fetching contexts:', 'onelogs' ) ); + setContexts( Array.isArray( data ) ? data : [] ); + } catch ( err ) { + setContexts( [] ); + setError( + getErrorMessage( + err, + __( 'Error fetching contexts.', 'onelogs' ) + ) + ); } }, [ filters ] ); const loadConnectors = useCallback( async () => { try { const data = await apiFetchConnectors( filters ); - setConnectors( data ); - } catch { - setError( __( 'Error fetching connectors:', 'onelogs' ) ); + setConnectors( Array.isArray( data ) ? data : [] ); + } catch ( err ) { + setConnectors( [] ); + setError( + getErrorMessage( + err, + __( 'Error fetching connectors.', 'onelogs' ) + ) + ); } }, [ filters ] ); const loadUsers = useCallback( async () => { try { const response = await apiFetchUsers( filters ); - setUsers( response.data as UserOption[] ); - } catch { - setError( __( 'Error fetching users:', 'onelogs' ) ); + setUsers( + Array.isArray( response?.data ) + ? ( response.data as UserOption[] ) + : [] + ); + } catch ( err ) { + setUsers( [] ); + setError( + getErrorMessage( err, __( 'Error fetching users.', 'onelogs' ) ) + ); } }, [ filters ] ); @@ -193,16 +218,22 @@ const LogsDashboard: React.FC = () => { const response = await apiFetchSharedSites(); setSharedSites( response as SharedSite[] ); } catch { - setError( __( 'Error fetching shared sites:', 'onelogs' ) ); + setError( __( 'Error fetching shared sites.', 'onelogs' ) ); } }, [] ); const loadActions = useCallback( async () => { try { const data = await fetchActions( filters ); - setActions( data ); - } catch { - setError( __( 'Error fetching shared sites:', 'onelogs' ) ); + setActions( Array.isArray( data ) ? data : [] ); + } catch ( err ) { + setActions( [] ); + setError( + getErrorMessage( + err, + __( 'Error fetching actions.', 'onelogs' ) + ) + ); } }, [ filters ] ); diff --git a/assets/src/admin/logs/types.ts b/assets/src/admin/logs/types.ts index f071fd9..8a29a4d 100644 --- a/assets/src/admin/logs/types.ts +++ b/assets/src/admin/logs/types.ts @@ -83,21 +83,9 @@ export type APIResponse = { export type StringArrayResponse = string[]; -export type fetchReturn = - | APIResponse - | StringArrayResponse - | string - | SharedSite[]; +export type fetchReturn = APIResponse | StringArrayResponse; -export interface SharedSite { - api_key: string; - id: string; - name: string; - url: string; -} - -export interface OneLogsDataType { - restUrl: string; - nonce: string; - apiKey: string; -} +/** + * A brand site, without its API key, which never leaves the server. + */ +export type { OneLogsSharedSite as SharedSite } from '@/types/global'; diff --git a/assets/src/admin/onboarding/index.tsx b/assets/src/admin/onboarding/index.tsx index faad83a..2e71b04 100644 --- a/assets/src/admin/onboarding/index.tsx +++ b/assets/src/admin/onboarding/index.tsx @@ -1,17 +1,5 @@ import { createRoot } from 'react-dom/client'; -import OnboardingScreen, { type SiteType } from './page'; - -interface OneLogsSettings { - nonce: string; - siteType: SiteType | ''; - setupUrl: string; -} - -declare global { - interface Window { - OneLogsSettings: OneLogsSettings; - } -} +import OnboardingScreen from './page'; // Render to the target element. const target = document.getElementById( 'onelogs-site-selection-modal' ); diff --git a/assets/src/admin/onboarding/page.tsx b/assets/src/admin/onboarding/page.tsx index aa56c21..23371c5 100644 --- a/assets/src/admin/onboarding/page.tsx +++ b/assets/src/admin/onboarding/page.tsx @@ -20,12 +20,9 @@ interface NoticeState { message: string; } -const { nonce, setupUrl, siteType: initialSiteType } = window.OneLogsSettings; - -/** - * Create NONCE middleware for apiFetch - */ -apiFetch.use( apiFetch.createNonceMiddleware( nonce ) ); +// WordPress sets up apiFetch's nonce and root URL, so no middleware is needed here. +const setupUrl = window.OneLogsSettings?.setupUrl ?? ''; +const initialSiteType = window.OneLogsSettings?.siteType ?? ''; const SiteTypeSelector = ( { value, diff --git a/assets/src/admin/settings/index.js b/assets/src/admin/settings/index.js deleted file mode 100644 index a8e7d47..0000000 --- a/assets/src/admin/settings/index.js +++ /dev/null @@ -1,213 +0,0 @@ -import { useState, useEffect } from 'react'; -import { createRoot } from 'react-dom/client'; -import { __ } from '@wordpress/i18n'; -import { Snackbar } from '@wordpress/components'; -import SiteTable from '../../components/SiteTable'; -import SiteModal from '../../components/SiteModal'; -import SiteSettings from '../../components/SiteSettings'; -import { API_NAMESPACE, NONCE } from '../../js/constants'; - -/** - * Settings page component for OneLogs plugin. - * - * @return {import('react').ReactElement} Rendered component. - */ -const OneLogsSettingsPage = () => { - const [ siteType, setSiteType ] = useState( '' ); - const [ showModal, setShowModal ] = useState( false ); - const [ editingIndex, setEditingIndex ] = useState( null ); - const [ sites, setSites ] = useState( [] ); - const [ formData, setFormData ] = useState( { - name: '', - url: '', - api_key: '', - } ); - const [ notice, setNotice ] = useState( { - type: 'success', - message: '', - } ); - - useEffect( () => { - const fetchData = async () => { - try { - const [ siteTypeRes, sitesRes ] = await Promise.all( [ - fetch( `${ API_NAMESPACE }/site-type`, { - headers: { - 'Content-Type': 'application/json', - 'X-WP-NONCE': NONCE, - }, - } ), - fetch( `${ API_NAMESPACE }/shared-sites`, { - headers: { - 'Content-Type': 'application/json', - 'X-WP-NONCE': NONCE, - }, - } ), - ] ); - - const siteTypeData = await siteTypeRes.json(); - const sitesData = await sitesRes.json(); - - if ( siteTypeData?.site_type ) { - setSiteType( siteTypeData?.site_type ); - } - if ( Array.isArray( sitesData?.shared_sites ) ) { - setSites( sitesData?.shared_sites ); - } - } catch { - setNotice( { - type: 'error', - message: __( - 'Error fetching site type or Brand sites.', - 'onelogs' - ), - } ); - } - }; - - fetchData(); - }, [] ); - - const handleFormSubmit = async () => { - const updated = - editingIndex !== null - ? sites.map( ( item, i ) => - i === editingIndex ? formData : item - ) - : [ ...sites, formData ]; - - try { - const response = await fetch( `${ API_NAMESPACE }/shared-sites`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-WP-NONCE': NONCE, - }, - body: JSON.stringify( { sites_data: updated } ), - } ); - if ( ! response.ok ) { - return response; - } - - if ( sites.length === 0 ) { - window.location.reload(); - } - - setSites( updated ); - setNotice( { - type: 'success', - message: __( 'Brand Site saved successfully.', 'onelogs' ), - } ); - } catch { - setNotice( { - type: 'error', - message: __( - 'Error saving Brand site. Please try again later.', - 'onelogs' - ), - } ); - } - - setFormData( { name: '', url: '', api_key: '' } ); - setShowModal( false ); - setEditingIndex( null ); - }; - - const handleDelete = async ( index ) => { - const updated = sites.filter( ( _, i ) => i !== index ); - - try { - const response = await fetch( `${ API_NAMESPACE }/shared-sites`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-WP-NONCE': NONCE, - }, - body: JSON.stringify( { sites_data: updated } ), - } ); - if ( ! response.ok ) { - setNotice( { - type: 'error', - message: __( - 'Failed to delete Brand site. Please try again.', - 'onelogs' - ), - } ); - return; - } - setNotice( { - type: 'success', - message: __( 'Brand Site deleted successfully.', 'onelogs' ), - } ); - setSites( updated ); - if ( updated.length === 0 ) { - window.location.reload(); - } else { - document.body.classList.remove( 'onelogs-missing-brand-sites' ); - } - } catch { - setNotice( { - type: 'error', - message: __( - 'Error deleting Brand site. Please try again later.', - 'onelogs' - ), - } ); - } - }; - - return ( - <> - { notice?.message?.length > 0 && ( - setNotice( null ) } - className={ - notice?.type === 'error' - ? 'onelogs-error-notice' - : 'onelogs-success-notice' - } - > - { notice?.message } - - ) } - - { siteType === 'brand-site' && } - - { siteType === 'governing-site' && ( - - ) } - - { showModal && ( - { - setShowModal( false ); - setEditingIndex( null ); - setFormData( { name: '', url: '', api_key: '' } ); - } } - editing={ editingIndex !== null } - originalData={ sites[ editingIndex ] } - /> - ) } - - ); -}; - -// Render to Gutenberg admin page with ID: onelogs-settings-page -const target = document.getElementById( 'onelogs-settings-page' ); -if ( target ) { - const root = createRoot( target ); - root.render( ); -} diff --git a/assets/src/admin/settings/index.tsx b/assets/src/admin/settings/index.tsx new file mode 100644 index 0000000..01b8f0d --- /dev/null +++ b/assets/src/admin/settings/index.tsx @@ -0,0 +1,16 @@ +/** + * External dependencies + */ +import { createRoot } from 'react-dom/client'; + +/** + * Internal dependencies + */ +import SettingsPage from './page'; + +// Render to Gutenberg admin page with ID: onelogs-settings-page +const target = document.getElementById( 'onelogs-settings-page' ); +if ( target ) { + const root = createRoot( target ); + root.render( ); +} diff --git a/assets/src/admin/settings/page.tsx b/assets/src/admin/settings/page.tsx new file mode 100644 index 0000000..d92b089 --- /dev/null +++ b/assets/src/admin/settings/page.tsx @@ -0,0 +1,255 @@ +/** + * External dependencies + */ +import { useState, useRef, useCallback } from 'react'; + +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; +import { Notice, Snackbar } from '@wordpress/components'; +import apiFetch from '@wordpress/api-fetch'; + +/** + * Internal dependencies + */ +import SiteTable from '@/components/SiteTable'; +import SiteModal from '@/components/SiteModal'; +import SiteSettings from '@/components/SiteSettings'; +import { REST_NAMESPACE, SHARED_SITES, SITE_TYPE } from '@/js/constants'; +import { getErrorMessage } from '@/js/utils'; + +export interface NoticeType { + // Set by the settings page, so each notice gets its own Snackbar. + id?: number; + type: 'success' | 'error' | 'warning' | 'info'; + message: string; +} + +export interface BrandSite { + id?: string; + name: string; + url: string; + // Only set while the admin types a key. The stored key never reaches the browser. + api_key?: string; +} + +export const defaultBrandSite: BrandSite = { + name: '', + url: '', + api_key: '', +}; + +export type EditingIndex = number | null; + +const SHARED_SITES_ENDPOINT = `/${ REST_NAMESPACE }/shared-sites`; + +interface SharedSitesResponse { + shared_sites?: BrandSite[]; +} + +interface DeleteSiteResponse extends SharedSitesResponse { + governing_site_notified?: boolean; + message?: string; +} + +/** + * Reloads the page, so the menu shows or hides the Logs page with the brand sites. + */ +const reloadPage = () => window.location.reload(); + +const SettingsPage = () => { + const [ showModal, setShowModal ] = useState( false ); + const [ editingIndex, setEditingIndex ] = useState< EditingIndex >( null ); + const [ sites, setSites ] = useState< BrandSite[] >( SHARED_SITES ); + const [ formData, setFormData ] = useState< BrandSite >( defaultBrandSite ); + const [ notice, setNoticeState ] = useState< NoticeType | null >( null ); + const noticeId = useRef( 0 ); + + // A new id remounts the Snackbar, which restarts its timer for the new notice. + const setNotice = useCallback( ( next: NoticeType | null ) => { + noticeId.current += 1; + setNoticeState( next ? { ...next, id: noticeId.current } : null ); + }, [] ); + + // Kept until dismissed, since each one asks the admin to finish disconnecting a brand site. + const [ disconnectNotices, setDisconnectNotices ] = useState< + NoticeType[] + >( [] ); + + const closeModal = () => { + setShowModal( false ); + setEditingIndex( null ); + setFormData( defaultBrandSite ); + }; + + const handleFormSubmit = async (): Promise< boolean | string > => { + const updated: BrandSite[] = + editingIndex !== null + ? sites.map( ( item, i ) => + i === editingIndex ? formData : item + ) + : [ ...sites, formData ]; + + try { + // The server health-checks new or changed sites before saving them. + const data = await apiFetch< SharedSitesResponse >( { + path: SHARED_SITES_ENDPOINT, + method: 'POST', + data: { sites_data: updated }, + } ); + + if ( ! data?.shared_sites ) { + return false; + } + + if ( sites.length === 0 ) { + reloadPage(); + } + + setSites( data.shared_sites ); + closeModal(); + setNotice( { + type: 'success', + message: __( 'Brand Site saved successfully.', 'onelogs' ), + } ); + return true; + } catch ( error ) { + // The modal stays open with the server's message, so the admin can fix the input and retry. + return getErrorMessage( error, '' ) || false; + } + }; + + const handleDelete = async ( index: number | null ): Promise< void > => { + const removedSite = index !== null ? sites[ index ] : undefined; + + if ( ! removedSite ) { + return; + } + + let response: DeleteSiteResponse; + + try { + // The server also tells the brand site to disconnect, with the key it stored. + response = await apiFetch< DeleteSiteResponse >( { + path: `${ SHARED_SITES_ENDPOINT }/${ encodeURIComponent( + removedSite.id ?? '' + ) }`, + method: 'DELETE', + } ); + } catch ( error ) { + setNotice( { + type: 'error', + message: getErrorMessage( + error, + __( + 'Failed to delete Brand site. Please try again.', + 'onelogs' + ) + ), + } ); + return; + } + + const remaining = + response?.shared_sites ?? + sites.filter( ( site ) => site.id !== removedSite.id ); + + setSites( remaining ); + + if ( response?.governing_site_notified === false && response.message ) { + const disconnectNotice: NoticeType = { + type: 'warning', + message: response.message, + }; + + setDisconnectNotices( ( notices ) => [ + ...notices.filter( + ( item ) => item.message !== disconnectNotice.message + ), + disconnectNotice, + ] ); + } else { + setNotice( { + type: 'success', + message: + response?.message || + __( 'Brand Site deleted successfully.', 'onelogs' ), + } ); + } + + // Keep the page while a disconnect notice needs reading. + if ( + remaining.length === 0 && + response?.governing_site_notified !== false + ) { + reloadPage(); + } + }; + + return ( + <> + { !! notice && notice.message.length > 0 && ( + setNotice( null ) } + className={ + notice.type === 'error' + ? 'onelogs-error-notice' + : 'onelogs-success-notice' + } + > + { notice.message } + + ) } + + { disconnectNotices.map( ( disconnectNotice ) => ( + + setDisconnectNotices( ( notices ) => + notices.filter( + ( item ) => item !== disconnectNotice + ) + ) + } + > + { disconnectNotice.message } + + ) ) } + + { SITE_TYPE === 'brand-site' && } + + { SITE_TYPE === 'governing-site' && ( + + ) } + + { showModal && ( + + ) } + + ); +}; + +export default SettingsPage; diff --git a/assets/src/components/SiteModal.tsx b/assets/src/components/SiteModal.tsx index 49241bf..6b748fb 100644 --- a/assets/src/components/SiteModal.tsx +++ b/assets/src/components/SiteModal.tsx @@ -1,23 +1,25 @@ -import { useState, useMemo } from 'react'; +/** + * External dependencies + */ +import { useMemo, useState } from 'react'; + +/** + * WordPress dependencies + */ import { + Button, Modal, + Notice, TextControl, TextareaControl, - Button, - Notice, } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { isValidUrl } from '../js/utils'; - -interface BrandSite { - name: string; - url: string; - api_key: string; -} +import type { BrandSite } from '@/admin/settings/page'; +import { isValidUrl, normalizeUrl } from '@/js/utils'; interface ErrorsType { name: string; @@ -32,14 +34,17 @@ const SiteModal = ( { onSubmit, onClose, editing, + sites, originalData, }: { formData: BrandSite; setFormData: ( data: BrandSite ) => void; - onSubmit: () => Promise< Response >; + // Resolves true on success, or false or the server's error message on failure. + onSubmit: () => Promise< boolean | string >; onClose: () => void; editing: boolean; - originalData?: BrandSite | undefined; + sites: BrandSite[]; + originalData: BrandSite | undefined; } ) => { const [ errors, setErrors ] = useState< ErrorsType >( { name: '', @@ -50,12 +55,32 @@ const SiteModal = ( { const [ showNotice, setShowNotice ] = useState( false ); const [ isProcessing, setIsProcessing ] = useState( false ); + // A blank API key means the user hasn't typed one yet. When editing, it keeps the stored key. + const typedApiKey = ( formData.api_key ?? '' ).trim(); + const needsApiKey = + ! editing || + normalizeUrl( formData.url ) !== + normalizeUrl( originalData?.url ?? '' ); + + // Check if form data has changed from original data (only for editing mode) + const hasChanges = useMemo( () => { + if ( ! editing ) { + return true; + } // Always allow submission for new sites + + return ( + formData.name !== originalData?.name || + formData.url !== originalData?.url || + typedApiKey !== '' + ); + }, [ editing, formData, originalData, typedApiKey ] ); + const handleSubmit = async (): Promise< void > => { // Validate inputs let siteUrlError = ''; if ( ! formData.url.trim() ) { siteUrlError = __( 'Site URL is required.', 'onelogs' ); - } else if ( ! isValidUrl( formData.url ) ) { + } else if ( ! isValidUrl( formData.url.trim() ) ) { siteUrlError = __( 'Enter a valid URL (must start with http or https).', 'onelogs' @@ -67,9 +92,10 @@ const SiteModal = ( { ? __( 'Site Name is required.', 'onelogs' ) : '', url: siteUrlError, - api_key: ! formData.api_key.trim() - ? __( 'API Key is required.', 'onelogs' ) - : '', + api_key: + needsApiKey && ! typedApiKey + ? __( 'API Key is required.', 'onelogs' ) + : '', message: '', }; @@ -89,65 +115,44 @@ const SiteModal = ( { return; } + // Different spellings of the same URL, like `HTTPS://Brand.test` and `https://brand.test/`, are the same site. + const formUrl = normalizeUrl( formData.url ); + const isAlreadyExists = sites.some( + ( site ) => + normalizeUrl( site.url ) === formUrl && + // Allow keeping the original url in editing mode. + ! ( + editing && + normalizeUrl( originalData?.url ?? '' ) === formUrl + ) + ); + + if ( isAlreadyExists ) { + setErrors( { + ...newErrors, + message: __( 'Brand Site already exists.', 'onelogs' ), + } ); + setShowNotice( true ); + return; + } + // Start processing setIsProcessing( true ); setShowNotice( false ); try { - // Perform health-check - const healthCheck = await fetch( - `${ formData.url }/wp-json/onelogs/v1/health-check`, - { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - 'X-OneLogs-Token': formData.api_key, - }, - } - ); - - const healthCheckData = await healthCheck.json(); - if ( ! healthCheckData.success ) { - setErrors( { - ...newErrors, - message: __( - 'Health check failed. Please ensure the site is accessible and the api key is correct.', - 'onelogs' - ), - } ); - setShowNotice( true ); - setIsProcessing( false ); - return; - } + const submitResponse = await onSubmit(); - setShowNotice( false ); - const submitResponse: Response & { - data?: { status?: number }; - message?: string; - } = await onSubmit(); - - if ( ! submitResponse?.ok ) { - const errorData = await submitResponse?.json(); + if ( submitResponse !== true ) { setErrors( { ...newErrors, message: - errorData.message || - __( - 'An error occurred while saving the site. Please try again.', - 'onelogs' - ), - } ); - setShowNotice( true ); - } - if ( submitResponse?.data?.status === 400 ) { - setErrors( { - ...newErrors, - message: - submitResponse?.message || - __( - 'An error occurred while saving the site. Please try again.', - 'onelogs' - ), + typeof submitResponse === 'string' && submitResponse + ? submitResponse + : __( + 'An error occurred while saving the site. Please try again.', + 'onelogs' + ), } ); setShowNotice( true ); } @@ -160,26 +165,11 @@ const SiteModal = ( { ), } ); setShowNotice( true ); - setIsProcessing( false ); - return; } finally { setIsProcessing( false ); } }; - // Check if form data has changed from original data (only for editing mode) - const hasChanges = useMemo( () => { - if ( ! editing ) { - return true; - } // Always allow submission for new sites - - return ( - formData.name !== originalData?.name || - formData.url !== originalData?.url || - formData.api_key !== originalData?.api_key - ); - }, [ editing, formData, originalData ] ); - // Button should be disabled if: // 1. Currently processing, OR // 2. Required fields are empty, OR @@ -188,7 +178,7 @@ const SiteModal = ( { isProcessing || ! formData.name || ! formData.url || - ! formData.api_key || + ( needsApiKey && ! typedApiKey ) || ( editing && ! hasChanges ); return ( @@ -241,17 +231,27 @@ const SiteModal = ( { __next40pxDefaultSize __nextHasNoMarginBottom /> - setFormData( { ...formData, api_key: value } ) } - help={ __( - 'This is the API key that will be used to authenticate the site for OneLogs.', - 'onelogs' - ) } + help={ + needsApiKey + ? __( + 'This is the API key that will be used to authenticate the site for OneLogs.', + 'onelogs' + ) + : __( + 'Leave blank to keep the current key.', + 'onelogs' + ) + } __nextHasNoMarginBottom /> diff --git a/assets/src/components/SiteSettings.tsx b/assets/src/components/SiteSettings.tsx index 59796f5..4f4f357 100644 --- a/assets/src/components/SiteSettings.tsx +++ b/assets/src/components/SiteSettings.tsx @@ -1,4 +1,11 @@ +/** + * External dependencies + */ import { useEffect, useState, useCallback } from 'react'; + +/** + * WordPress dependencies + */ import { TextareaControl, Button, @@ -11,68 +18,28 @@ import { Modal, } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; +import apiFetch from '@wordpress/api-fetch'; /** * Internal dependencies */ -import { API_NAMESPACE, NONCE, API_KEY } from '../js/constants'; - -type NoticeState = { - type: 'success' | 'error' | 'warning' | 'info'; - message: string; -} | null; +import type { NoticeType } from '@/admin/settings/page'; +import { API_KEY, REST_NAMESPACE } from '@/js/constants'; const SiteSettings = () => { const [ apiKey, setApiKey ] = useState( API_KEY ); - const [ isLoading, setIsLoading ] = useState( false ); - const [ notice, setNotice ] = useState< NoticeState >( null ); + const [ isLoading, setIsLoading ] = useState( true ); + const [ notice, setNotice ] = useState< NoticeType | null >( null ); const [ governingSite, setGoverningSite ] = useState( '' ); const [ showDisconnectionModal, setShowDisconnectionModal ] = useState( false ); - const fetchApiKey = useCallback( async () => { - try { - setIsLoading( true ); - const response = await fetch( API_NAMESPACE + '/secret-key', { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - 'X-WP-Nonce': NONCE, - 'X-OneLogs-Token': API_KEY, - }, - } ); - if ( ! response.ok ) { - throw new Error( 'Network response was not ok' ); - } - const data = await response.json(); - setApiKey( data?.secret_key || '' ); - } catch { - setNotice( { - type: 'error', - message: __( - 'Failed to fetch API key. Please try again later.', - 'onelogs' - ), - } ); - } finally { - setIsLoading( false ); - } - }, [] ); - - // regenerate api key using REST endpoint. const regenerateApiKey = useCallback( async () => { try { - const response = await fetch( API_NAMESPACE + '/secret-key', { + const data = await apiFetch< { secret_key?: string } >( { + path: `/${ REST_NAMESPACE }/secret-key`, method: 'POST', - headers: { - 'X-WP-Nonce': NONCE, - 'X-OneLogs-Token': API_KEY, - }, } ); - if ( ! response.ok ) { - throw new Error( 'Network response was not ok' ); - } - const data = await response.json(); if ( data?.secret_key ) { setApiKey( data.secret_key ); setNotice( { @@ -103,24 +70,11 @@ const SiteSettings = () => { }, [] ); const fetchCurrentGoverningSite = useCallback( async () => { - setIsLoading( true ); try { - const response = await fetch( - `${ API_NAMESPACE }/governing-site?${ new Date().getTime() }`, - { - method: 'GET', - headers: { - 'Content-Type': 'application/json', - 'X-WP-Nonce': NONCE, - 'X-OneLogs-Token': apiKey, - }, - } - ); - if ( ! response.ok ) { - throw new Error( 'Network response was not ok' ); - } - const data = await response.json(); - setGoverningSite( data?.governing_site_url || '' ); + const data = await apiFetch< { + onelogs_parent_site_url?: string; + } >( { path: '/wp/v2/settings' } ); + setGoverningSite( data?.onelogs_parent_site_url || '' ); } catch { setNotice( { type: 'error', @@ -129,25 +83,26 @@ const SiteSettings = () => { 'onelogs' ), } ); - } finally { - setIsLoading( false ); } - }, [ apiKey ] ); + }, [] ); const deleteGoverningSiteConnection = useCallback( async () => { try { - const response = await fetch( `${ API_NAMESPACE }/governing-site`, { + const data = await apiFetch< { + governing_site_notified: boolean; + message: string; + } >( { + path: `/${ REST_NAMESPACE }/governing-site`, method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - 'X-WP-Nonce': NONCE, - 'X-OneLogs-Token': apiKey, - }, } ); - if ( ! response.ok ) { - throw new Error( 'Network response was not ok' ); - } setGoverningSite( '' ); + + // Disconnected locally, but the governing site may still list this site. + if ( data?.governing_site_notified === false ) { + setNotice( { type: 'warning', message: data.message } ); + return; + } + setNotice( { type: 'success', message: __( @@ -166,16 +121,16 @@ const SiteSettings = () => { } finally { setShowDisconnectionModal( false ); } - }, [ apiKey ] ); + }, [] ); const handleDisconnectGoverningSite = useCallback( async () => { setShowDisconnectionModal( true ); }, [] ); + // Load once on mount. useEffect( () => { - fetchApiKey(); - fetchCurrentGoverningSite(); - }, [ fetchApiKey, fetchCurrentGoverningSite ] ); + fetchCurrentGoverningSite().finally( () => setIsLoading( false ) ); + }, [ fetchCurrentGoverningSite ] ); if ( isLoading ) { return ; @@ -204,8 +159,10 @@ const SiteSettings = () => { + + +
+ ), +} ) ); + +jest.mock( '@/components/SiteModal', () => ( { + __esModule: true, + default: ( { + onSubmit, + onClose, + }: { + onSubmit: () => Promise< boolean | string >; + onClose: () => void; + } ) => ( +
+ + +
+ ), +} ) ); + +jest.mock( '@/components/SiteSettings', () => ( { + __esModule: true, + default: () =>
Brand Site Settings
, +} ) ); + +import SettingsPage from '@/admin/settings/page'; + +const mockedApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; + +const baseSettings = window.OneLogsSettings as OneLogsSettings; + +const setSettings = ( + siteType: SiteType, + sharedSites: OneLogsSharedSite[] = [] +) => { + window.OneLogsSettings = { ...baseSettings, siteType, sharedSites }; +}; + +const brandSite: OneLogsSharedSite = { + id: 'one', + name: 'Brand Site', + url: 'https://brand.example.com/', +}; + +const remainingSite: OneLogsSharedSite = { + id: 'two', + name: 'Remaining Site', + url: 'https://remaining.example.com/', +}; + +const openAndSubmitModal = async () => { + fireEvent.click( + await screen.findByRole( 'button', { name: 'Open Modal' } ) + ); + // The save resolves in a microtask, so let its state updates finish inside act(). + await act( async () => { + fireEvent.click( + screen.getByRole( 'button', { name: 'Submit Modal' } ) + ); + } ); +}; + +describe( 'SettingsPage', () => { + // A test that fails while on fake timers would leave them on for the next ones. + afterEach( () => { + jest.useRealTimers(); + window.OneLogsSettings = baseSettings; + } ); + + beforeEach( () => { + mockedApiFetch.mockReset(); + setSettings( 'governing-site' ); + mockSubmitResults.length = 0; + } ); + + it( 'shows neither settings view until the site type is chosen in the setup modal', () => { + setSettings( '' ); + + render( ); + + expect( screen.queryByTestId( 'site-table' ) ).not.toBeInTheDocument(); + expect( + screen.queryByTestId( 'site-settings' ) + ).not.toBeInTheDocument(); + } ); + + it( 'shows the brand site settings on brand sites', () => { + setSettings( 'brand-site' ); + + render( ); + + expect( screen.getByTestId( 'site-settings' ) ).toBeInTheDocument(); + expect( screen.queryByTestId( 'site-table' ) ).not.toBeInTheDocument(); + } ); + + it( 'starts from the localized brand sites without fetching them', () => { + setSettings( 'governing-site', [ brandSite ] ); + + render( ); + + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( '1' ); + expect( mockedApiFetch ).not.toHaveBeenCalled(); + expect( global.fetch ).not.toHaveBeenCalled(); + } ); + + it( 'saves site changes through apiFetch and shows success feedback', async () => { + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockResolvedValueOnce( { + shared_sites: [ brandSite, remainingSite ], + } ); + + render( ); + await openAndSubmitModal(); + + await waitFor( () => { + expect( mockSubmitResults ).toEqual( [ true ] ); + } ); + expect( mockedApiFetch ).toHaveBeenCalledWith( { + path: '/onelogs/v1/shared-sites', + method: 'POST', + data: { + sites_data: [ brandSite, { name: '', url: '', api_key: '' } ], + }, + } ); + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( '2' ); + expect( screen.queryByTestId( 'site-modal' ) ).not.toBeInTheDocument(); + expect( + screen.getAllByText( 'Brand Site saved successfully.' ).length + ).toBeGreaterThanOrEqual( 1 ); + expect( global.fetch ).not.toHaveBeenCalled(); + } ); + + it( 'reloads after the first brand site is added, so the Logs menu appears (QA TC-028)', async () => { + mockedApiFetch.mockResolvedValueOnce( { + shared_sites: [ brandSite ], + } ); + + render( ); + await openAndSubmitModal(); + + await waitFor( () => { + expect( mockSubmitResults ).toEqual( [ true ] ); + } ); + + // jsdom can't reload, so the reload shows up as its "not implemented" error. + expect( console ).toHaveErrored(); + } ); + + it( 'keeps the modal open and returns the server message when saving fails', async () => { + mockedApiFetch.mockRejectedValueOnce( { + code: 'onelogs_bad_key', + message: 'The brand site rejected this API key.', + } ); + + render( ); + await openAndSubmitModal(); + + await waitFor( () => { + expect( mockSubmitResults ).toEqual( [ + 'The brand site rejected this API key.', + ] ); + } ); + expect( screen.getByTestId( 'site-modal' ) ).toBeInTheDocument(); + } ); + + it( 'returns false when saving fails without a message', async () => { + mockedApiFetch.mockRejectedValueOnce( {} ); + + render( ); + await openAndSubmitModal(); + + await waitFor( () => { + expect( mockSubmitResults ).toEqual( [ false ] ); + } ); + expect( screen.getByTestId( 'site-modal' ) ).toBeInTheDocument(); + } ); + + it( 'keeps the modal open when the response lacks shared sites', async () => { + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockResolvedValueOnce( {} ); + + render( ); + await openAndSubmitModal(); + + await waitFor( () => { + expect( mockSubmitResults ).toEqual( [ false ] ); + } ); + expect( screen.getByTestId( 'site-modal' ) ).toBeInTheDocument(); + } ); + + it( 'submits edit changes correctly', async () => { + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockResolvedValueOnce( { + shared_sites: [ { ...brandSite, name: 'Edited Brand Site' } ], + } ); + + render( ); + fireEvent.click( + await screen.findByRole( 'button', { name: 'Edit Site' } ) + ); + await openAndSubmitModal(); + + await waitFor( () => { + expect( mockedApiFetch ).toHaveBeenLastCalledWith( + expect.objectContaining( { + method: 'POST', + data: { + sites_data: [ + { + name: 'Edited Brand Site', + url: 'https://edited.example.com/', + api_key: 'edited-key', + }, + ], + }, + } ) + ); + } ); + } ); + + it( 'closes the modal via close action', async () => { + render( ); + fireEvent.click( + await screen.findByRole( 'button', { name: 'Open Modal' } ) + ); + expect( screen.getByTestId( 'site-modal' ) ).toBeInTheDocument(); + + fireEvent.click( + screen.getByRole( 'button', { name: 'Close Modal' } ) + ); + + expect( screen.queryByTestId( 'site-modal' ) ).not.toBeInTheDocument(); + } ); + + it( 'removes a brand site through the server, which disconnects it', async () => { + setSettings( 'governing-site', [ brandSite, remainingSite ] ); + mockedApiFetch.mockResolvedValueOnce( { + governing_site_notified: true, + message: 'Brand Site deleted successfully.', + shared_sites: [ remainingSite ], + } ); + + render( ); + + fireEvent.click( + await screen.findByRole( 'button', { name: 'Delete Site' } ) + ); + + await waitFor( () => { + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( + '1' + ); + } ); + expect( mockedApiFetch ).toHaveBeenLastCalledWith( { + path: '/onelogs/v1/shared-sites/one', + method: 'DELETE', + } ); + expect( global.fetch ).not.toHaveBeenCalled(); + expect( + ( await screen.findAllByText( 'Brand Site deleted successfully.' ) ) + .length + ).toBeGreaterThanOrEqual( 1 ); + expect( + screen.queryByText( /was removed, but/, { + selector: '.components-notice__content', + } ) + ).not.toBeInTheDocument(); + } ); + + it( 'drops the site locally when the response has no list', async () => { + setSettings( 'governing-site', [ brandSite, remainingSite ] ); + mockedApiFetch.mockResolvedValueOnce( { + governing_site_notified: true, + } ); + + render( ); + + fireEvent.click( + await screen.findByRole( 'button', { name: 'Delete Site' } ) + ); + + await waitFor( () => { + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( + '1' + ); + } ); + // Without a server message, the default one is shown. + expect( + ( await screen.findAllByText( 'Brand Site deleted successfully.' ) ) + .length + ).toBeGreaterThanOrEqual( 1 ); + } ); + + it( 'reloads after the last brand site is deleted, so the Logs menu disappears (QA TC-046)', async () => { + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockResolvedValueOnce( { + governing_site_notified: true, + message: 'Brand Site deleted successfully.', + shared_sites: [], + } ); + + render( ); + + fireEvent.click( + await screen.findByRole( 'button', { name: 'Delete Site' } ) + ); + + await waitFor( () => { + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( + '0' + ); + } ); + + // jsdom can't reload, so the reload shows up as its "not implemented" error. + expect( console ).toHaveErrored(); + } ); + + it( 'warns, and does not reload, when the deleted last brand site could not be notified', async () => { + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockResolvedValueOnce( { + governing_site_notified: false, + message: 'Brand Site was removed, but it could not be notified.', + shared_sites: [], + } ); + + render( ); + + fireEvent.click( + await screen.findByRole( 'button', { name: 'Delete Site' } ) + ); + + const message = 'Brand Site was removed, but it could not be notified.'; + expect( + await screen.findByText( message, { + selector: '.components-notice__content', + } ) + ).toBeInTheDocument(); + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( '0' ); + // No reload, so the "not implemented" navigation error never happened. + expect( console ).not.toHaveErrored(); + + // The admin can dismiss it once they have acted on it. + fireEvent.click( screen.getByRole( 'button', { name: 'Close' } ) ); + expect( + screen.queryByText( message, { + selector: '.components-notice__content', + } ) + ).not.toBeInTheDocument(); + } ); + + it( 'shows the server error and leaves the brand site alone when deleting fails', async () => { + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockRejectedValueOnce( { + code: 'onelogs_site_not_found', + message: 'The brand site was not found.', + } ); + + render( ); + + fireEvent.click( + await screen.findByRole( 'button', { name: 'Delete Site' } ) + ); + + expect( + ( await screen.findAllByText( 'The brand site was not found.' ) ) + .length + ).toBeGreaterThanOrEqual( 1 ); + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( '1' ); + } ); + + it( 'falls back to a generic message when deleting fails without one', async () => { + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockRejectedValueOnce( {} ); + + render( ); + + fireEvent.click( + await screen.findByRole( 'button', { name: 'Delete Site' } ) + ); + + expect( + ( + await screen.findAllByText( + 'Failed to delete Brand site. Please try again.' + ) + ).length + ).toBeGreaterThanOrEqual( 1 ); + expect( screen.getByTestId( 'site-count' ) ).toHaveTextContent( '1' ); + } ); + + it( 'gives each notice its own snackbar timer', async () => { + jest.useFakeTimers(); + setSettings( 'governing-site', [ brandSite ] ); + mockedApiFetch.mockRejectedValueOnce( {} ).mockResolvedValueOnce( { + shared_sites: [ brandSite, remainingSite ], + } ); + + render( ); + fireEvent.click( + screen.getByRole( 'button', { name: 'Delete Site' } ) + ); + await screen.findAllByText( + 'Failed to delete Brand site. Please try again.' + ); + + // The second notice arrives just before the first one's timer ends. + act( () => { + jest.advanceTimersByTime( 9000 ); + } ); + fireEvent.click( screen.getByRole( 'button', { name: 'Open Modal' } ) ); + fireEvent.click( + screen.getByRole( 'button', { name: 'Submit Modal' } ) + ); + await screen.findAllByText( 'Brand Site saved successfully.' ); + + act( () => { + jest.advanceTimersByTime( 2000 ); + } ); + + expect( + document.querySelector( '.components-snackbar' ) + ).toHaveTextContent( 'Brand Site saved successfully.' ); + } ); +} ); diff --git a/tests/js/SiteModal.test.tsx b/tests/js/SiteModal.test.tsx index 9dad10a..bbfcda9 100644 --- a/tests/js/SiteModal.test.tsx +++ b/tests/js/SiteModal.test.tsx @@ -4,40 +4,38 @@ import { useState } from 'react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +/** + * WordPress dependencies + */ +import apiFetch from '@wordpress/api-fetch'; + +/** + * Internal dependencies + */ import SiteModal from '@/components/SiteModal'; +import { defaultBrandSite, type BrandSite } from '@/admin/settings/page'; -type SiteData = { name: string; url: string; api_key: string }; +const mockedApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; -const baseFormData: SiteData = { +const baseFormData: BrandSite = { + ...defaultBrandSite, name: 'Brand Site', url: 'https://brand.example.com', api_key: 'secret-key', }; -const okResponse = () => - ( { - ok: true, - json: jest.fn().mockResolvedValue( {} ), - } ) as unknown as Response; - -const errorResponse = ( - message = 'An error occurred while saving the site. Please try again.' -) => - ( { - ok: false, - json: jest.fn().mockResolvedValue( { message } ), - } ) as unknown as Response; - function SiteModalHarness( { initialData = baseFormData, editing = false, + sites = [], originalData, - onSubmit = jest.fn().mockResolvedValue( okResponse() ), + onSubmit = jest.fn().mockResolvedValue( true ), }: { - initialData?: SiteData; + initialData?: BrandSite; editing?: boolean; - originalData?: SiteData; - onSubmit?: jest.Mock< Promise< Response >, [] >; + sites?: BrandSite[]; + originalData?: BrandSite; + onSubmit?: jest.Mock< Promise< boolean | string >, [] >; } ) { const [ formData, setFormData ] = useState( initialData ); @@ -48,18 +46,25 @@ function SiteModalHarness( { onSubmit={ onSubmit } onClose={ jest.fn() } editing={ editing } + sites={ sites } originalData={ originalData } /> ); } +const clickAdd = () => + fireEvent.click( screen.getByRole( 'button', { name: 'Add Site' } ) ); + describe( 'SiteModal', () => { it( 'disables submit when editing without changes', () => { + // The key field starts empty when editing. + const stored = { ...baseFormData, api_key: '' }; + render( ); @@ -68,6 +73,18 @@ describe( 'SiteModal', () => { ).toBeDisabled(); } ); + it( 'disables submit for a new site until an API key is typed', () => { + render( + + ); + + expect( + screen.getByRole( 'button', { name: 'Add Site' } ) + ).toBeDisabled(); + } ); + it( 'shows validation feedback for invalid input', async () => { render( { /> ); - fireEvent.click( screen.getByRole( 'button', { name: 'Add Site' } ) ); + clickAdd(); // WordPress renders notices in both accessibility region and visible content expect( @@ -89,34 +106,85 @@ describe( 'SiteModal', () => { ).toHaveLength( 2 ); } ); - it( 'shows a health check error when the remote site rejects the credentials', async () => { - const onSubmit = jest.fn().mockResolvedValue( okResponse() ); - global.fetch = jest.fn().mockResolvedValue( { - json: jest.fn().mockResolvedValue( { success: false } ), - } ) as typeof fetch; + it( 'requires a site name even when it is only whitespace', async () => { + const onSubmit = jest.fn().mockResolvedValue( true ); - render( ); + render( + + ); - fireEvent.click( screen.getByRole( 'button', { name: 'Add Site' } ) ); + clickAdd(); - // WordPress renders notices in both accessibility region and visible content expect( - await screen.findAllByText( - 'Health check failed. Please ensure the site is accessible and the api key is correct.' - ) + await screen.findAllByText( 'Site Name is required.' ) ).toHaveLength( 2 ); expect( onSubmit ).not.toHaveBeenCalled(); } ); + it.each( [ 'ftp://example.com', 'javascript:alert(1)', 'abc' ] )( + 'rejects %s with the http/https message (QA TC-032, TC-033)', + async ( url ) => { + const onSubmit = jest.fn().mockResolvedValue( true ); + + render( + + ); + + clickAdd(); + + expect( + await screen.findAllByText( + 'Enter a valid URL (must start with http or https).' + ) + ).toHaveLength( 2 ); + expect( onSubmit ).not.toHaveBeenCalled(); + } + ); + + it.each( [ + 'https://brand.example.com/', + 'https://brand.example.com', + 'HTTPS://Brand.Example.com/', + ] )( + 'treats %s as a duplicate of an existing site (QA TC-036, TC-037)', + async ( url ) => { + const onSubmit = jest.fn().mockResolvedValue( true ); + + render( + + ); + + clickAdd(); + + expect( + await screen.findAllByText( 'Brand Site already exists.' ) + ).toHaveLength( 2 ); + expect( onSubmit ).not.toHaveBeenCalled(); + } + ); + it( 'shows an error when saving the site fails', async () => { - const onSubmit = jest.fn().mockResolvedValue( errorResponse() ); - global.fetch = jest.fn().mockResolvedValue( { - json: jest.fn().mockResolvedValue( { success: true } ), - } ) as typeof fetch; + const onSubmit = jest.fn().mockResolvedValue( false ); render( ); - fireEvent.click( screen.getByRole( 'button', { name: 'Add Site' } ) ); + clickAdd(); // WordPress renders notices in both accessibility region and visible content expect( @@ -127,46 +195,158 @@ describe( 'SiteModal', () => { expect( onSubmit ).toHaveBeenCalled(); } ); - it( 'handles unexpected fetch failures gracefully', async () => { - global.fetch = jest + it( 'shows the server message when saving fails', async () => { + const onSubmit = jest .fn() - .mockRejectedValue( new Error( 'network failed' ) ) as typeof fetch; + .mockResolvedValue( + "The brand site rejected this API key. Copy the key from the brand site's OneLogs settings and try again." + ); - render( ); + render( ); - fireEvent.click( screen.getByRole( 'button', { name: 'Add Site' } ) ); + clickAdd(); + + expect( + await screen.findAllByText( + "The brand site rejected this API key. Copy the key from the brand site's OneLogs settings and try again." + ) + ).toHaveLength( 2 ); + } ); + + it( 'handles a submit handler that throws', async () => { + const onSubmit = jest.fn().mockRejectedValue( new Error( 'boom' ) ); + + render( ); + + clickAdd(); - // WordPress renders notices in both accessibility region and visible content expect( await screen.findAllByText( 'An unexpected error occurred. Please try again.' ) ).toHaveLength( 2 ); + expect( + screen.getByRole( 'button', { name: 'Add Site' } ) + ).not.toBeDisabled(); } ); - it( 'submits after a successful health check', async () => { - const onSubmit = jest.fn().mockResolvedValue( okResponse() ); - global.fetch = jest.fn().mockResolvedValue( { - json: jest.fn().mockResolvedValue( { success: true } ), - } ) as typeof fetch; + it( 'submits without calling the brand site, which the server checks on save', async () => { + const onSubmit = jest.fn().mockResolvedValue( true ); render( ); - fireEvent.click( screen.getByRole( 'button', { name: 'Add Site' } ) ); + clickAdd(); await waitFor( () => { - expect( global.fetch ).toHaveBeenCalledWith( - 'https://brand.example.com/wp-json/onelogs/v1/health-check', - expect.objectContaining( { - method: 'GET', - headers: expect.objectContaining( { - 'X-OneLogs-Token': 'secret-key', - } ), - } ) - ); + expect( onSubmit ).toHaveBeenCalled(); } ); - expect( onSubmit ).toHaveBeenCalled(); + expect( mockedApiFetch ).not.toHaveBeenCalled(); + expect( global.fetch ).not.toHaveBeenCalled(); expect( screen.queryByRole( 'alert' ) ).not.toBeInTheDocument(); } ); + + it( 'saves an edit without a new key', async () => { + const onSubmit = jest.fn().mockResolvedValue( true ); + const stored = { ...baseFormData, id: 'one', api_key: '' }; + + render( + + ); + + expect( + screen.getByText( 'Leave blank to keep the current key.' ) + ).toBeInTheDocument(); + + fireEvent.click( + screen.getByRole( 'button', { name: 'Update Site' } ) + ); + + await waitFor( () => { + expect( onSubmit ).toHaveBeenCalled(); + } ); + } ); + + it( 'allows keeping the original url when editing', async () => { + const onSubmit = jest.fn().mockResolvedValue( true ); + const stored = { + ...baseFormData, + id: 'one', + url: 'https://brand.example.com/', + api_key: '', + }; + + render( + + ); + + fireEvent.click( + screen.getByRole( 'button', { name: 'Update Site' } ) + ); + + await waitFor( () => { + expect( onSubmit ).toHaveBeenCalled(); + } ); + expect( + screen.queryByText( 'Brand Site already exists.' ) + ).not.toBeInTheDocument(); + } ); + + it( 'needs the key again when an edit changes the URL', () => { + const stored = { ...baseFormData, id: 'one', api_key: '' }; + + render( + + ); + + expect( + screen.getByRole( 'button', { name: 'Update Site' } ) + ).toBeDisabled(); + expect( screen.getByText( 'API Key*' ) ).toBeInTheDocument(); + } ); + + it( 'does not need the key again when an edit only changes the URL spelling', () => { + const stored = { + ...baseFormData, + id: 'one', + url: 'https://brand.example.com/', + api_key: '', + }; + + render( + + ); + + expect( + screen.getByRole( 'button', { name: 'Update Site' } ) + ).not.toBeDisabled(); + } ); } ); diff --git a/tests/js/SiteSettings.test.tsx b/tests/js/SiteSettings.test.tsx index 0b02fa9..b2c9c5b 100644 --- a/tests/js/SiteSettings.test.tsx +++ b/tests/js/SiteSettings.test.tsx @@ -3,119 +3,95 @@ */ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +/** + * WordPress dependencies + */ +import apiFetch from '@wordpress/api-fetch'; + +/** + * Internal dependencies + */ import SiteSettings from '@/components/SiteSettings'; -const okJson = ( data: unknown ) => - ( { - ok: true, - json: jest.fn().mockResolvedValue( data ), - } ) as unknown as Response; +const mockedApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; -const siteSettingsFetch = ( handlers: { - secretKey?: string; +const mockRequests = ( handlers: { governingSiteUrl?: string; regeneratedKey?: string; - deleteOk?: boolean; - failSecretKey?: boolean; + disconnectResponse?: Record< string, unknown >; failGoverningSite?: boolean; failRegenerate?: boolean; failDisconnect?: boolean; } ) => - jest.fn( async ( input: RequestInfo | URL, init?: RequestInit ) => { - const url = String( input ); - const method = init?.method ?? 'GET'; - - if ( url.includes( '/secret-key' ) && method === 'GET' ) { - if ( handlers.failSecretKey ) { - return { ok: false } as Response; - } - - return okJson( { secret_key: handlers.secretKey ?? '' } ); - } - - if ( url.includes( '/secret-key' ) && method === 'POST' ) { + mockedApiFetch.mockImplementation( ( async ( { + path, + method = 'GET', + }: { + path?: string; + method?: string; + } ) => { + if ( path === '/onelogs/v1/secret-key' && method === 'POST' ) { if ( handlers.failRegenerate ) { - return { ok: false } as Response; + throw new Error( 'Request failed' ); } - return okJson( { secret_key: handlers.regeneratedKey ?? '' } ); + return { secret_key: handlers.regeneratedKey ?? '' }; } - if ( url.includes( '/governing-site?' ) && method === 'GET' ) { + if ( path === '/wp/v2/settings' && method === 'GET' ) { if ( handlers.failGoverningSite ) { - return { ok: false } as Response; + throw new Error( 'Request failed' ); } - return okJson( { - governing_site_url: handlers.governingSiteUrl ?? '', - } ); + return { + onelogs_parent_site_url: handlers.governingSiteUrl ?? '', + }; } - if ( url.endsWith( '/governing-site' ) && method === 'DELETE' ) { + if ( path === '/onelogs/v1/governing-site' && method === 'DELETE' ) { if ( handlers.failDisconnect ) { - return { ok: false } as Response; + throw new Error( 'Request failed' ); } - return { - ok: handlers.deleteOk ?? true, - json: jest.fn().mockResolvedValue( {} ), - } as unknown as Response; + return ( + handlers.disconnectResponse ?? { governing_site_notified: true } + ); } - return { ok: false } as Response; - } ); + throw new Error( `Unexpected request: ${ method } ${ path }` ); + } ) as unknown as typeof apiFetch ); describe( 'SiteSettings', () => { it( 'loads the api key and governing site details', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', } ); render( ); expect( - await screen.findByDisplayValue( 'brand-secret' ) + await screen.findByDisplayValue( 'api-key' ) ).toBeInTheDocument(); expect( screen.getByDisplayValue( 'https://governing.example.com/' ) ).toBeInTheDocument(); } ); - it( 'shows an error when loading the api key fails', async () => { - global.fetch = siteSettingsFetch( { - failSecretKey: true, - governingSiteUrl: '', - } ); - - render( ); - - expect( - await screen.findByText( - 'Failed to fetch API key. Please try again later.', - { - selector: '.components-notice__content', - } - ) - ).toBeInTheDocument(); - } ); - it( 'copies the api key to the clipboard and shows success feedback', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', } ); render( ); - await screen.findByDisplayValue( 'brand-secret' ); + await screen.findByDisplayValue( 'api-key' ); fireEvent.click( screen.getByRole( 'button', { name: 'Copy API Key' } ) ); await waitFor( () => { expect( navigator.clipboard.writeText ).toHaveBeenCalledWith( - 'brand-secret' + 'api-key' ); } ); @@ -127,33 +103,30 @@ describe( 'SiteSettings', () => { } ); it( 'regenerates the api key and reports success', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', regeneratedKey: 'new-secret', } ); render( ); - await screen.findByDisplayValue( 'brand-secret' ); + await screen.findByDisplayValue( 'api-key' ); fireEvent.click( screen.getByRole( 'button', { name: 'Regenerate API Key' } ) ); - // Wait for the API call to complete - that's the important behavior - await waitFor( () => { - expect( global.fetch ).toHaveBeenCalledWith( - expect.stringContaining( '/secret-key' ), - expect.objectContaining( { method: 'POST' } ) - ); - } ); + expect( await screen.findByDisplayValue( 'new-secret' ) ).toBeVisible(); + expect( + screen.getByText( + 'API key regenerated successfully. Please update your old key with this newly generated key to make sure plugin works properly.', + { selector: '.components-notice__content' } + ) + ).toBeInTheDocument(); } ); it( 'disconnects from the governing site after confirmation', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', - deleteOk: true, } ); render( ); @@ -175,9 +148,39 @@ describe( 'SiteSettings', () => { expect( screen.getByDisplayValue( '' ) ).toBeInTheDocument(); } ); + it( 'warns when the governing site could not be notified of the disconnection', async () => { + mockRequests( { + governingSiteUrl: 'https://governing.example.com/', + disconnectResponse: { + governing_site_notified: false, + message: 'The governing site could not be notified.', + }, + } ); + + render( ); + + await screen.findByDisplayValue( 'https://governing.example.com/' ); + fireEvent.click( + screen.getByRole( 'button', { name: 'Disconnect Governing Site' } ) + ); + fireEvent.click( screen.getByRole( 'button', { name: 'Disconnect' } ) ); + + expect( + await screen.findByText( + 'The governing site could not be notified.', + { + selector: '.components-notice__content', + } + ) + ).toBeInTheDocument(); + expect( + screen.queryByText( 'Governing site disconnected successfully.' ) + ).not.toBeInTheDocument(); + expect( screen.getByDisplayValue( '' ) ).toBeInTheDocument(); + } ); + it( 'shows an error notice when copying the api key fails', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', } ); navigator.clipboard.writeText = jest @@ -186,7 +189,7 @@ describe( 'SiteSettings', () => { render( ); - await screen.findByDisplayValue( 'brand-secret' ); + await screen.findByDisplayValue( 'api-key' ); fireEvent.click( screen.getByRole( 'button', { name: 'Copy API Key' } ) ); @@ -199,9 +202,40 @@ describe( 'SiteSettings', () => { ).toBeInTheDocument(); } ); + it( 'shows an error notice when the clipboard api is unavailable', async () => { + mockRequests( { + governingSiteUrl: 'https://governing.example.com/', + } ); + const clipboard = navigator.clipboard; + Object.defineProperty( navigator, 'clipboard', { + value: undefined, + configurable: true, + } ); + + try { + render( ); + + await screen.findByDisplayValue( 'api-key' ); + fireEvent.click( + screen.getByRole( 'button', { name: 'Copy API Key' } ) + ); + + expect( + await screen.findByText( + 'Failed to copy api key. Please try again.', + { selector: '.components-notice__content' } + ) + ).toBeInTheDocument(); + } finally { + Object.defineProperty( navigator, 'clipboard', { + value: clipboard, + configurable: true, + } ); + } + } ); + it( 'shows an error notice when disconnecting the governing site fails', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', failDisconnect: true, } ); @@ -223,8 +257,7 @@ describe( 'SiteSettings', () => { } ); it( 'shows an error notice when loading the governing site fails', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { failGoverningSite: true, } ); @@ -239,15 +272,14 @@ describe( 'SiteSettings', () => { } ); it( 'shows an error notice when regeneration returns no secret key', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', regeneratedKey: '', } ); render( ); - await screen.findByDisplayValue( 'brand-secret' ); + await screen.findByDisplayValue( 'api-key' ); fireEvent.click( screen.getByRole( 'button', { name: 'Regenerate API Key' } ) ); @@ -261,15 +293,14 @@ describe( 'SiteSettings', () => { } ); it( 'shows an error notice when regenerating the api key fails', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', failRegenerate: true, } ); render( ); - await screen.findByDisplayValue( 'brand-secret' ); + await screen.findByDisplayValue( 'api-key' ); fireEvent.click( screen.getByRole( 'button', { name: 'Regenerate API Key' } ) ); @@ -283,8 +314,7 @@ describe( 'SiteSettings', () => { } ); it( 'closes the disconnect modal when cancel is clicked', async () => { - global.fetch = siteSettingsFetch( { - secretKey: 'brand-secret', + mockRequests( { governingSiteUrl: 'https://governing.example.com/', } ); @@ -311,4 +341,37 @@ describe( 'SiteSettings', () => { ).not.toBeInTheDocument(); } ); } ); + + it( 'loads once on mount, and does not reload after regenerating', async () => { + mockRequests( { + governingSiteUrl: 'https://governing.example.com/', + regeneratedKey: 'new-secret', + } ); + + render( ); + + await screen.findByDisplayValue( 'api-key' ); + expect( mockedApiFetch ).toHaveBeenCalledTimes( 1 ); + + fireEvent.click( + screen.getByRole( 'button', { name: 'Regenerate API Key' } ) + ); + + expect( await screen.findByDisplayValue( 'new-secret' ) ).toBeVisible(); + // Nothing but the regeneration request was made after the initial load. + expect( mockedApiFetch ).toHaveBeenCalledTimes( 2 ); + } ); + + it( 'keeps the key field selectable for a manual copy', async () => { + mockRequests( { + governingSiteUrl: 'https://governing.example.com/', + } ); + + render( ); + + const field = await screen.findByDisplayValue( 'api-key' ); + expect( field ).toBe( screen.getByLabelText( 'API Key' ) ); + expect( field ).not.toBeDisabled(); + expect( field ).toHaveAttribute( 'readonly' ); + } ); } ); diff --git a/tests/js/SiteTable.test.tsx b/tests/js/SiteTable.test.tsx index 91db4b2..f0ce8b0 100644 --- a/tests/js/SiteTable.test.tsx +++ b/tests/js/SiteTable.test.tsx @@ -3,27 +3,35 @@ */ import { fireEvent, render, screen, within } from '@testing-library/react'; +/** + * Internal dependencies + */ import SiteTable from '@/components/SiteTable'; +import type { BrandSite } from '@/admin/settings/page'; -const sites = [ +const sites: BrandSite[] = [ { + id: 'one', name: 'Brand One', url: 'https://brand-one.example.com/', - api_key: '1234567890abcdef', }, ]; +const renderTable = ( props: Partial< Parameters< typeof SiteTable >[ 0 ] > ) => + render( + + ); + describe( 'SiteTable', () => { it( 'renders an empty state when there are no brand sites', () => { - render( - - ); + renderTable( {} ); expect( screen.getByText( 'No Brand Sites found.' ) @@ -33,15 +41,7 @@ describe( 'SiteTable', () => { it( 'opens the add modal when the add button is clicked', () => { const setShowModal = jest.fn(); - render( - - ); + renderTable( { setShowModal } ); fireEvent.click( screen.getByRole( 'button', { name: 'Add Brand Site' } ) @@ -50,24 +50,30 @@ describe( 'SiteTable', () => { expect( setShowModal ).toHaveBeenCalledWith( true ); } ); - it( 'passes the selected site to edit handlers', () => { + it( 'masks the api key, which never reaches the browser (QA TC-047)', () => { + renderTable( { + // Even if a key were passed, it isn't shown. + sites: [ { ...sites[ 0 ]!, api_key: '1234567890abcdef' } ], + } ); + + expect( screen.getByText( '••••••••' ) ).toBeInTheDocument(); + expect( screen.queryByText( /1234567890/ ) ).not.toBeInTheDocument(); + } ); + + it( 'passes the selected site to edit handlers with an empty key field', () => { const onEdit = jest.fn(); const setFormData = jest.fn(); const setShowModal = jest.fn(); - render( - - ); + renderTable( { sites, onEdit, setFormData, setShowModal } ); fireEvent.click( screen.getByRole( 'button', { name: 'Edit' } ) ); - expect( setFormData ).toHaveBeenCalledWith( sites[ 0 ] ); + // The empty key keeps the stored one when saved. + expect( setFormData ).toHaveBeenCalledWith( { + ...sites[ 0 ], + api_key: '', + } ); expect( onEdit ).toHaveBeenCalledWith( 0 ); expect( setShowModal ).toHaveBeenCalledWith( true ); } ); @@ -75,15 +81,7 @@ describe( 'SiteTable', () => { it( 'confirms deletion before calling onDelete', () => { const onDelete = jest.fn(); - render( - - ); + renderTable( { sites, onDelete } ); fireEvent.click( screen.getByRole( 'button', { name: 'Delete' } ) ); @@ -106,15 +104,7 @@ describe( 'SiteTable', () => { it( 'lets the user cancel deletion', () => { const onDelete = jest.fn(); - render( - - ); + renderTable( { sites, onDelete } ); fireEvent.click( screen.getByRole( 'button', { name: 'Delete' } ) ); fireEvent.click( screen.getByRole( 'button', { name: 'Cancel' } ) ); diff --git a/tests/js/apiService.test.ts b/tests/js/apiService.test.ts new file mode 100644 index 0000000..8da76ac --- /dev/null +++ b/tests/js/apiService.test.ts @@ -0,0 +1,214 @@ +/** + * WordPress dependencies + */ +import apiFetch from '@wordpress/api-fetch'; + +/** + * Internal dependencies + */ +import { + fetchActions, + fetchContexts, + fetchLogs, + fetchSharedSites, + fetchUsers, +} from '@/admin/logs/apiService'; +import type { FilterOptions } from '@/admin/logs/types'; + +const mockedApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; + +const BRAND_URL = 'https://brand-one.example.com/'; + +/** + * Gets the path and query of the nth apiFetch call. + * + * @param call The call index. + */ +const requestOf = ( call = 0 ) => { + const options = mockedApiFetch.mock.calls[ call ]?.[ 0 ] as { + path: string; + method: string; + }; + const url = new URL( options.path, 'https://governing.example.com' ); + + return { + method: options.method, + pathname: url.pathname, + query: Object.fromEntries( url.searchParams.entries() ), + }; +}; + +const baseFilters: FilterOptions = { page: 1, per_page: 20 }; + +describe( 'logs apiService', () => { + beforeEach( () => { + mockedApiFetch.mockReset(); + } ); + + it( "fetches the governing site's own logs without a site_url", async () => { + mockedApiFetch.mockResolvedValueOnce( { + data: [ { ID: 1 } ], + meta: { total: 1, total_pages: 1, errors: [] }, + } ); + + const result = await fetchLogs( { + ...baseFilters, + site_url: 'governing-site', + date_from: '2026-11-01', + site_id: 1, + } ); + + const { method, pathname, query } = requestOf(); + expect( method ).toBe( 'GET' ); + expect( pathname ).toBe( '/onelogs/v1/logs' ); + expect( query ).toEqual( + expect.objectContaining( { + page: '1', + per_page: '20', + current_site_logs: 'true', + include_shared_sites: 'false', + date_from: '2026-11-01 00:00:00', + site_id: '1', + } ) + ); + expect( query ).not.toHaveProperty( 'site_url' ); + expect( result ).toEqual( { + logs: [ { ID: 1 } ], + total: 1, + pages: 1, + errors: null, + } ); + } ); + + it( "asks the governing site for a brand site's logs by its URL", async () => { + mockedApiFetch.mockResolvedValueOnce( { + data: [ { ID: 7, is_remote: true } ], + meta: { total: 41, total_pages: 3, errors: [] }, + } ); + + const result = await fetchLogs( { + ...baseFilters, + site_url: BRAND_URL, + date_to: '2026-11-10', + site_id: 1, + } ); + + const { pathname, query } = requestOf(); + expect( pathname ).toBe( '/onelogs/v1/logs' ); + expect( query ).toEqual( + expect.objectContaining( { + site_url: BRAND_URL, + current_site_logs: 'false', + include_shared_sites: 'true', + date_to: '2026-11-10 23:59:59', + } ) + ); + // The governing site's own site id means nothing to the brand site. + expect( query ).not.toHaveProperty( 'site_id' ); + expect( result ).toEqual( { + logs: [ { ID: 7, is_remote: true } ], + total: 41, + pages: 3, + errors: [], + } ); + } ); + + it.each( [ + [ 'null data', { data: null, meta: { total: 0, total_pages: 0 } } ], + [ 'missing data and meta', {} ], + [ 'no body', null ], + ] )( + 'returns no logs instead of crashing for %s (QA TC-054)', + async ( _label, response ) => { + mockedApiFetch.mockResolvedValueOnce( response ); + + const result = await fetchLogs( { + ...baseFilters, + site_url: BRAND_URL, + } ); + + expect( result.logs ).toEqual( [] ); + expect( result.total ).toBe( 0 ); + expect( result.pages ).toBe( 1 ); + } + ); + + it( 'rejects with the REST error, so the dashboard can show its message', async () => { + const error = { + code: 'onelogs_brand_site_unreachable', + message: 'Could not reach Brand One.', + }; + mockedApiFetch.mockRejectedValueOnce( error ); + + await expect( + fetchLogs( { ...baseFilters, site_url: BRAND_URL } ) + ).rejects.toBe( error ); + } ); + + it( 'passes an encoded site_url to the filter routes for a brand site', async () => { + mockedApiFetch + .mockResolvedValueOnce( { data: [ 'posts' ] } ) + .mockResolvedValueOnce( { data: [ 'updated' ] } ) + .mockResolvedValueOnce( { data: [], meta: { total: 0 } } ); + + const brandUrl = 'https://brand-one.example.com/sub?x=1&y=2'; + const filters = { ...baseFilters, site_url: brandUrl }; + + await expect( fetchContexts( filters ) ).resolves.toEqual( [ + 'posts', + ] ); + await expect( fetchActions( filters ) ).resolves.toEqual( [ + 'updated', + ] ); + await fetchUsers( filters ); + + expect( requestOf( 0 ) ).toEqual( { + method: 'GET', + pathname: '/onelogs/v1/logs/contexts', + query: { site_url: brandUrl }, + } ); + expect( requestOf( 1 ).pathname ).toBe( '/onelogs/v1/logs/actions' ); + expect( requestOf( 1 ).query ).toEqual( { site_url: brandUrl } ); + expect( requestOf( 2 ).pathname ).toBe( '/onelogs/v1/logs/users' ); + expect( requestOf( 2 ).query ).toEqual( { site_url: brandUrl } ); + } ); + + it( "doesn't pass a site_url to the filter routes for the governing site", async () => { + mockedApiFetch.mockResolvedValueOnce( { data: [ 'posts' ] } ); + + await fetchContexts( { ...baseFilters, site_url: 'governing-site' } ); + + expect( requestOf().pathname ).toBe( '/onelogs/v1/logs/contexts' ); + expect( requestOf().query ).toEqual( {} ); + } ); + + it( 'returns an empty list when the response lacks the requested key', async () => { + mockedApiFetch.mockResolvedValueOnce( {} ); + + await expect( fetchContexts( baseFilters ) ).resolves.toEqual( [] ); + } ); + + it( 'gets the brand sites from the page, without a request', async () => { + // The settings localized in setup.ts have no brand sites. + await expect( fetchSharedSites() ).resolves.toEqual( [] ); + expect( mockedApiFetch ).not.toHaveBeenCalled(); + } ); + + it( 'never adds apiFetch middleware or its own token header', async () => { + mockedApiFetch.mockResolvedValue( { + data: [], + meta: { total: 0, total_pages: 1 }, + } ); + + await fetchLogs( { ...baseFilters, site_url: BRAND_URL } ); + await fetchLogs( { ...baseFilters, site_url: 'governing-site' } ); + await fetchContexts( baseFilters ); + + // WordPress sets up apiFetch's root and nonce, so registering middleware per request would stack it up. + expect( apiFetch.use ).not.toHaveBeenCalled(); + for ( const [ options ] of mockedApiFetch.mock.calls ) { + expect( options ).not.toHaveProperty( 'headers' ); + } + expect( global.fetch ).not.toHaveBeenCalled(); + } ); +} ); diff --git a/tests/js/setup.ts b/tests/js/setup.ts index 11b8a05..4b63cfb 100644 --- a/tests/js/setup.ts +++ b/tests/js/setup.ts @@ -1,3 +1,5 @@ +/// + /** * External dependencies */ @@ -15,21 +17,12 @@ Object.defineProperty( global, 'fetch', { Object.defineProperty( window, 'OneLogsSettings', { value: { - restUrl: 'https://example.com/wp-json', - nonce: 'nonce', apiKey: 'api-key', + restNamespace: 'onelogs/v1', + setupUrl: '/wp-admin/admin.php?page=onelogs-settings', + sharedSites: [], siteType: 'governing-site', siteName: 'Example Site', - setupUrl: '/wp-admin/admin.php?page=onelogs-settings', - }, - writable: true, -} ); - -Object.defineProperty( window, 'OneLogsOnboarding', { - value: { - nonce: 'onboarding-nonce', - siteType: '', - setupUrl: '', }, writable: true, } ); diff --git a/tests/js/tsconfig.json b/tests/js/tsconfig.json index 858cf6f..995ba82 100644 --- a/tests/js/tsconfig.json +++ b/tests/js/tsconfig.json @@ -3,7 +3,6 @@ "extends": "../../tsconfig.json", "compilerOptions": { "noEmit": true, - "baseUrl": "../../", "types": [ "jest", "node", "@testing-library/jest-dom" ] }, "include": [ diff --git a/tests/js/utils.test.ts b/tests/js/utils.test.ts index b6b40e7..cdbdda3 100644 --- a/tests/js/utils.test.ts +++ b/tests/js/utils.test.ts @@ -1,14 +1,19 @@ /** - * External dependencies + * Internal dependencies */ import { API_KEY, - API_NAMESPACE, - NONCE, - SITE_TYPE, + REST_NAMESPACE, + SHARED_SITES, SITE_NAME, + SITE_TYPE, } from '@/js/constants'; -import { isValidUrl, formatDate } from '@/js/utils'; +import { + formatDate, + getErrorMessage, + isValidUrl, + normalizeUrl, +} from '@/js/utils'; describe( 'utils', () => { it( 'validates well-formed urls', () => { @@ -16,19 +21,114 @@ describe( 'utils', () => { expect( isValidUrl( 'not-a-url' ) ).toBe( false ); } ); + it( 'only accepts http and https urls', () => { + expect( isValidUrl( 'http://localhost:8890' ) ).toBe( true ); + expect( isValidUrl( 'HTTPS://example.com' ) ).toBe( true ); + expect( isValidUrl( 'ftp://example.com' ) ).toBe( false ); + expect( isValidUrl( 'javascript:alert(1)' ) ).toBe( false ); + expect( isValidUrl( 'mailto:a@b.c' ) ).toBe( false ); + } ); + + it( 'normalizes urls so different spellings of a site match', () => { + expect( normalizeUrl( '' ) ).toBe( '' ); + expect( normalizeUrl( ' ' ) ).toBe( '' ); + expect( normalizeUrl( 'https://brand.example.com' ) ).toBe( + 'https://brand.example.com/' + ); + expect( normalizeUrl( ' HTTPS://Brand.Example.COM/ ' ) ).toBe( + 'https://brand.example.com/' + ); + // Only the scheme and host are case-insensitive. + expect( normalizeUrl( 'https://Example.com/Sub/Path' ) ).toBe( + 'https://example.com/Sub/Path/' + ); + } ); + + it( 'gets the message from rest errors and falls back otherwise', () => { + expect( + getErrorMessage( + { code: 'onelogs_bad_key', message: 'Key rejected.' }, + 'Fallback' + ) + ).toBe( 'Key rejected.' ); + expect( getErrorMessage( new Error( 'Boom' ), 'Fallback' ) ).toBe( + 'Boom' + ); + expect( getErrorMessage( { message: '' }, 'Fallback' ) ).toBe( + 'Fallback' + ); + expect( getErrorMessage( 'oops', 'Fallback' ) ).toBe( 'Fallback' ); + expect( getErrorMessage( null, 'Fallback' ) ).toBe( 'Fallback' ); + } ); + it( 'formats date strings into readable format', () => { const formatted = formatDate( '2024-01-15T10:30:00Z' ); expect( formatted ).toBeTruthy(); expect( typeof formatted ).toBe( 'string' ); } ); +} ); - it( 'reads wordpress settings constants from the global config', () => { - expect( API_NAMESPACE ).toBe( - 'https://example.com/wp-json/onelogs/v1' - ); +// Lets the tests unset the optional globals, which `exactOptionalPropertyTypes` won't allow directly. +const globals = window as unknown as { + OneLogsSettings: unknown; + OneLogsData: unknown; +}; + +describe( 'constants', () => { + it( 'reads the settings localized for the settings screen', () => { expect( API_KEY ).toBe( 'api-key' ); - expect( NONCE ).toBe( 'nonce' ); + expect( REST_NAMESPACE ).toBe( 'onelogs/v1' ); expect( SITE_TYPE ).toBe( 'governing-site' ); expect( SITE_NAME ).toBe( 'Example Site' ); + expect( SHARED_SITES ).toEqual( [] ); + } ); + + it( 'falls back to the data localized for the logs dashboard', () => { + const settings = window.OneLogsSettings; + globals.OneLogsSettings = undefined; + globals.OneLogsData = { + apiKey: '', + restNamespace: 'onelogs/v1', + setupUrl: '', + sharedSites: [ + { id: 'one', name: 'Brand One', url: 'https://one.test/' }, + ], + siteName: 'Dashboard Site', + siteType: 'brand-site', + }; + + try { + jest.isolateModules( () => { + const constants = + require( '@/js/constants' ) as typeof import('@/js/constants'); + + expect( constants.SITE_TYPE ).toBe( 'brand-site' ); + expect( constants.SITE_NAME ).toBe( 'Dashboard Site' ); + expect( constants.API_KEY ).toBe( '' ); + expect( constants.SHARED_SITES ).toHaveLength( 1 ); + } ); + } finally { + globals.OneLogsSettings = settings; + globals.OneLogsData = undefined; + } + } ); + + it( 'uses defaults when nothing is localized', () => { + const settings = window.OneLogsSettings; + globals.OneLogsSettings = undefined; + + try { + jest.isolateModules( () => { + const constants = + require( '@/js/constants' ) as typeof import('@/js/constants'); + + expect( constants.REST_NAMESPACE ).toBe( 'onelogs/v1' ); + expect( constants.SITE_TYPE ).toBe( '' ); + expect( constants.API_KEY ).toBe( '' ); + expect( constants.SHARED_SITES ).toEqual( [] ); + } ); + } finally { + globals.OneLogsSettings = settings; + } } ); } ); diff --git a/tests/phpunit/Integration/Modules/Core/AssetsTest.php b/tests/phpunit/Integration/Modules/Core/AssetsTest.php index 1b091b1..98d9ac4 100644 --- a/tests/phpunit/Integration/Modules/Core/AssetsTest.php +++ b/tests/phpunit/Integration/Modules/Core/AssetsTest.php @@ -65,18 +65,63 @@ public function test_defer_scripts_does_not_duplicate_defer_attribute(): void { } /** - * Ensures localized data exposes the expected keys. + * Ensures localized data exposes the expected keys, and a governing site gets no keys at all. */ public function test_get_localized_data_returns_expected_keys(): void { + $this->reset_localized_data(); update_option( Settings::OPTION_SITE_TYPE, Settings::SITE_TYPE_GOVERNING, false ); + Settings::set_shared_sites( + [ + [ + 'id' => 'site-one', + 'name' => 'Brand One', + 'url' => 'https://brand.test', + 'api_key' => 'brand-key', + ], + ] + ); $data = Assets::get_localized_data(); - $this->assertArrayHasKey( 'nonce', $data ); - $this->assertArrayHasKey( 'apiKey', $data ); - $this->assertArrayHasKey( 'restUrl', $data ); - $this->assertArrayHasKey( 'setupUrl', $data ); - $this->assertArrayHasKey( 'siteType', $data ); - $this->assertArrayHasKey( 'siteName', $data ); + $this->assertSame( [ 'apiKey', 'restNamespace', 'setupUrl', 'sharedSites', 'siteName', 'siteType' ], array_keys( $data ) ); + $this->assertSame( 'onelogs/v1', $data['restNamespace'] ); + $this->assertSame( Settings::SITE_TYPE_GOVERNING, $data['siteType'] ); + + // Governing sites don't have a key of their own, and the brand sites' keys never reach the browser. + $this->assertSame( '', $data['apiKey'] ); + $this->assertSame( + [ + [ + 'id' => 'site-one', + 'name' => 'Brand One', + 'url' => 'https://brand.test/', + ], + ], + $data['sharedSites'] + ); + $this->assertStringNotContainsString( 'brand-key', (string) wp_json_encode( $data ) ); + + delete_option( Settings::OPTION_GOVERNING_SHARED_SITES ); + } + + /** + * Ensures a brand site gets its own key, which its settings screen shows. + */ + public function test_get_localized_data_gives_brand_sites_their_key(): void { + $this->reset_localized_data(); + update_option( Settings::OPTION_SITE_TYPE, Settings::SITE_TYPE_CONSUMER, false ); + + $data = Assets::get_localized_data(); + + $this->assertSame( Settings::get_api_key(), $data['apiKey'] ); + $this->assertSame( [], $data['sharedSites'] ); + } + + /** + * Clears the cached localized data, so each test builds it for its own settings. + */ + private function reset_localized_data(): void { + $property = new \ReflectionProperty( Assets::class, 'localized_data' ); + $property->setValue( null, [] ); } } diff --git a/tests/phpunit/Integration/Modules/Core/RestTest.php b/tests/phpunit/Integration/Modules/Core/RestTest.php deleted file mode 100644 index b389a00..0000000 --- a/tests/phpunit/Integration/Modules/Core/RestTest.php +++ /dev/null @@ -1,50 +0,0 @@ -register_hooks(); - - $this->assertTrue( true ); - } - - /** - * Tests that the OneLogs token header is added once. - */ - public function test_allowed_cors_headers_adds_onelogs_token_once(): void { - $rest = new Rest(); - - $this->assertSame( - [ 'X-WP-Nonce', 'X-OneLogs-Token' ], - $rest->allowed_cors_headers( [ 'X-WP-Nonce' ] ), - 'Token should be added to headers' - ); - - $this->assertSame( - [ 'X-OneLogs-Token' ], - $rest->allowed_cors_headers( [ 'X-OneLogs-Token' ] ), - 'Token should not be readded' - ); - } -} diff --git a/tests/phpunit/Integration/Modules/Rest/Governing_Site_ControllerTest.php b/tests/phpunit/Integration/Modules/Rest/Governing_Site_ControllerTest.php new file mode 100644 index 0000000..303d21c --- /dev/null +++ b/tests/phpunit/Integration/Modules/Rest/Governing_Site_ControllerTest.php @@ -0,0 +1,300 @@ +}> + */ + private array $requests = []; + + /** + * {@inheritDoc} + */ + protected function setUp(): void { + parent::setUp(); + + delete_option( Settings::OPTION_CONSUMER_PARENT_SITE_URL ); + delete_option( Settings::OPTION_GOVERNING_SHARED_SITES ); + } + + /** + * {@inheritDoc} + */ + protected function tearDown(): void { + delete_option( Settings::OPTION_SITE_TYPE ); + delete_option( Settings::OPTION_CONSUMER_PARENT_SITE_URL ); + delete_option( Settings::OPTION_GOVERNING_SHARED_SITES ); + + parent::tearDown(); + } + + /** + * Ensures a governing site with this brand site's key connects it (TC-021, TC-028). + */ + public function test_governing_site_with_the_key_connects(): void { + $server = $this->brand_server(); + + $response = $server->dispatch( $this->signed( 'POST', '/onelogs/v1/governing-site', Settings::get_api_key() ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( untrailingslashit( self::GOVERNING_URL ), Settings::get_parent_site_url() ); + } + + /** + * Ensures a wrong key can't connect, and doesn't set the governing site (TC-034). + */ + public function test_wrong_key_cannot_connect(): void { + $server = $this->brand_server(); + + $response = $server->dispatch( $this->signed( 'POST', '/onelogs/v1/governing-site', 'wrong-key' ) ); + + $this->assertContains( $response->get_status(), [ 401, 403 ] ); + $this->assertNull( Settings::get_parent_site_url() ); + } + + /** + * Ensures a request without the sending site's URL can't connect, which used to trust the Origin header. + */ + public function test_missing_site_url_cannot_connect(): void { + $server = $this->brand_server(); + $request = new \WP_REST_Request( 'POST', '/onelogs/v1/governing-site' ); + $request->set_header( 'X-OneLogs-Token', Settings::get_api_key() ); + $request->set_header( 'Origin', self::GOVERNING_URL ); + + $response = $server->dispatch( $request ); + + $this->assertContains( $response->get_status(), [ 401, 403 ] ); + $this->assertNull( Settings::get_parent_site_url() ); + } + + /** + * Ensures a connected brand site can't be claimed by another governing site (TC-039). + */ + public function test_connected_brand_site_rejects_another_governing_site(): void { + $server = $this->brand_server(); + Settings::set_parent_site_url( self::GOVERNING_URL ); + + $response = $server->dispatch( $this->signed( 'POST', '/onelogs/v1/governing-site', Settings::get_api_key(), 'https://other-governing.test/' ) ); + + $this->assertSame( 409, $response->get_status() ); + $this->assertSame( untrailingslashit( self::GOVERNING_URL ), Settings::get_parent_site_url() ); + } + + /** + * Ensures the connected governing site can reconnect, however its URL is spelled. + */ + public function test_connected_governing_site_can_reconnect(): void { + $server = $this->brand_server(); + Settings::set_parent_site_url( self::GOVERNING_URL ); + + $response = $server->dispatch( $this->signed( 'POST', '/onelogs/v1/governing-site', Settings::get_api_key(), 'HTTPS://Governing.test' ) ); + + $this->assertSame( 200, $response->get_status() ); + } + + /** + * Ensures the governing site can disconnect this site without being called back. + */ + public function test_governing_site_disconnects_brand_site(): void { + $server = $this->brand_server(); + Settings::set_parent_site_url( self::GOVERNING_URL ); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $server->dispatch( $this->signed( 'DELETE', '/onelogs/v1/governing-site', Settings::get_api_key() ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertTrue( $response->get_data()['governing_site_notified'] ); + $this->assertNull( Settings::get_parent_site_url() ); + $this->assertSame( [], $this->requests ); + } + + /** + * Ensures an admin disconnecting tells the governing site, which removes the brand site (TC-024, TC-025). + */ + public function test_admin_disconnect_deregisters_from_the_governing_site(): void { + $server = $this->brand_server(); + Settings::set_parent_site_url( self::GOVERNING_URL ); + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $server->dispatch( new \WP_REST_Request( 'DELETE', '/onelogs/v1/governing-site' ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertTrue( $response->get_data()['governing_site_notified'] ); + $this->assertNull( Settings::get_parent_site_url() ); + + $this->assertCount( 1, $this->requests ); + $this->assertSame( 'https://governing.test/wp-json/onelogs/v1/brand-site', $this->requests[0]['url'] ); + $this->assertSame( 'DELETE', $this->requests[0]['args']['method'] ); + $this->assertSame( Settings::get_api_key(), $this->requests[0]['args']['headers']['X-OneLogs-Token'] ); + } + + /** + * Ensures disconnecting still works when the governing site can't be told, with a message saying so. + */ + public function test_admin_disconnect_reports_an_unreachable_governing_site(): void { + $server = $this->brand_server(); + Settings::set_parent_site_url( self::GOVERNING_URL ); + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + $this->mock_remote_requests( static fn () => new \WP_Error( 'http_request_failed', 'timeout' ), $this->requests ); + + $response = $server->dispatch( new \WP_REST_Request( 'DELETE', '/onelogs/v1/governing-site' ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertFalse( $response->get_data()['governing_site_notified'] ); + $this->assertStringContainsString( 'could not be notified', $response->get_data()['message'] ); + $this->assertNull( Settings::get_parent_site_url() ); + } + + /** + * Ensures an anonymous request can't disconnect the site. + */ + public function test_anonymous_request_cannot_disconnect(): void { + $server = $this->brand_server(); + Settings::set_parent_site_url( self::GOVERNING_URL ); + + $response = $server->dispatch( new \WP_REST_Request( 'DELETE', '/onelogs/v1/governing-site' ) ); + + $this->assertSame( 401, $response->get_status() ); + $this->assertNotNull( Settings::get_parent_site_url() ); + } + + /** + * Ensures regenerating the key returns a new one that replaces the old one (TC-019, TC-020). + */ + public function test_admin_regenerates_the_key(): void { + $server = $this->brand_server(); + $old_key = Settings::get_api_key(); + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + + $response = $server->dispatch( new \WP_REST_Request( 'POST', '/onelogs/v1/secret-key' ) ); + + $this->assertSame( 200, $response->get_status() ); + $new_key = $response->get_data()['secret_key']; + $this->assertSame( 128, strlen( $new_key ) ); + $this->assertNotSame( $old_key, $new_key ); + $this->assertSame( $new_key, Settings::get_api_key() ); + } + + /** + * Ensures the brand site routes aren't on governing sites, and the governing site routes aren't on brand sites. + */ + public function test_routes_follow_the_site_type(): void { + $brand_routes = $this->brand_server()->get_routes(); + $this->assertArrayHasKey( '/onelogs/v1/governing-site', $brand_routes ); + $this->assertArrayHasKey( '/onelogs/v1/secret-key', $brand_routes ); + $this->assertArrayNotHasKey( '/onelogs/v1/brand-site', $brand_routes ); + + $governing_routes = $this->governing_server()->get_routes(); + $this->assertArrayHasKey( '/onelogs/v1/brand-site', $governing_routes ); + $this->assertArrayNotHasKey( '/onelogs/v1/governing-site', $governing_routes ); + $this->assertArrayNotHasKey( '/onelogs/v1/secret-key', $governing_routes ); + } + + /** + * Ensures a brand site can remove itself from its governing site with its own key. + */ + public function test_brand_site_removes_itself_from_the_governing_site(): void { + $server = $this->governing_server(); + Settings::set_shared_sites( [ $this->brand_site() ] ); + + $response = $server->dispatch( $this->signed( 'DELETE', '/onelogs/v1/brand-site', 'brand-key', 'https://brand.test' ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( [], Settings::get_shared_sites() ); + } + + /** + * Ensures a brand site can't remove itself with the wrong key, or remove another site. + */ + public function test_brand_site_needs_its_own_key_to_remove_itself(): void { + $server = $this->governing_server(); + Settings::set_shared_sites( [ $this->brand_site() ] ); + + $wrong_key = $server->dispatch( $this->signed( 'DELETE', '/onelogs/v1/brand-site', 'wrong-key', 'https://brand.test' ) ); + $wrong_url = $server->dispatch( $this->signed( 'DELETE', '/onelogs/v1/brand-site', 'brand-key', 'https://other-brand.test' ) ); + + $this->assertContains( $wrong_key->get_status(), [ 401, 403 ] ); + $this->assertContains( $wrong_url->get_status(), [ 401, 403 ] ); + $this->assertCount( 1, Settings::get_shared_sites() ); + } + + /** + * Builds a REST server for a brand site. + */ + private function brand_server(): \WP_REST_Server { + update_option( Settings::OPTION_SITE_TYPE, Settings::SITE_TYPE_CONSUMER ); + + return $this->set_up_rest_server( [ new Governing_Site_Controller(), new Brand_Site_Controller(), new Secret_Key_Controller() ] ); + } + + /** + * Builds a REST server for a governing site. + */ + private function governing_server(): \WP_REST_Server { + update_option( Settings::OPTION_SITE_TYPE, Settings::SITE_TYPE_GOVERNING ); + + return $this->set_up_rest_server( [ new Governing_Site_Controller(), new Brand_Site_Controller(), new Secret_Key_Controller() ] ); + } + + /** + * A brand site of the governing site. + * + * @return array + */ + private function brand_site(): array { + return [ + 'id' => 'site-one', + 'name' => 'Brand One', + 'url' => 'https://brand.test', + 'api_key' => 'brand-key', + ]; + } + + /** + * Builds a request signed like another site sends it. + * + * @param string $method The method. + * @param string $route The route. + * @param string $api_key The key the sender holds. + * @param string $site_url The sender's URL. + * + * @return \WP_REST_Request> + */ + private function signed( string $method, string $route, string $api_key, string $site_url = self::GOVERNING_URL ): \WP_REST_Request { + $request = new \WP_REST_Request( $method, $route ); + $request->set_header( 'X-OneLogs-Token', $api_key ); + $request->set_header( 'X-OneLogs-Site-URL', $site_url ); + + return $request; + } +} diff --git a/tests/phpunit/Integration/Modules/Rest/Logs_REST_ControllerTest.php b/tests/phpunit/Integration/Modules/Rest/Logs_REST_ControllerTest.php new file mode 100644 index 0000000..acc57cf --- /dev/null +++ b/tests/phpunit/Integration/Modules/Rest/Logs_REST_ControllerTest.php @@ -0,0 +1,373 @@ +}> + */ + private array $requests = []; + + /** + * {@inheritDoc} + */ + protected function setUp(): void { + parent::setUp(); + + global $wpdb; + + // Stream's log table, with the columns OneLogs reads. The test case makes it a temporary table. + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange + $wpdb->query( + "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}stream ( + ID bigint(20) unsigned NOT NULL AUTO_INCREMENT, + site_id bigint(20) unsigned NOT NULL DEFAULT 1, + blog_id bigint(20) unsigned NOT NULL DEFAULT 1, + object_id bigint(20) unsigned NULL, + user_id bigint(20) unsigned NOT NULL DEFAULT 0, + user_role varchar(50) NOT NULL DEFAULT '', + summary longtext NOT NULL, + created datetime NOT NULL, + connector varchar(100) NOT NULL, + context varchar(100) NOT NULL, + action varchar(100) NOT NULL, + ip varchar(39) NULL, + PRIMARY KEY (ID) + )" + ); + // phpcs:enable + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery + $wpdb->insert( + $wpdb->prefix . 'stream', + [ + 'summary' => 'Local log', + // The database returns IDs as strings, which strict types rejected. + 'object_id' => 42, + 'created' => '2026-11-01 10:00:00', + 'connector' => 'posts', + 'context' => 'post', + 'action' => 'updated', + 'ip' => '127.0.0.1', + ] + ); + + delete_option( Settings::OPTION_CONSUMER_PARENT_SITE_URL ); + delete_option( Settings::OPTION_GOVERNING_SHARED_SITES ); + } + + /** + * {@inheritDoc} + */ + protected function tearDown(): void { + delete_option( Settings::OPTION_SITE_TYPE ); + delete_option( Settings::OPTION_CONSUMER_PARENT_SITE_URL ); + delete_option( Settings::OPTION_GOVERNING_SHARED_SITES ); + + parent::tearDown(); + } + + /** + * Ensures anonymous requests can't read logs. + */ + public function test_anonymous_requests_cannot_read_logs(): void { + $server = $this->server_for( Settings::SITE_TYPE_CONSUMER ); + + $response = $server->dispatch( new \WP_REST_Request( 'GET', '/onelogs/v1/logs' ) ); + + $this->assertSame( 401, $response->get_status() ); + } + + /** + * Ensures a brand site's own admin can read its logs (TC-056). + */ + public function test_admin_reads_local_logs(): void { + $server = $this->server_for( Settings::SITE_TYPE_CONSUMER ); + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + + $response = $server->dispatch( $this->logs_request() ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( [ 'Local log' ], array_column( $response->get_data()['data'], 'summary' ) ); + } + + /** + * Ensures the connected governing site can read the brand site's logs with its key. + */ + public function test_connected_governing_site_reads_logs(): void { + $server = $this->server_for( Settings::SITE_TYPE_CONSUMER ); + Settings::set_parent_site_url( self::GOVERNING_URL ); + + $response = $server->dispatch( $this->logs_request( [], Settings::get_api_key() ) ); + + $this->assertSame( 200, $response->get_status() ); + } + + /** + * Ensures the key alone isn't enough: the request has to come from the connected governing site (TC-025). + */ + public function test_other_sites_cannot_read_logs_with_the_key(): void { + $server = $this->server_for( Settings::SITE_TYPE_CONSUMER ); + + // Not connected yet. + $not_connected = $server->dispatch( $this->logs_request( [], Settings::get_api_key() ) ); + + // Connected to a different governing site. + Settings::set_parent_site_url( 'https://other-governing.test' ); + $other_site = $server->dispatch( $this->logs_request( [], Settings::get_api_key() ) ); + + // Connected, with an old key (TC-020). + Settings::set_parent_site_url( self::GOVERNING_URL ); + $old_key = $server->dispatch( $this->logs_request( [], 'old-key' ) ); + + $this->assertSame( 401, $not_connected->get_status() ); + $this->assertSame( 401, $other_site->get_status() ); + $this->assertSame( 401, $old_key->get_status() ); + } + + /** + * Ensures a brand site never fetches other sites' logs for a `site_url` parameter (TC-058). + */ + public function test_brand_site_ignores_site_url(): void { + $server = $this->server_for( Settings::SITE_TYPE_CONSUMER ); + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + $this->mock_remote_requests( static fn () => self::http_response( 200, [ 'data' => [ [ 'summary' => 'Remote log' ] ] ] ), $this->requests ); + + $response = $server->dispatch( + $this->logs_request( + [ + 'site_url' => 'https://another-site.test', + 'include_shared_sites' => 'true', + 'current_site_logs' => 'true', + ] + ) + ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( [], $this->requests ); + $this->assertSame( [ 'Local log' ], array_column( $response->get_data()['data'], 'summary' ) ); + } + + /** + * Ensures a governing site only fetches logs from its own brand sites. + */ + public function test_governing_site_rejects_unknown_site_url(): void { + $server = $this->governing_server(); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $server->dispatch( $this->brand_logs_request( 'https://not-a-brand.test' ) ); + + $this->assertSame( 404, $response->get_status() ); + $this->assertSame( [], $this->requests ); + } + + /** + * Ensures a brand site's logs are fetched with its key, and labeled with its name and URL (TC-051, TC-052). + */ + public function test_governing_site_reads_brand_site_logs(): void { + $server = $this->governing_server(); + $this->mock_remote_requests( + static fn () => self::http_response( + 200, + [ + 'status' => 'success', + 'data' => [ + [ + 'ID' => 7, + 'summary' => 'Remote log', + ], + ], + 'meta' => [ + 'total' => 1, + 'total_pages' => 1, + ], + ] + ), + $this->requests + ); + + // The site is found however its URL is spelled. + $response = $server->dispatch( $this->brand_logs_request( 'https://Brand.test', [ 'search' => 'Remote' ] ) ); + + $this->assertSame( 200, $response->get_status() ); + + $this->assertCount( 1, $this->requests ); + $this->assertStringStartsWith( 'https://brand.test/wp-json/onelogs/v1/logs?', $this->requests[0]['url'] ); + $this->assertSame( 'brand-key', $this->requests[0]['args']['headers']['X-OneLogs-Token'] ); + + parse_str( (string) wp_parse_url( $this->requests[0]['url'], PHP_URL_QUERY ), $query ); + $this->assertArrayNotHasKey( 'site_url', $query ); + $this->assertSame( 'Remote', $query['search'] ?? null ); + $this->assertSame( '1', $query['current_site_logs'] ?? null ); + + $log = $response->get_data()['data'][0]; + $this->assertSame( 'Remote log', $log['summary'] ); + $this->assertSame( 'Brand One', $log['site_name'] ); + $this->assertSame( 'https://brand.test/', $log['site_url'] ); + $this->assertTrue( $log['is_remote'] ); + $this->assertSame( 1, $response->get_data()['meta']['total'] ); + } + + /** + * Ensures an unreachable brand site gives a clear error instead of an empty 200 (TC-054). + */ + public function test_unreachable_brand_site_returns_an_error(): void { + $server = $this->governing_server(); + $this->mock_remote_requests( static fn () => new \WP_Error( 'http_request_failed', 'cURL error 28' ), $this->requests ); + + $response = $server->dispatch( $this->brand_logs_request( 'https://brand.test' ) ); + + $this->assertSame( 502, $response->get_status() ); + $this->assertSame( 'onelogs_brand_site_unreachable', $response->get_data()['code'] ); + $this->assertStringContainsString( 'Could not reach Brand One', $response->get_data()['message'] ); + $this->assertSame( 'true', $response->get_headers()['x-vip-reached-origin'] ?? null ); + } + + /** + * Ensures a brand site rejecting the stored key says so (TC-020, TC-054). + */ + public function test_rejected_key_returns_an_error(): void { + $server = $this->governing_server(); + $this->mock_remote_requests( static fn () => self::http_response( 401, [ 'code' => 'rest_forbidden' ] ), $this->requests ); + + foreach ( [ 'logs', 'logs/contexts', 'logs/actions', 'logs/users' ] as $route ) { + $request = new \WP_REST_Request( 'GET', '/onelogs/v1/' . $route ); + $request->set_query_params( + [ + 'site_url' => 'https://brand.test', + 'include_shared_sites' => 'true', + ] + ); + + $response = $server->dispatch( $request ); + + $this->assertSame( 502, $response->get_status(), $route ); + $this->assertSame( 'onelogs_bad_key', $response->get_data()['code'], $route ); + $this->assertStringContainsString( 'Brand One rejected the API key', $response->get_data()['message'], $route ); + } + } + + /** + * Ensures a brand site's own error message is passed on. + */ + public function test_brand_site_error_message_is_passed_on(): void { + $server = $this->governing_server(); + $this->mock_remote_requests( static fn () => self::http_response( 500, [ 'message' => '

There has been a critical error on this website.

' ] ), $this->requests ); + + $response = $server->dispatch( $this->brand_logs_request( 'https://brand.test' ) ); + + $this->assertSame( 502, $response->get_status() ); + $this->assertSame( 'Brand One returned an error: There has been a critical error on this website.', $response->get_data()['message'] ); + } + + /** + * Ensures the governing site's own logs don't call out. + */ + public function test_governing_site_reads_its_own_logs(): void { + $server = $this->governing_server(); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $server->dispatch( $this->logs_request() ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( [], $this->requests ); + $this->assertSame( [ 'Local log' ], array_column( $response->get_data()['data'], 'summary' ) ); + } + + /** + * Builds a REST server with the logs routes for a site type. + * + * @param string $site_type The site type. + */ + private function server_for( string $site_type ): \WP_REST_Server { + update_option( Settings::OPTION_SITE_TYPE, $site_type ); + + return $this->set_up_rest_server( [ new Logs_REST_Controller() ] ); + } + + /** + * Builds a REST server for a governing site with one brand site, and logs in its admin. + */ + private function governing_server(): \WP_REST_Server { + $server = $this->server_for( Settings::SITE_TYPE_GOVERNING ); + + Settings::set_shared_sites( + [ + [ + 'id' => 'site-one', + 'name' => 'Brand One', + 'url' => 'https://brand.test', + 'api_key' => 'brand-key', + ], + ] + ); + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + + return $server; + } + + /** + * Builds a request for this site's logs. + * + * @param array $query Query arguments. + * @param ?string $api_key Sign it like the governing site, with this key. + * + * @return \WP_REST_Request> + */ + private function logs_request( array $query = [], ?string $api_key = null ): \WP_REST_Request { + $request = new \WP_REST_Request( 'GET', '/onelogs/v1/logs' ); + $request->set_query_params( $query + [ 'current_site_logs' => 'true' ] ); + + if ( null !== $api_key ) { + $request->set_header( 'X-OneLogs-Token', $api_key ); + $request->set_header( 'X-OneLogs-Site-URL', self::GOVERNING_URL ); + } + + return $request; + } + + /** + * Builds a request for a brand site's logs, like the dashboard sends it. + * + * @param string $site_url The brand site's URL. + * @param array $query More query arguments. + * + * @return \WP_REST_Request> + */ + private function brand_logs_request( string $site_url, array $query = [] ): \WP_REST_Request { + $request = new \WP_REST_Request( 'GET', '/onelogs/v1/logs' ); + $request->set_query_params( + $query + [ + 'site_url' => $site_url, + 'include_shared_sites' => 'true', + 'current_site_logs' => 'false', + ] + ); + + return $request; + } +} diff --git a/tests/phpunit/Integration/Modules/Rest/Shared_Sites_ControllerTest.php b/tests/phpunit/Integration/Modules/Rest/Shared_Sites_ControllerTest.php new file mode 100644 index 0000000..343bb42 --- /dev/null +++ b/tests/phpunit/Integration/Modules/Rest/Shared_Sites_ControllerTest.php @@ -0,0 +1,354 @@ +}> + */ + private array $requests = []; + + /** + * {@inheritDoc} + */ + protected function setUp(): void { + parent::setUp(); + + update_option( Settings::OPTION_SITE_TYPE, Settings::SITE_TYPE_GOVERNING ); + delete_option( Settings::OPTION_GOVERNING_SHARED_SITES ); + wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); + + $this->server = $this->set_up_rest_server( [ new Shared_Sites_Controller() ] ); + } + + /** + * {@inheritDoc} + */ + protected function tearDown(): void { + delete_option( Settings::OPTION_SITE_TYPE ); + delete_option( Settings::OPTION_GOVERNING_SHARED_SITES ); + + parent::tearDown(); + } + + /** + * Ensures the routes exist only on governing sites. + */ + public function test_routes_are_only_registered_on_governing_sites(): void { + $this->assertArrayHasKey( '/onelogs/v1/shared-sites', $this->server->get_routes() ); + + update_option( Settings::OPTION_SITE_TYPE, Settings::SITE_TYPE_CONSUMER ); + $server = $this->set_up_rest_server( [ new Shared_Sites_Controller() ] ); + + $this->assertArrayNotHasKey( '/onelogs/v1/shared-sites', $server->get_routes() ); + } + + /** + * Ensures only admins can save brand sites. + */ + public function test_saving_requires_manage_options(): void { + wp_set_current_user( self::factory()->user->create( [ 'role' => 'editor' ] ) ); + + $response = $this->save_sites( [ $this->site() ] ); + + $this->assertSame( 403, $response->get_status() ); + } + + /** + * Ensures a new site is health-checked on the brand site by the server, and saved without its key leaving the server (TC-028). + */ + public function test_saving_a_new_site_health_checks_it_and_hides_keys(): void { + $this->mock_remote_requests( static fn () => self::http_response( 200, [ 'message' => 'Connected' ] ), $this->requests ); + + $response = $this->save_sites( [ $this->site() ] ); + + $this->assertSame( 200, $response->get_status() ); + + // The health check went to the brand site, signed with its key and this site's URL. + $this->assertCount( 1, $this->requests ); + $this->assertSame( 'https://brand.test/wp-json/onelogs/v1/governing-site', $this->requests[0]['url'] ); + $this->assertSame( 'POST', $this->requests[0]['args']['method'] ); + $this->assertSame( 'brand-key', $this->requests[0]['args']['headers']['X-OneLogs-Token'] ); + $this->assertSame( Utils::get_current_site_url(), $this->requests[0]['args']['headers']['X-OneLogs-Site-URL'] ); + + // The site is stored with its key, but the response has no keys. + $this->assertSame( 'brand-key', Settings::get_shared_site_by_url( 'https://brand.test' )['api_key'] ?? null ); + $data = $response->get_data(); + $this->assertCount( 1, $data['shared_sites'] ); + $this->assertArrayNotHasKey( 'api_key', $data['shared_sites'][0] ); + $this->assertNotEmpty( $data['shared_sites'][0]['id'] ); + } + + /** + * Ensures non-http URLs are rejected with the validation message (TC-033). + */ + public function test_saving_rejects_non_http_urls(): void { + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + foreach ( [ 'ftp://brand.test', 'javascript:alert(1)', 'abc' ] as $url ) { + $response = $this->save_sites( [ $this->site( [ 'url' => $url ] ) ] ); + + $this->assertSame( 400, $response->get_status(), $url ); + $this->assertSame( 'Enter a valid URL (must start with http or https).', $response->get_data()['message'], $url ); + } + + $this->assertSame( [], $this->requests ); + $this->assertSame( [], Settings::get_shared_sites() ); + } + + /** + * Ensures different spellings of the same URL are duplicates (TC-036, TC-037). + */ + public function test_saving_rejects_duplicate_url_variants(): void { + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + foreach ( [ 'https://brand.test', 'https://brand.test/', 'HTTPS://brand.test/', 'https://Brand.TEST' ] as $variant ) { + $response = $this->save_sites( + [ + $this->site(), + $this->site( + [ + 'name' => 'Again', + 'url' => $variant, + ] + ), + ] + ); + + $this->assertSame( 400, $response->get_status(), $variant ); + $this->assertSame( 'Brand Site already exists.', $response->get_data()['message'], $variant ); + } + + $this->assertSame( [], $this->requests ); + } + + /** + * Ensures a key the brand site rejects isn't saved, and the reason is returned (TC-034). + */ + public function test_saving_reports_a_rejected_key(): void { + $this->mock_remote_requests( static fn () => self::http_response( 401, [ 'code' => 'rest_forbidden' ] ), $this->requests ); + + $response = $this->save_sites( [ $this->site() ] ); + + $this->assertSame( 400, $response->get_status() ); + $this->assertSame( 'onelogs_bad_key', $response->get_data()['code'] ); + $this->assertSame( [], Settings::get_shared_sites() ); + } + + /** + * Ensures a brand site already connected elsewhere isn't saved (TC-039). + */ + public function test_saving_reports_a_brand_site_connected_elsewhere(): void { + $this->mock_remote_requests( static fn () => self::http_response( 409, [ 'code' => 'onelogs_already_connected' ] ), $this->requests ); + + $response = $this->save_sites( [ $this->site() ] ); + + $this->assertSame( 409, $response->get_status() ); + $this->assertSame( 'onelogs_already_connected', $response->get_data()['code'] ); + $this->assertSame( [], Settings::get_shared_sites() ); + } + + /** + * Ensures an unreachable site isn't saved, and the 502 keeps its message on VIP (TC-035). + */ + public function test_saving_reports_an_unreachable_site(): void { + $this->mock_remote_requests( static fn () => new \WP_Error( 'http_request_failed', 'cURL error 6' ), $this->requests ); + + $response = $this->save_sites( [ $this->site() ] ); + + $this->assertSame( 502, $response->get_status() ); + $this->assertSame( 'onelogs_health_check_failed', $response->get_data()['code'] ); + $this->assertSame( 'true', $response->get_headers()['x-vip-reached-origin'] ?? null ); + $this->assertSame( [], Settings::get_shared_sites() ); + } + + /** + * Ensures editing a site's name with a blank key keeps the stored key, without a new health check (TC-040). + */ + public function test_editing_without_a_key_keeps_the_stored_key(): void { + $stored = $this->store_site(); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $this->save_sites( + [ + [ + 'id' => $stored['id'], + 'name' => 'Renamed', + 'url' => $stored['url'], + 'api_key' => '', + ], + ] + ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( [], $this->requests ); + + $site = Settings::get_shared_site_by_url( 'https://brand.test' ); + $this->assertSame( 'Renamed', $site['name'] ?? null ); + $this->assertSame( 'brand-key', $site['api_key'] ?? null ); + } + + /** + * Ensures a new key is health-checked before it replaces the stored one (TC-042). + */ + public function test_editing_with_a_new_key_health_checks_it(): void { + $stored = $this->store_site(); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $this->save_sites( + [ + [ + 'id' => $stored['id'], + 'name' => $stored['name'], + 'url' => $stored['url'], + 'api_key' => 'new-key', + ], + ] + ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertCount( 1, $this->requests ); + $this->assertSame( 'new-key', $this->requests[0]['args']['headers']['X-OneLogs-Token'] ); + $this->assertSame( 'new-key', Settings::get_shared_site_by_url( 'https://brand.test' )['api_key'] ?? null ); + } + + /** + * Ensures a changed URL needs a key, since the stored key belongs to the old site. + */ + public function test_editing_the_url_requires_a_key(): void { + $stored = $this->store_site(); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $this->save_sites( + [ + [ + 'id' => $stored['id'], + 'name' => $stored['name'], + 'url' => 'https://other-brand.test', + 'api_key' => '', + ], + ] + ); + + $this->assertSame( 400, $response->get_status() ); + $this->assertSame( 'onelogs_missing_api_key', $response->get_data()['code'] ); + $this->assertSame( [], $this->requests ); + } + + /** + * Ensures deleting a site removes it and tells the brand site to disconnect (TC-045). + */ + public function test_deleting_a_site_removes_it_and_notifies_the_brand_site(): void { + $stored = $this->store_site(); + $this->mock_remote_requests( static fn () => self::http_response( 200 ), $this->requests ); + + $response = $this->server->dispatch( new \WP_REST_Request( 'DELETE', '/onelogs/v1/shared-sites/' . $stored['id'] ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertTrue( $response->get_data()['governing_site_notified'] ); + $this->assertSame( [], $response->get_data()['shared_sites'] ); + $this->assertSame( [], Settings::get_shared_sites() ); + + $this->assertCount( 1, $this->requests ); + $this->assertSame( 'https://brand.test/wp-json/onelogs/v1/governing-site', $this->requests[0]['url'] ); + $this->assertSame( 'DELETE', $this->requests[0]['args']['method'] ); + } + + /** + * Ensures a site is still removed when the brand site can't be told, with a message saying so. + */ + public function test_deleting_a_site_reports_an_unreachable_brand_site(): void { + $stored = $this->store_site(); + $this->mock_remote_requests( static fn () => new \WP_Error( 'http_request_failed', 'timeout' ), $this->requests ); + + $response = $this->server->dispatch( new \WP_REST_Request( 'DELETE', '/onelogs/v1/shared-sites/' . $stored['id'] ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertFalse( $response->get_data()['governing_site_notified'] ); + $this->assertStringContainsString( 'Brand One was removed', $response->get_data()['message'] ); + $this->assertSame( [], Settings::get_shared_sites() ); + } + + /** + * Ensures deleting an unknown site fails. + */ + public function test_deleting_an_unknown_site_returns_404(): void { + $response = $this->server->dispatch( new \WP_REST_Request( 'DELETE', '/onelogs/v1/shared-sites/unknown-id' ) ); + + $this->assertSame( 404, $response->get_status() ); + } + + /** + * Builds a brand site for the request. + * + * @param array $overrides Fields to change. + * + * @return array + */ + private function site( array $overrides = [] ): array { + return $overrides + [ + 'name' => 'Brand One', + 'url' => 'https://brand.test', + 'api_key' => 'brand-key', + ]; + } + + /** + * Stores a brand site directly. + * + * @return array{api_key: string, id: string, name: string, url: string} + */ + private function store_site(): array { + Settings::set_shared_sites( [ $this->site( [ 'id' => 'site-one' ] ) ] ); + + $site = Settings::get_shared_site_by_url( 'https://brand.test' ); + $this->assertNotNull( $site ); + + return $site; + } + + /** + * Saves brand sites through the route. + * + * @param array> $sites The sites. + */ + private function save_sites( array $sites ): \WP_REST_Response { + $request = new \WP_REST_Request( 'POST', '/onelogs/v1/shared-sites' ); + $request->set_header( 'Content-Type', 'application/json' ); + $request->set_body( (string) wp_json_encode( [ 'sites_data' => $sites ] ) ); + + return $this->server->dispatch( $request ); + } +} diff --git a/tests/phpunit/Integration/Modules/Settings/SettingsTest.php b/tests/phpunit/Integration/Modules/Settings/SettingsTest.php index 9643b55..2357395 100644 --- a/tests/phpunit/Integration/Modules/Settings/SettingsTest.php +++ b/tests/phpunit/Integration/Modules/Settings/SettingsTest.php @@ -60,6 +60,9 @@ public function test_register_settings_registers_consumer_options(): void { $this->assertSettingRegistered( Settings::OPTION_CONSUMER_API_KEY ); $this->assertSettingRegistered( Settings::OPTION_CONSUMER_PARENT_SITE_URL ); + + // The key is only shown on the settings screen and regenerated through the OneLogs route. + $this->assertFalse( get_registered_settings()[ Settings::OPTION_CONSUMER_API_KEY ]['show_in_rest'] ); } /** Ensures register_settings registers governing options. */ @@ -69,6 +72,9 @@ public function test_register_settings_registers_governing_options(): void { $this->settings->register_settings(); $this->assertSettingRegistered( Settings::OPTION_GOVERNING_SHARED_SITES ); + + // The stored sites hold the brand sites' keys, which never leave the server. + $this->assertFalse( get_registered_settings()[ Settings::OPTION_GOVERNING_SHARED_SITES ]['show_in_rest'] ); } /** Ensures get_site_type returns null when not set. */ @@ -210,6 +216,73 @@ public function test_get_shared_site_by_url(): void { $this->assertSame( 'Brand One', Settings::get_shared_site_by_url( 'https://brand-one.example' )['name'] ); } + /** Ensures get_shared_site_by_url finds a site however its URL is spelled (TC-037). */ + public function test_get_shared_site_by_url_matches_url_variants(): void { + Settings::set_shared_sites( + [ + [ + 'id' => 'brand-1', + 'name' => 'Brand One', + 'url' => 'https://brand-one.example', + 'api_key' => 'brand-one-key', + ], + ] + ); + + foreach ( [ 'https://brand-one.example/', 'HTTPS://Brand-One.example', ' https://brand-one.example ' ] as $variant ) { + $this->assertSame( 'Brand One', Settings::get_shared_site_by_url( $variant )['name'] ?? null, $variant ); + } + } + + /** Ensures the sites for the browser have no keys. */ + public function test_get_shared_sites_without_keys(): void { + Settings::set_shared_sites( + [ + [ + 'id' => 'brand-1', + 'name' => 'Brand One', + 'url' => 'https://brand-one.example', + 'api_key' => 'brand-one-key', + ], + ] + ); + + $this->assertSame( + [ + [ + 'id' => 'brand-1', + 'name' => 'Brand One', + 'url' => 'https://brand-one.example/', + ], + ], + Settings::get_shared_sites_without_keys() + ); + } + + /** Ensures remove_shared_site removes only the matching site. */ + public function test_remove_shared_site(): void { + Settings::set_shared_sites( + [ + [ + 'id' => 'brand-1', + 'name' => 'Brand One', + 'url' => 'https://brand-one.example', + 'api_key' => 'brand-one-key', + ], + [ + 'id' => 'brand-2', + 'name' => 'Brand Two', + 'url' => 'https://brand-two.example', + 'api_key' => 'brand-two-key', + ], + ] + ); + + $this->assertFalse( Settings::remove_shared_site( 'https://unknown.example' ) ); + $this->assertTrue( Settings::remove_shared_site( 'HTTPS://Brand-One.example/' ) ); + $this->assertSame( [ 'https://brand-two.example/' ], array_keys( Settings::get_shared_sites() ) ); + } + /** Ensures get_shared_site_by_url returns null for unknown URLs. */ public function test_get_shared_site_by_url_returns_null_for_unknown(): void { $this->assertNull( Settings::get_shared_site_by_url( 'https://unknown.example' ) ); diff --git a/tests/phpunit/Integration/UtilsTest.php b/tests/phpunit/Integration/UtilsTest.php new file mode 100644 index 0000000..b418252 --- /dev/null +++ b/tests/phpunit/Integration/UtilsTest.php @@ -0,0 +1,60 @@ + + */ + public static function url_provider(): array { + return [ + 'adds a trailing slash' => [ 'https://brand.test', 'https://brand.test/' ], + 'keeps a trailing slash' => [ 'https://brand.test/', 'https://brand.test/' ], + 'trims whitespace' => [ ' https://brand.test ', 'https://brand.test/' ], + 'lowercases the scheme' => [ 'HTTPS://brand.test/', 'https://brand.test/' ], + 'lowercases the host' => [ 'https://Brand.TEST', 'https://brand.test/' ], + 'keeps the port' => [ 'https://Brand.test:8443', 'https://brand.test:8443/' ], + 'keeps the case of the path' => [ 'HTTPS://Brand.test/SubSite', 'https://brand.test/SubSite/' ], + 'leaves strings without a scheme' => [ 'Brand.test', 'Brand.test/' ], + ]; + } + + /** + * Ensures URLs are normalized so different spellings compare equal (QA TC-037). + * + * @param string $url The URL to normalize. + * @param string $expected The normalized URL. + */ + #[DataProvider( 'url_provider' )] + public function test_normalize_url( string $url, string $expected ): void { + $this->assertSame( $expected, Utils::normalize_url( $url ) ); + } + + /** + * Ensures the current site URL comes from the home option, normalized. + */ + public function test_get_current_site_url(): void { + // wp-env defines WP_HOME, which wins over the stored option. + add_filter( 'option_home', static fn (): string => 'HTTP://Governing.example', 20 ); + + $this->assertSame( 'http://governing.example/', Utils::get_current_site_url() ); + } +} diff --git a/tests/phpunit/TestCase.php b/tests/phpunit/TestCase.php index fbfc946..db2a6bc 100644 --- a/tests/phpunit/TestCase.php +++ b/tests/phpunit/TestCase.php @@ -81,5 +81,79 @@ protected function checkRequirements(): void { // phpcs:ignore Generic.CodeAnaly parent::checkRequirements(); } - // Add any common setup or utility methods for tests here. + /** + * Replaces the REST server with one that only has the given controllers' routes. + * + * The plugin only loads with Stream active, so tests register the routes they need. Set the site type first, since + * routes are registered by site type. + * + * @param \OneLogs\Modules\Rest\Abstract_REST_Controller[] $controllers The controllers to register. + */ + protected function set_up_rest_server( array $controllers ): \WP_REST_Server { + global $wp_rest_server; + + // Avoid registering core and other plugin routes. + remove_all_actions( 'rest_api_init' ); + + // The settings are read through /wp/v2/settings in some flows, and are registered on rest_api_init. + add_action( 'rest_api_init', [ new \OneLogs\Modules\Settings\Settings(), 'register_settings' ] ); + + foreach ( $controllers as $controller ) { + add_action( 'rest_api_init', [ $controller, 'register_routes' ] ); + } + + $wp_rest_server = new \WP_REST_Server(); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited + do_action( 'rest_api_init', $wp_rest_server ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core hook. + + return $wp_rest_server; + } + + /** + * Answers outgoing HTTP requests with a callback instead of the network, and records them. + * + * @param callable $responder Returns the response for a URL and request arguments. + * @param ?array $requests Collects the requests. + * + * @phpstan-param callable(string, array): (array|\WP_Error) $responder + * @phpstan-param ?array}> $requests + * @param-out array}> $requests + */ + protected function mock_remote_requests( callable $responder, ?array &$requests = null ): void { + $requests = []; + + add_filter( + 'pre_http_request', + static function ( $preempt, $args, $url ) use ( $responder, &$requests ) { // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter -- The filter's signature. + $requests[] = [ + 'url' => (string) $url, + 'args' => (array) $args, + ]; + + return $responder( (string) $url, (array) $args ); + }, + 10, + 3 + ); + } + + /** + * Builds a fake HTTP response like `wp_remote_request()` returns. + * + * @param int $code The status code. + * @param array|string $body The body. Arrays are JSON-encoded. + * + * @return array + */ + protected static function http_response( int $code, array|string $body = [] ): array { + return [ + 'headers' => [], + 'body' => is_array( $body ) ? (string) wp_json_encode( $body ) : $body, + 'response' => [ + 'code' => $code, + 'message' => get_status_header_desc( $code ), + ], + 'cookies' => [], + 'filename' => null, + ]; + } } diff --git a/webpack.config.js b/webpack.config.js index 32f5582..9f9da06 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -79,7 +79,7 @@ const scripts = { 'src', 'admin', 'settings', - 'index.js' + 'index.tsx' ), }, module: {