Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ All notable changes to this project will be documented in this file.

- **Improvement**: `DB_EXPECT_EXISTING=true` makes Notifuse refuse to start instead of creating or initialising its system database, and refuse to create a missing workspace database, on a server that must already hold the data (an upgrade, a restore). Without it, a first start on an empty database is now logged as a warning.

- **Fix**: The setup wizard sends telemetry and update checks as it shows them; they were sent switched off unless « Advanced Settings » was opened. It also saves the EHLO hostname it tests with, accepts several root emails as documented, asks for the SSO redirect URI and scopes, and accepts a setup where the environment sets only some SMTP or SSO values.
- **Fix**: The setup wizard sends telemetry and update checks as it shows them; they were sent switched off unless « Advanced Settings » was opened. It also saves the EHLO hostname it tests with, accepts several root emails as documented, asks for the SSO redirect URI and scopes, accepts a setup where the environment sets only some SMTP or SSO values, and waits for the restarted server before offering to sign in.

- **Fix**: The sender name set in the setup wizard or in System settings is used for system emails; it was always replaced by « Notifuse » unless `SMTP_FROM_NAME` was set.

Expand Down
30 changes: 29 additions & 1 deletion console/src/pages/SetupWizard.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { i18n } from '@lingui/core'
import { I18nProvider } from '@lingui/react'
Expand Down Expand Up @@ -72,6 +72,7 @@ describe('SetupWizard', () => {
})

afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})

Expand Down Expand Up @@ -246,6 +247,33 @@ describe('SetupWizard', () => {
expect(setupApi.initialize).not.toHaveBeenCalled()
})

it('waits for another boot_id than the process that saved the setup: it still answers', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
// Opened before a restart: the status read then has another boot_id than the process
// that handles setup.initialize. Only the latter counts.
mockStatus({ ...ALL_BUT_UPDATES, boot_id: 'boot-at-opening' })
vi.mocked(setupApi.initialize).mockResolvedValue({ success: true, message: 'ok', boot_id: 'boot-before' })
const status = (bootId: string) =>
new Response(JSON.stringify({ ...ALL_BUT_UPDATES, is_installed: true, boot_id: bootId }), { status: 200 })
vi.spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(status('boot-before'))
.mockResolvedValueOnce(status('boot-after'))
renderWizard()

await screen.findByRole('switch', { name: 'Check for updates' })
await complete(user)
expect(await screen.findByText('Applying your configuration')).toBeInTheDocument()
await waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1))
// The first answer comes from the process shutting down: still waiting.
expect(screen.queryByText('Notifuse is ready')).not.toBeInTheDocument()
await act(async () => {
await vi.advanceTimersByTimeAsync(1000)
})
expect(await screen.findByText('Notifuse is ready')).toBeInTheDocument()
expect(globalThis.fetch).toHaveBeenCalledTimes(2)
})

