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
9 changes: 9 additions & 0 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package main

import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
Expand Down Expand Up @@ -63,6 +65,13 @@ func runServer(cfg *config.Config, appLogger logger.Logger) error {
// Wait for shutdown signal or server error
select {
case err := <-serverError:
if errors.Is(err, http.ErrServerClosed) {
// The app closed its own server to load a new configuration (setup, system settings).
// The error still ends the process with a failure code, so that a process manager
// restarting only on failure starts it again.
appLogger.Info("Server stopped to load its new configuration - exiting so that the process manager restarts it")
return err
}
if err != nil {
appLogger.WithField("error", err.Error()).Error("Server error")
}
Expand Down
34 changes: 34 additions & 0 deletions cmd/api/shutdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"net/http"
"os"
"sync/atomic"
"testing"
Expand Down Expand Up @@ -82,3 +83,36 @@ func TestRunServer_ReturnsWhenTheShutdownOutlivesItsTimeout(t *testing.T) {
t.Fatal("runServer kept waiting for a shutdown past its timeout")
}
}

// selfClosedApp closes its own server, as setup and the system settings do to reload the configuration.
type selfClosedApp struct {
app.AppInterface
}

func (a *selfClosedApp) Initialize() error { return nil }

func (a *selfClosedApp) Start() error { return http.ErrServerClosed }

func TestRunServer_ServerClosedForReloadIsNotLoggedAsAnError(t *testing.T) {
originalNewApp := newApp
originalSignalNotify := signalNotify
defer func() {
newApp = originalNewApp
signalNotify = originalSignalNotify
}()
newApp = func(cfg *config.Config, opts ...app.AppOption) app.AppInterface { return &selfClosedApp{} }
signalNotify = func(c chan<- os.Signal, sig ...os.Signal) {}

ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockLogger := pkgmocks.NewMockLogger(ctrl)
mockLogger.EXPECT().WithField(gomock.Any(), gomock.Any()).Return(mockLogger).AnyTimes()
mockLogger.EXPECT().Info("Server started successfully").AnyTimes()
mockLogger.EXPECT().Info("Server stopped to load its new configuration - exiting so that the process manager restarts it").Times(1)
mockLogger.EXPECT().Error(gomock.Any()).Times(0)

err := runServer(&config.Config{}, mockLogger)

// Still an error: main exits with a failure code, which every restart policy restarts
assert.ErrorIs(t, err, http.ErrServerClosed)
}
22 changes: 22 additions & 0 deletions console/src/__tests__/SignInPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,28 @@ describe('SignInPage', () => {
expect(screen.getByText(/demo@notifuse.com/i)).toBeInTheDocument()
})

it('prefills the root email the setup handed over, once, without sending a code', async () => {
sessionStorage.setItem('notifuse_setup_signin_email', 'admin@acme.com')
const { unmount } = renderWithProviders(<SignInPage />)

await waitFor(() => expect(screen.getByLabelText(/email/i)).toHaveValue('admin@acme.com'))
expect(authService.authService.signIn).not.toHaveBeenCalled()
expect(sessionStorage.getItem('notifuse_setup_signin_email')).toBeNull()

unmount()
renderWithProviders(<SignInPage />)
expect(screen.getByLabelText(/email/i)).toHaveValue('')
})

it('lets an email in the URL win over the one the setup handed over', async () => {
sessionStorage.setItem('notifuse_setup_signin_email', 'admin@acme.com')
mockSearch.email = 'other@acme.com'
vi.mocked(authService.authService.signIn).mockResolvedValue({ message: 'ok' } as never)
renderWithProviders(<SignInPage />)

await waitFor(() => expect(authService.authService.signIn).toHaveBeenCalledWith({ email: 'other@acme.com' }))
})

it('does not auto-submit when email parameter is not present', async () => {
// Ensure email is not in search params
mockSearch.email = undefined
Expand Down
16 changes: 14 additions & 2 deletions console/src/components/setup/SmtpPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,14 @@ const DOCS = [
{ name: 'Postmark', href: 'https://postmarkapp.com/developer/user-guide/send-email-with-smtp' }
]

export function SmtpPanel({ status, state }: { status: SetupStatus; state: SetupPanelState }) {
export interface SmtpPanelProps {
status: SetupStatus
state: SetupPanelState
/** Told whether the last test failed, so that the summary says so too. */
onTestFailedChange?: (failed: boolean) => void
}

export function SmtpPanel({ status, state, onTestFailedChange }: SmtpPanelProps) {
const { t } = useLingui()
const form = Form.useFormInstance<SetupFormValues>()
const locked = isPanelLocked(status, 'smtp')
Expand All @@ -39,6 +46,11 @@ export function SmtpPanel({ status, state }: { status: SetupStatus; state: Setup
setResult(null)
}, [host, port, username, password, useTls])

const testFailed = !locked && result !== null && !result.ok
useEffect(() => {
onTestFailedChange?.(testFailed)
}, [testFailed, onTestFailedChange])

// setup.testSmtp tests only the values in its body (it applies env credentials, nothing else):
// with one of these set by the environment it would test another connection than the real one.
const testUnreliable = (['smtp_host', 'smtp_port', 'smtp_use_tls', 'smtp_ehlo_hostname'] as const).some((key) =>
Expand Down Expand Up @@ -132,7 +144,7 @@ export function SmtpPanel({ status, state }: { status: SetupStatus; state: Setup
</>
)
}}
state={!locked && result && !result.ok ? { tone: 'danger', label: t`Test failed` } : state}
state={state}
footer={footer}
>
{locked ? (
Expand Down
22 changes: 21 additions & 1 deletion console/src/components/setup/setupHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { PillTone } from '../layout'
import type { SetupStatus } from '../../types/setup'
import {
PANEL_SWITCH,
SETUP_FIELDS,
SETUP_PANELS,
isPanelLocked,
missingFields,
Expand All @@ -23,8 +24,20 @@ export interface PanelSummary extends SetupPanelState {
missing: SetupKey[]
}

/** What the form knows beyond the values: the fields its rules refuse, and the last SMTP test. */
export interface SetupFormChecks {
/** Fields whose rules currently report an error. */
fieldErrors?: SetupKey[]
/** The last connection test failed (and its values were not edited since). */
smtpTestFailed?: boolean
}

/** Each panel's state, from the same field spec as the form's rules. */
export function usePanelSummaries(status: SetupStatus, values: SetupFormValues): PanelSummary[] {
export function usePanelSummaries(
status: SetupStatus,
values: SetupFormValues,
checks: SetupFormChecks = {}
): PanelSummary[] {
const { t } = useLingui()
const titles: Record<SetupPanelId, string> = {
administrator: t`Administrator`,
Expand All @@ -39,6 +52,13 @@ export function usePanelSummaries(status: SetupStatus, values: SetupFormValues):
const summary = (tone: PillTone, label: string): PanelSummary => ({ id, title: titles[id], missing, tone, label })
if (isPanelLocked(status, id)) return summary('info', t`Set by environment`)
if (panelSwitch && values[panelSwitch] !== true) return summary('neutral', t`Off`)
// A failed connection test first: it is what the panel's alert says
if (id === 'smtp' && checks.smtpTestFailed) return summary('danger', t`Test failed`)
// A filled field its rules refuse (an invalid email or URL): the panel is not complete
const invalid = SETUP_FIELDS.filter(
(field) => field.panel === id && checks.fieldErrors?.includes(field.key) && !missing.includes(field.key)
).length
if (invalid > 0) return summary('danger', plural(invalid, { one: '# field to fix', other: '# fields to fix' }))
const count = missing.length
if (count > 0) return summary('warning', plural(count, { one: '# field to fill', other: '# fields to fill' }))
return summary('success', panelSwitch ? t`On` : t`Complete`)
Expand Down
31 changes: 31 additions & 0 deletions console/src/components/setup/signInHandoff.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { handOffSignInEmail, takeSignInEmail } from './signInHandoff'

describe('signInHandoff', () => {
afterEach(() => {
vi.restoreAllMocks()
sessionStorage.clear()
})

it('gives the handed email once', () => {
handOffSignInEmail('admin@acme.com')
expect(takeSignInEmail()).toBe('admin@acme.com')
expect(takeSignInEmail()).toBeUndefined()
})

it('stores nothing for no email', () => {
handOffSignInEmail(undefined)
expect(takeSignInEmail()).toBeUndefined()
})

it('does without storage when the browser refuses it', () => {
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('blocked')
})
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked')
})
expect(() => handOffSignInEmail('admin@acme.com')).not.toThrow()
expect(takeSignInEmail()).toBeUndefined()
})
})
24 changes: 24 additions & 0 deletions console/src/components/setup/signInHandoff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// The root email the setup page hands to the sign-in page across the full reload that follows
// the setup. Kept in this tab's session storage rather than the URL: an address in a query
// string ends up in server logs and history, and the sign-in page sends a code for it at once.
const KEY = 'notifuse_setup_signin_email'

/** Called by the setup page just before it reloads into the sign-in page. */
export function handOffSignInEmail(email: string | undefined): void {
try {
if (email) sessionStorage.setItem(KEY, email)
} catch {
// No storage (private mode, blocked site data): the field just stays empty.
}
}

/** Read once by the sign-in page: the address it prefills, without sending a code. */
export function takeSignInEmail(): string | undefined {
try {
const email = sessionStorage.getItem(KEY) ?? undefined
sessionStorage.removeItem(KEY)
return email || undefined
} catch {
return undefined
}
}
Loading
Loading