it('moves to the restart view once the setup is saved', async () => {
const user = userEvent.setup()
mockStatus(ALL_BUT_UPDATES)
Expand Down
31 changes: 25 additions & 6 deletions console/src/pages/SetupWizard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ const EMPTY_STATUS: SetupStatus = {
// Fields inside a panel keep two thirds of antd's margin: the panel's padding closes each one.
const FORM_THEME = { components: { Form: { itemMarginBottom: 16 } } }

// Only without a boot_id to compare (a server older than the field): a pause before the
// first poll, so that the process shutting down is less likely to answer it.
const RESTART_PAUSE_MS = 2000
const RESTART_POLL_MS = 1000
const RESTART_ATTEMPTS = 60
Expand Down Expand Up @@ -63,6 +65,18 @@ async function subscribeToNewsletter(email: string, values: SetupFormValues) {
}
}

/** The answer comes from another process than the one read on opening the page. */
async function isRestarted(response: Response, previousBootId: string | undefined): Promise<boolean> {
if (!previousBootId) return true
try {
const body = (await response.json()) as Partial<SetupStatus>
// A server without boot_id cannot say; take its answer as before.
return !body.boot_id || body.boot_id !== previousBootId
} catch {
return false
}
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function SetupWizard() {
Expand Down Expand Up @@ -104,19 +118,23 @@ export default function SetupWizard() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

/** Polls the address that just answered setup.initialize until the restarted server answers. */
const waitForRestart = async (rootEmail: string | undefined) => {
/**
* Polls the address that just answered setup.initialize until the restarted server answers:
* a boot_id other than the one of the process that handled setup.initialize, since that
* process still answers 200 while it drains.
*/
const waitForRestart = async (rootEmail: string | undefined, previousBootId: string | undefined) => {
const started = Date.now()
const tick = () => Math.round((Date.now() - started) / 1000)
setRestart({ phase: 'waiting', elapsed: 0, rootEmail })
await sleep(RESTART_PAUSE_MS)
if (!previousBootId) await sleep(RESTART_PAUSE_MS)
for (let attempt = 0; attempt < RESTART_ATTEMPTS; attempt++) {
if (unmounted.current) return
setRestart({ phase: 'waiting', elapsed: tick(), rootEmail })
try {
// A plain GET without custom headers: no CORS preflight while the server comes back.
const response = await fetch(`${apiBaseUrl()}/api/setup.status?t=${Date.now()}`, { method: 'GET' })
if (response.ok) {
if (response.ok && (await isRestarted(response, previousBootId))) {
setRestart({ phase: 'ready', elapsed: tick(), rootEmail })
return
}
Expand All @@ -138,8 +156,9 @@ export default function SetupWizard() {
const all = form.getFieldsValue(true) as SetupFormValues
setSubmitting(true)
setError(undefined)
let initializedBy: string | undefined
try {
await setupApi.initialize(buildSetupConfig(all, status))
initializedBy = (await setupApi.initialize(buildSetupConfig(all, status))).boot_id
} catch (err) {
setError(err instanceof Error ? err.message : t`Failed to complete setup`)
setSubmitting(false)
Expand All @@ -148,7 +167,7 @@ export default function SetupWizard() {
const rootEmail = isFieldLocked(status, 'root_email') ? undefined : splitList(all.root_email)[0]
if (all.subscribe_newsletter && rootEmail) await subscribeToNewsletter(rootEmail, all)
setSubmitting(false)
await waitForRestart(rootEmail)
await waitForRestart(rootEmail, initializedBy)
}

const goTo = (summary: PanelSummary) => {
Expand Down
4 changes: 4 additions & 0 deletions console/src/types/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,15 @@ export interface SetupStatus {
oidc_configured: boolean
/** Before install only: the setting keys whose environment variable is set (names, never values). */
env_overrides?: string[]
/** Random, drawn at each start of the server process: a new value means it restarted. */
boot_id?: string
}

export interface InitializeResponse {
success: boolean
message: string
/** The process that handled the request; the page waits for the server to answer another. */
boot_id?: string
}

export interface TestSMTPConfig {
Expand Down
14 changes: 14 additions & 0 deletions internal/http/setup_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/Notifuse/notifuse/internal/service"
"github.com/Notifuse/notifuse/pkg/logger"
"github.com/google/uuid"
)

// AppShutdowner defines the interface for triggering app shutdown
Expand All @@ -23,6 +24,9 @@ type SetupHandler struct {
settingService *service.SettingService
logger logger.Logger
app AppShutdowner
// bootID is drawn once per handler, so once per process: the setup page tells
// the restarted server from the one shutting down by a different value.
bootID string
}

// NewSetupHandler creates a new setup handler
Expand All @@ -37,6 +41,7 @@ func NewSetupHandler(
settingService: settingService,
logger: logger,
app: app,
bootID: uuid.NewString(),
}
}

Expand All @@ -51,6 +56,9 @@ type StatusResponse struct {
// EnvOverrides lists, before install only, the setting keys whose environment
// variable is set (names, never values), so the wizard can lock those fields.
EnvOverrides []string `json:"env_overrides,omitempty"`
// BootID is random and changes at each start of the process; it says nothing
// about the host or the time.
BootID string `json:"boot_id"`
}

// InitializeRequest represents the setup initialization request
Expand Down Expand Up @@ -87,6 +95,9 @@ type InitializeRequest struct {
type InitializeResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
// BootID of the process that handled the request: the setup page waits for the
// server to answer another one, since this process restarts to apply the setup.
BootID string `json:"boot_id"`
}

// TestSMTPRequest represents the SMTP connection test request
Expand Down Expand Up @@ -130,6 +141,7 @@ func (h *SetupHandler) Status(w http.ResponseWriter, r *http.Request) {
RootEmailConfigured: configStatus.RootEmailConfigured,
SMTPBridgeConfigured: configStatus.SMTPBridgeConfigured,
OIDCConfigured: configStatus.OIDCConfigured,
BootID: h.bootID,
}
if !isInstalled {
for key, set := range h.setupService.GetEnvOverrides() {
Expand Down Expand Up @@ -166,6 +178,7 @@ func (h *SetupHandler) Initialize(w http.ResponseWriter, r *http.Request) {
response := InitializeResponse{
Success: true,
Message: "Setup already completed. System is ready to use.",
BootID: h.bootID,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -244,6 +257,7 @@ func (h *SetupHandler) Initialize(w http.ResponseWriter, r *http.Request) {
response := InitializeResponse{
Success: true,
Message: "Setup completed successfully. Server is restarting with new configuration...",
BootID: h.bootID,
}

w.Header().Set("Content-Type", "application/json")
Expand Down
33 changes: 33 additions & 0 deletions internal/http/setup_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,39 @@ func TestSetupHandler_Status_EnvOverrides(t *testing.T) {
})
}

// The setup page waits for a different boot_id to know the restarted process answers,
// not the one shutting down.
func TestSetupHandler_Status_BootID(t *testing.T) {
newHandler := func() *SetupHandler {
settingService := service.NewSettingService(newMockSettingRepository())
setupService := service.NewSetupService(settingService, &service.UserService{}, newMockUserRepository(), logger.NewLogger(), "secret-key", nil, nil)
return NewSetupHandler(setupService, settingService, logger.NewLogger(), newMockAppShutdowner())
}
bootID := func(h *SetupHandler) string {
w := httptest.NewRecorder()
h.Status(w, httptest.NewRequest(http.MethodGet, "/api/setup.status", nil))
var body StatusResponse
require.NoError(t, json.NewDecoder(w.Body).Decode(&body))
return body.BootID
}

first := newHandler()
id := bootID(first)
assert.NotEmpty(t, id)
assert.Equal(t, id, bootID(first), "one process answers one boot_id")
assert.NotEqual(t, id, bootID(newHandler()), "a new process answers another")

// setup.initialize answers the boot_id of the process that handled it: the one the
// page compares against, whatever it read when it opened.
body := `{"root_email":"admin@example.com","api_endpoint":"https://api.example.com","smtp_host":"smtp.example.com","smtp_port":587,"smtp_from_email":"noreply@example.com"}`
w := httptest.NewRecorder()
first.Initialize(w, httptest.NewRequest(http.MethodPost, "/api/setup.initialize", bytes.NewBufferString(body)))
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var initialized InitializeResponse
require.NoError(t, json.NewDecoder(w.Body).Decode(&initialized))
assert.Equal(t, id, initialized.BootID)
}

func TestSetupHandler_TestSMTP(t *testing.T) {
tlsTrue := true
tlsFalse := false
Expand Down
Loading
Loading