diff --git a/.dependency-cruiser-known-violations.json b/.dependency-cruiser-known-violations.json index 89cf5e61a..780bc35ff 100644 --- a/.dependency-cruiser-known-violations.json +++ b/.dependency-cruiser-known-violations.json @@ -57,50 +57,6 @@ "name": "modules-not-to-features" } }, - { - "type": "dependency", - "from": "app/modules/quota/quota-toast.tsx", - "to": "app/features/account/email-verification/email-verification-error.ts", - "unresolvedTo": "@/features/account/email-verification/email-verification-error", - "dependencyTypes": ["aliased", "aliased-tsconfig", "aliased-tsconfig-paths", "local", "import"], - "rule": { - "severity": "error", - "name": "modules-not-to-features" - } - }, - { - "type": "dependency", - "from": "app/modules/quota/quota-toast.tsx", - "to": "app/features/project/read-only/project-read-only-error.ts", - "unresolvedTo": "@/features/project/read-only/project-read-only-error", - "dependencyTypes": ["aliased", "aliased-tsconfig", "aliased-tsconfig-paths", "local", "import"], - "rule": { - "severity": "error", - "name": "modules-not-to-features" - } - }, - { - "type": "dependency", - "from": "app/modules/quota/quota-toast.tsx", - "to": "app/features/project/suspension/classify-suspension-error.ts", - "unresolvedTo": "@/features/project/suspension/classify-suspension-error", - "dependencyTypes": ["aliased", "aliased-tsconfig", "aliased-tsconfig-paths", "local", "import"], - "rule": { - "severity": "error", - "name": "modules-not-to-features" - } - }, - { - "type": "dependency", - "from": "app/modules/quota/quota-toast.tsx", - "to": "app/features/project/suspension/suspension-toast.ts", - "unresolvedTo": "@/features/project/suspension/suspension-toast", - "dependencyTypes": ["aliased", "aliased-tsconfig", "aliased-tsconfig-paths", "local", "import"], - "rule": { - "severity": "error", - "name": "modules-not-to-features" - } - }, { "type": "cycle", "from": "app/features/edge/proxy/overview/active-pops-globe.tsx", diff --git a/app/modules/quota/quota-toast.tsx b/app/components/error/mutation-error-toast.tsx similarity index 96% rename from app/modules/quota/quota-toast.tsx rename to app/components/error/mutation-error-toast.tsx index dee03a6bc..11c06d157 100644 --- a/app/modules/quota/quota-toast.tsx +++ b/app/components/error/mutation-error-toast.tsx @@ -1,11 +1,11 @@ -import { buildQuotaIncreaseRequest } from './build-quota-increase-request'; -import { classifyQuotaError, parseQuotaError } from './quota-error'; import { toastApiError } from '@/components/error/toast-api-error'; import { isEmailNotVerifiedError } from '@/features/account/email-verification/email-verification-error'; import { isProjectReadOnlyError } from '@/features/project/read-only/project-read-only-error'; import { isProjectSuspendedError } from '@/features/project/suspension/classify-suspension-error'; import { showProjectSuspendedToast } from '@/features/project/suspension/suspension-toast'; import { logger } from '@/modules/logger'; +import { buildQuotaIncreaseRequest } from '@/modules/quota/build-quota-increase-request'; +import { classifyQuotaError, parseQuotaError } from '@/modules/quota/quota-error'; import { paths } from '@/utils/config/paths.config'; import { getPathWithParams } from '@/utils/helpers/path.helper'; import { openSupportMessage } from '@/utils/open-support-message'; diff --git a/app/features/edge/dns-zone/components/refresh-nameservers-button.tsx b/app/features/edge/dns-zone/components/refresh-nameservers-button.tsx index 0a1cffedf..99d6b2607 100644 --- a/app/features/edge/dns-zone/components/refresh-nameservers-button.tsx +++ b/app/features/edge/dns-zone/components/refresh-nameservers-button.tsx @@ -1,5 +1,5 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { ReadOnlyGuard } from '@/features/project/read-only'; -import { showMutationErrorToast } from '@/modules/quota'; import { PermissionGate } from '@/modules/rbac'; import { formatRefreshCooldown, diff --git a/app/features/edge/dns-zone/discovery-preview.tsx b/app/features/edge/dns-zone/discovery-preview.tsx index 95ee752ef..88b013d05 100644 --- a/app/features/edge/dns-zone/discovery-preview.tsx +++ b/app/features/edge/dns-zone/discovery-preview.tsx @@ -1,6 +1,6 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { toastApiError } from '@/components/error/toast-api-error'; import { DnsRecordTable } from '@/features/edge/dns-records'; -import { showMutationErrorToast } from '@/modules/quota'; import { type IFlattenedDnsRecord, useBulkImportDnsRecords } from '@/resources/dns-records'; import { useCreateDnsZoneDiscovery, useDnsZoneDiscovery } from '@/resources/dns-zone-discoveries'; import { paths } from '@/utils/config/paths.config'; diff --git a/app/features/edge/dns-zone/dns-zone-form-dialog.tsx b/app/features/edge/dns-zone/dns-zone-form-dialog.tsx index e89107bf8..ad9b831f6 100644 --- a/app/features/edge/dns-zone/dns-zone-form-dialog.tsx +++ b/app/features/edge/dns-zone/dns-zone-form-dialog.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { AnalyticsAction, useAnalytics } from '@/modules/rybbit'; import { type CreateDnsZoneInput, diff --git a/app/features/edge/dns-zone/form/dns-record-form.tsx b/app/features/edge/dns-zone/form/dns-record-form.tsx index 3b3cf1554..31ec69860 100644 --- a/app/features/edge/dns-zone/form/dns-record-form.tsx +++ b/app/features/edge/dns-zone/form/dns-record-form.tsx @@ -14,12 +14,12 @@ import { TLSARecordField, TXTRecordField, } from './types'; -import { usePreserveTouchedOnSubmit } from '@/components/form/use-preserve-touched-on-submit'; import { - classifyQuotaError, showMutationErrorToast, showQuotaExceededToast, -} from '@/modules/quota'; +} from '@/components/error/mutation-error-toast'; +import { usePreserveTouchedOnSubmit } from '@/components/form/use-preserve-touched-on-submit'; +import { classifyQuotaError } from '@/modules/quota'; import { CreateDnsRecordSchema, createDnsRecordSchema, diff --git a/app/features/edge/dns-zone/overview/description-form-card.tsx b/app/features/edge/dns-zone/overview/description-form-card.tsx index f706d2f6d..197e29b14 100644 --- a/app/features/edge/dns-zone/overview/description-form-card.tsx +++ b/app/features/edge/dns-zone/overview/description-form-card.tsx @@ -1,5 +1,5 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { ReadOnlyGuard } from '@/features/project/read-only'; -import { showMutationErrorToast } from '@/modules/quota'; import { PermissionGate } from '@/modules/rbac'; import type { DnsZone } from '@/resources/dns-zones'; import { createDnsZoneSchema, useUpdateDnsZone } from '@/resources/dns-zones'; diff --git a/app/features/edge/domain/add/add-domains-dialog.tsx b/app/features/edge/domain/add/add-domains-dialog.tsx index f6c8fa529..4a16f1726 100644 --- a/app/features/edge/domain/add/add-domains-dialog.tsx +++ b/app/features/edge/domain/add/add-domains-dialog.tsx @@ -1,8 +1,8 @@ import { annotateSummaryItems } from './annotate-summary'; import { renderBulkSummaryContent } from './bulk-summary-content'; import { DuplicateDomainNotice } from './duplicate-domain-notice'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { toastApiError } from '@/components/error/toast-api-error'; -import { showMutationErrorToast } from '@/modules/quota'; import { AnalyticsAction, useAnalytics } from '@/modules/rybbit'; import { useApp } from '@/providers/app.provider'; import { diff --git a/app/features/edge/domain/domain-form-dialog.tsx b/app/features/edge/domain/domain-form-dialog.tsx index 42ac9e56a..5458a8e78 100644 --- a/app/features/edge/domain/domain-form-dialog.tsx +++ b/app/features/edge/domain/domain-form-dialog.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { AnalyticsAction, useAnalytics } from '@/modules/rybbit'; import { type DomainSchema, domainSchema, useCreateDomain, type Domain } from '@/resources/domains'; import { Form } from '@datum-cloud/datum-ui/form'; diff --git a/app/features/edge/domain/domain-header-actions.tsx b/app/features/edge/domain/domain-header-actions.tsx index 7d59eddbf..472b673a9 100644 --- a/app/features/edge/domain/domain-header-actions.tsx +++ b/app/features/edge/domain/domain-header-actions.tsx @@ -1,6 +1,6 @@ import { useConfirmationDialog } from '@/components/confirmation-dialog/confirmation-dialog.provider'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { showDomainInUseToast } from '@/features/edge/domain/domain-in-use-toast'; -import { showMutationErrorToast } from '@/modules/quota'; import { PermissionGate } from '@/modules/rbac'; import { type DnsZone } from '@/resources/dns-zones'; import { diff --git a/app/features/edge/domain/overview/verification-card.tsx b/app/features/edge/domain/overview/verification-card.tsx index 7c49843ad..60688e7a9 100644 --- a/app/features/edge/domain/overview/verification-card.tsx +++ b/app/features/edge/domain/overview/verification-card.tsx @@ -1,5 +1,5 @@ import { DateTime } from '@/components/date-time'; -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { useResourcePermissions } from '@/modules/rbac'; import { type Domain, diff --git a/app/features/edge/proxy/backends/algorithm-menu.tsx b/app/features/edge/proxy/backends/algorithm-menu.tsx index dd5c888f6..e4d6029f9 100644 --- a/app/features/edge/proxy/backends/algorithm-menu.tsx +++ b/app/features/edge/proxy/backends/algorithm-menu.tsx @@ -4,7 +4,7 @@ import { algorithmValue, type AlgorithmValue, } from './backend-pool'; -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { type HttpProxy, type HttpProxyLoadBalancer, diff --git a/app/features/edge/proxy/backends/backend-form-dialog.tsx b/app/features/edge/proxy/backends/backend-form-dialog.tsx index 025dc624a..187beef20 100644 --- a/app/features/edge/proxy/backends/backend-form-dialog.tsx +++ b/app/features/edge/proxy/backends/backend-form-dialog.tsx @@ -6,6 +6,7 @@ import { toBackendRows, type BackendRow, } from './backend-pool'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { OriginTypeCards, WorkloadServiceFields, @@ -13,7 +14,6 @@ import { } from '@/features/edge/proxy/form/origin-type-fields'; import { ProtocolEndpointInput } from '@/features/edge/proxy/form/protocol-endpoint-input'; import { useComputePluginSlug } from '@/features/edge/proxy/overview/compute-backend'; -import { showMutationErrorToast } from '@/modules/quota'; import { HTTP_PROXY_MAX_WEIGHT, type HttpProxy, @@ -309,7 +309,7 @@ export const BackendFormDialog = forwardRef< let backend: HttpProxyBackendInput; if (originLocked) { - backend = { raw: editing!.backend.raw, weight: nextWeight }; + backend = { raw: editing.backend.raw, weight: nextWeight }; } else if (data.originType === 'networkService') { const { tls: _tls, endpoint: _endpoint, ...raw } = keepRaw('networkService') ?? {}; backend = { diff --git a/app/features/edge/proxy/backends/backends-table-card.tsx b/app/features/edge/proxy/backends/backends-table-card.tsx index 3adced5e0..daa5b3508 100644 --- a/app/features/edge/proxy/backends/backends-table-card.tsx +++ b/app/features/edge/proxy/backends/backends-table-card.tsx @@ -1,8 +1,8 @@ import { poolWith, type BackendRow } from './backend-pool'; import { StatusChip } from '@/components/card/status-chip'; import { useConfirmationDialog } from '@/components/confirmation-dialog/confirmation-dialog.provider'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; -import { showMutationErrorToast } from '@/modules/quota'; import { usePermission } from '@/modules/rbac'; import { type HttpProxy, useUpdateHttpProxy } from '@/resources/http-proxies'; import { Badge } from '@datum-cloud/datum-ui/badge'; diff --git a/app/features/edge/proxy/backends/health-checks-card.tsx b/app/features/edge/proxy/backends/health-checks-card.tsx index 7ea26818e..e4ffcae9d 100644 --- a/app/features/edge/proxy/backends/health-checks-card.tsx +++ b/app/features/edge/proxy/backends/health-checks-card.tsx @@ -1,7 +1,7 @@ import { formatDuration, GATEWAY_DURATION_PATTERN, resolvedPassive } from './backend-pool'; import { FieldLabel } from '@/components/card/field-label'; import { ToggleState } from '@/components/card/toggle-state'; -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { PermissionButton } from '@/modules/rbac'; import { PASSIVE_HEALTH_CHECK_DEFAULTS, diff --git a/app/features/edge/proxy/overview/config-card.tsx b/app/features/edge/proxy/overview/config-card.tsx index 3589d136c..46fbdbb38 100644 --- a/app/features/edge/proxy/overview/config-card.tsx +++ b/app/features/edge/proxy/overview/config-card.tsx @@ -2,9 +2,9 @@ import { FieldLabel } from '@/components/card/field-label'; import { UnavailableBadge } from '@/components/card/inline-controls'; import { StatusChip, type StatusChipTone } from '@/components/card/status-chip'; import { useConfirmationDialog } from '@/components/confirmation-dialog/confirmation-dialog.provider'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { planSecurityUpdate } from '@/features/edge/proxy/overview/security-update'; import { WafCategoryList } from '@/features/edge/proxy/overview/waf-category-list'; -import { showMutationErrorToast } from '@/modules/quota'; import { useResourcePermissions } from '@/modules/rbac'; import { type HttpProxy, diff --git a/app/features/edge/proxy/overview/general-card.tsx b/app/features/edge/proxy/overview/general-card.tsx index 2ed0d5057..23f9f9387 100644 --- a/app/features/edge/proxy/overview/general-card.tsx +++ b/app/features/edge/proxy/overview/general-card.tsx @@ -1,8 +1,8 @@ import { BadgeCopy } from '@/components/badge/badge-copy'; import { FieldLabel } from '@/components/card/field-label'; import { DateTime } from '@/components/date-time/date-time'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { LazyNoteEditor } from '@/features/notes/lazy-note-editor'; -import { showMutationErrorToast } from '@/modules/quota'; import { useResourcePermissions } from '@/modules/rbac'; import { type HttpProxy, useUpdateHttpProxy } from '@/resources/http-proxies'; import { diff --git a/app/features/edge/proxy/overview/hostname-dns-records.tsx b/app/features/edge/proxy/overview/hostname-dns-records.tsx index 4bfb6e1bc..d16ce8a34 100644 --- a/app/features/edge/proxy/overview/hostname-dns-records.tsx +++ b/app/features/edge/proxy/overview/hostname-dns-records.tsx @@ -1,8 +1,8 @@ import { StatusChip } from '@/components/card/status-chip'; import { useConfirmationDialog } from '@/components/confirmation-dialog/confirmation-dialog.provider'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { planZoneRecord } from '@/features/edge/proxy/utils/zone-record-plan'; import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; -import { showMutationErrorToast } from '@/modules/quota'; import { PermissionButton } from '@/modules/rbac'; import { type CreateDnsRecordSchema, diff --git a/app/features/edge/proxy/overview/hostnames-card.tsx b/app/features/edge/proxy/overview/hostnames-card.tsx index 94d173ee3..424fa7d91 100644 --- a/app/features/edge/proxy/overview/hostnames-card.tsx +++ b/app/features/edge/proxy/overview/hostnames-card.tsx @@ -1,6 +1,7 @@ import { StatusChip } from '@/components/card/status-chip'; import { ValueRow } from '@/components/card/value-row'; import { useConfirmationDialog } from '@/components/confirmation-dialog/confirmation-dialog.provider'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { ProxyZoneRecordsWatch, useProxyZoneRecords, @@ -17,7 +18,6 @@ import { findZoneForHostname } from '@/features/edge/proxy/utils/delete-dns-prev import { buildHostnameState, type HostnameState } from '@/features/edge/proxy/utils/hostname-state'; import { requestWildcardHostnames } from '@/features/edge/proxy/utils/request-wildcards'; import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; -import { showMutationErrorToast } from '@/modules/quota'; import { PermissionButton, usePermission } from '@/modules/rbac'; import { ControlPlaneStatus } from '@/resources/base'; import { useDomains } from '@/resources/domains'; @@ -73,8 +73,7 @@ type HostnameRow = HostnameState & { type DomainCondition = { type?: string; status?: string }; function isVerifiedByZoneOnly(status: unknown): boolean { - const conditions = ((status as { conditions?: DomainCondition[] } | undefined)?.conditions ?? - []) as DomainCondition[]; + const conditions = (status as { conditions?: DomainCondition[] } | undefined)?.conditions ?? []; const isTrue = (type: string) => conditions.some((c) => c.type === type && c.status === 'True'); return isTrue('VerifiedDNSZone') && !isTrue('VerifiedDNS'); } diff --git a/app/features/edge/proxy/overview/tls-card.tsx b/app/features/edge/proxy/overview/tls-card.tsx index a1ac05956..543f2751c 100644 --- a/app/features/edge/proxy/overview/tls-card.tsx +++ b/app/features/edge/proxy/overview/tls-card.tsx @@ -1,9 +1,9 @@ import { FieldLabel } from '@/components/card/field-label'; import { StatusChip } from '@/components/card/status-chip'; import { ToggleState } from '@/components/card/toggle-state'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { WildcardsNotEnabledChip } from '@/features/edge/proxy/overview/hostname-status-chips'; import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'; -import { showMutationErrorToast } from '@/modules/quota'; import { PermissionGate } from '@/modules/rbac'; import { type HttpProxy, diff --git a/app/features/edge/proxy/proxy-basic-auth-dialog.tsx b/app/features/edge/proxy/proxy-basic-auth-dialog.tsx index 4308c4911..7c79257a7 100644 --- a/app/features/edge/proxy/proxy-basic-auth-dialog.tsx +++ b/app/features/edge/proxy/proxy-basic-auth-dialog.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { basicAuthSchema, type BasicAuthSchema, diff --git a/app/features/edge/proxy/proxy-form-dialog.tsx b/app/features/edge/proxy/proxy-form-dialog.tsx index 54e2c0a61..bc1521185 100644 --- a/app/features/edge/proxy/proxy-form-dialog.tsx +++ b/app/features/edge/proxy/proxy-form-dialog.tsx @@ -1,3 +1,4 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { OriginTypeCards, WorkloadServiceFields, @@ -6,7 +7,6 @@ import { import { ProtocolEndpointInput } from '@/features/edge/proxy/form/protocol-endpoint-input'; import { ProxyTlsField } from '@/features/edge/proxy/form/tls-field'; import { useComputePluginSlug } from '@/features/edge/proxy/overview/compute-backend'; -import { showMutationErrorToast } from '@/modules/quota'; import { AnalyticsAction, useAnalytics } from '@/modules/rybbit'; import { type HttpProxySchema, diff --git a/app/features/edge/proxy/proxy-hostnames-dialog.tsx b/app/features/edge/proxy/proxy-hostnames-dialog.tsx index e36f3f998..b04e3372c 100644 --- a/app/features/edge/proxy/proxy-hostnames-dialog.tsx +++ b/app/features/edge/proxy/proxy-hostnames-dialog.tsx @@ -1,6 +1,6 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { ProxyHostnamesField } from '@/features/edge/proxy/form/hostnames-field'; import { getUnverifiedHostnameError } from '@/features/edge/proxy/utils/hostname-verification'; -import { showMutationErrorToast } from '@/modules/quota'; import { type Domain, useDomains } from '@/resources/domains'; import { type HttpProxy, useUpdateHttpProxy } from '@/resources/http-proxies'; import { httpProxyHostnameSchema } from '@/resources/http-proxies/http-proxy.schema'; diff --git a/app/features/metric/export-policies/form/update-form.tsx b/app/features/metric/export-policies/form/update-form.tsx index a42b4d8b6..d6becd224 100644 --- a/app/features/metric/export-policies/form/update-form.tsx +++ b/app/features/metric/export-policies/form/update-form.tsx @@ -1,9 +1,9 @@ import { SinksForm } from './sink/sinks-form'; import { SourcesForm } from './source/sources-form'; import { useConfirmationDialog } from '@/components/confirmation-dialog/confirmation-dialog.provider'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { toastApiError } from '@/components/error/toast-api-error'; import { MetadataForm } from '@/components/metadata/metadata-form'; -import { showMutationErrorToast } from '@/modules/quota'; import { ExportPolicyAuthenticationType, ExportPolicySinkTypeEnum, diff --git a/app/features/notes/note-form-dialog.tsx b/app/features/notes/note-form-dialog.tsx index bb4375b63..631a26846 100644 --- a/app/features/notes/note-form-dialog.tsx +++ b/app/features/notes/note-form-dialog.tsx @@ -1,6 +1,6 @@ import { LazyNoteEditor } from './lazy-note-editor'; import { NoteMeta } from './note-meta'; -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { useCreateNote, useUpdateNote } from '@/resources/notes/note.queries'; import type { Note, SubjectRef } from '@/resources/notes/note.schema'; import { diff --git a/app/features/project/read-only/README.md b/app/features/project/read-only/README.md index 93a0611fe..4994eaad1 100644 --- a/app/features/project/read-only/README.md +++ b/app/features/project/read-only/README.md @@ -128,6 +128,6 @@ deliberate exceptions keep deep paths: - `app/resources/*/*.queries.ts` import `use-guarded-mutation` directly. The barrel re-exports React components, and dragging those into every data-layer module is a real bundle cost on a hot path. -- `app/modules/quota/quota-toast.tsx` imports the leaf error/toast modules. +- `app/components/error/mutation-error-toast.tsx` imports the leaf error/toast modules. Going through the barrel would create a cycle, since `GuardedWriteButton` imports `@/modules/quota`. diff --git a/app/features/project/settings/general-card.tsx b/app/features/project/settings/general-card.tsx index 397be39a1..4131c31a4 100644 --- a/app/features/project/settings/general-card.tsx +++ b/app/features/project/settings/general-card.tsx @@ -1,5 +1,5 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { ReadOnlyGuard } from '@/features/project/read-only'; -import { showMutationErrorToast } from '@/modules/quota'; import { useApp } from '@/providers/app.provider'; import type { Project } from '@/resources/projects'; import { projectKeys, updateProjectSchema, useUpdateProject } from '@/resources/projects'; diff --git a/app/features/secret/form/edit/edit-key-value-dialog.tsx b/app/features/secret/form/edit/edit-key-value-dialog.tsx index 6b9434c12..b4cf04c5c 100644 --- a/app/features/secret/form/edit/edit-key-value-dialog.tsx +++ b/app/features/secret/form/edit/edit-key-value-dialog.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { toSecretData, useUpdateSecret } from '@/resources/secrets'; import { Form } from '@datum-cloud/datum-ui/form'; import { toast } from '@datum-cloud/datum-ui/toast'; diff --git a/app/features/secret/form/edit/edit-keys.tsx b/app/features/secret/form/edit/edit-keys.tsx index cad1a7132..1db687e5a 100644 --- a/app/features/secret/form/edit/edit-keys.tsx +++ b/app/features/secret/form/edit/edit-keys.tsx @@ -1,10 +1,10 @@ import { EditKeyValueDialog, EditKeyValueDialogRef } from './edit-key-value-dialog'; import { useConfirmationDialog } from '@/components/confirmation-dialog/confirmation-dialog.provider'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { KeysFormDialog, VariablesFormDialogRef, } from '@/features/secret/form/keys/keys-form-dialog'; -import { showMutationErrorToast } from '@/modules/quota'; import { type Secret, useUpdateSecret } from '@/resources/secrets'; import { Button } from '@datum-cloud/datum-ui/button'; import { Card, CardAction, CardContent, CardHeader, CardTitle } from '@datum-cloud/datum-ui/card'; diff --git a/app/features/secret/form/keys/keys-form-dialog.tsx b/app/features/secret/form/keys/keys-form-dialog.tsx index 97e9a80ab..cd4a07f85 100644 --- a/app/features/secret/form/keys/keys-form-dialog.tsx +++ b/app/features/secret/form/keys/keys-form-dialog.tsx @@ -1,5 +1,5 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { KeyValueFieldArray } from '@/features/secret/form/key-value-field-array'; -import { showMutationErrorToast } from '@/modules/quota'; import type { SecretVariablesSchema } from '@/resources/secrets'; import { secretVariablesSchema, toSecretData, useUpdateSecret } from '@/resources/secrets'; import { Form } from '@datum-cloud/datum-ui/form'; diff --git a/app/features/secret/form/secret-form-dialog.tsx b/app/features/secret/form/secret-form-dialog.tsx index 4307d33ed..5e0bf9850 100644 --- a/app/features/secret/form/secret-form-dialog.tsx +++ b/app/features/secret/form/secret-form-dialog.tsx @@ -1,7 +1,7 @@ +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { InputName } from '@/components/input-name/input-name'; import { SECRET_TYPES } from '@/features/secret/constants'; import { KeyValueFieldArray } from '@/features/secret/form/key-value-field-array'; -import { showMutationErrorToast } from '@/modules/quota'; import { AnalyticsAction, useAnalytics } from '@/modules/rybbit'; import { type SecretCreateSchema, diff --git a/app/features/service-account/card/display-name-form-card.tsx b/app/features/service-account/card/display-name-form-card.tsx index aaaa53924..b03de3792 100644 --- a/app/features/service-account/card/display-name-form-card.tsx +++ b/app/features/service-account/card/display-name-form-card.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { serviceAccountUpdateSchema, useUpdateServiceAccount, diff --git a/app/features/service-account/form/service-account-form-dialog.tsx b/app/features/service-account/form/service-account-form-dialog.tsx index 77eb3b306..ce4b8c5da 100644 --- a/app/features/service-account/form/service-account-form-dialog.tsx +++ b/app/features/service-account/form/service-account-form-dialog.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { serviceAccountCreateSchema, serviceAccountUpdateSchema, diff --git a/app/features/service-account/form/service-account-key-form-dialog.tsx b/app/features/service-account/form/service-account-key-form-dialog.tsx index e4a17fb94..aa73e2db6 100644 --- a/app/features/service-account/form/service-account-key-form-dialog.tsx +++ b/app/features/service-account/form/service-account-key-form-dialog.tsx @@ -1,5 +1,5 @@ import { SingleDatePicker } from '@/components/date-picker/single-date-picker'; -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { serviceAccountKeyCreateSchema, useCreateServiceAccountKey, diff --git a/app/features/service-account/service-account-header-actions.tsx b/app/features/service-account/service-account-header-actions.tsx index b1617cb8c..3efe7895c 100644 --- a/app/features/service-account/service-account-header-actions.tsx +++ b/app/features/service-account/service-account-header-actions.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { PermissionButton } from '@/modules/rbac'; import { useUpdateServiceAccount, type ServiceAccount } from '@/resources/service-accounts'; import { Icon } from '@datum-cloud/datum-ui/icons'; diff --git a/app/modules/quota/index.ts b/app/modules/quota/index.ts index c3913c818..52efd625c 100644 --- a/app/modules/quota/index.ts +++ b/app/modules/quota/index.ts @@ -2,7 +2,6 @@ export * from './types'; export * from './derive-quota-verdict'; export * from './use-resource-quota'; export * from './quota-error'; -export * from './quota-toast'; export * from './components/QuotaGuard'; export * from './components/QuotaExhaustedAlert'; export * from './components/QuotaWatchBridge'; diff --git a/app/modules/rbac/client/rbac-api.test.ts b/app/modules/rbac/client/rbac-api.test.ts new file mode 100644 index 000000000..42a31e458 --- /dev/null +++ b/app/modules/rbac/client/rbac-api.test.ts @@ -0,0 +1,46 @@ +import { checkPermissionAPI, checkPermissionsBulkAPI } from './rbac-api'; +import { afterEach, describe, expect, test, vi } from 'vitest'; + +vi.mock('@/modules/rate-limit', () => ({ + gatedFetch: (input: RequestInfo | URL, init?: RequestInit) => fetch(input, init), +})); + +function respondWith(status: number, body: unknown) { + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.resolve(new Response(JSON.stringify(body), { status }))) + ); +} + +const check = { organizationId: 'org', resource: 'projects', verb: 'list', group: '' } as const; +const denial = { code: 'AUTHORIZATION_ERROR', message: 'nope', status: 403, requestId: 'r' }; + +describe('rbac api client', () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + test("a failed single check surfaces the server's message", async () => { + respondWith(403, denial); + + await expect(checkPermissionAPI(check)).rejects.toThrow('nope'); + }); + + test("a failed bulk check surfaces the server's message", async () => { + respondWith(403, denial); + + await expect(checkPermissionsBulkAPI('org', [check])).rejects.toThrow('nope'); + }); + + test('a failure with no message falls back to a generic one', async () => { + respondWith(500, {}); + + await expect(checkPermissionAPI(check)).rejects.toThrow('Permission check failed'); + }); + + test('a successful check returns its data', async () => { + respondWith(200, { success: true, data: { allowed: true } }); + + await expect(checkPermissionAPI(check)).resolves.toEqual({ allowed: true }); + }); +}); diff --git a/app/modules/rbac/client/rbac-api.ts b/app/modules/rbac/client/rbac-api.ts index c961a1a94..360902ea4 100644 --- a/app/modules/rbac/client/rbac-api.ts +++ b/app/modules/rbac/client/rbac-api.ts @@ -23,6 +23,17 @@ export interface BulkCheckResult extends IPermissionResult { }; } +/** Error body every `/api` route answers a failure with (a serialized `AppError`). */ +interface ApiErrorBody { + code?: string; + message?: string; +} + +async function readFailure(response: Response): Promise { + const body = (await response.json().catch(() => ({}))) as ApiErrorBody; + return new Error(body.message || 'Permission check failed'); +} + /** Single precise check (escape hatch — useAccessReview / usePermission). */ export async function checkPermissionAPI(check: CheckPermissionInput): Promise { const response = await gatedFetch('/api/permissions/check', { @@ -31,10 +42,10 @@ export async function checkPermissionAPI(check: CheckPermissionInput): Promise { if (isShuttingDown) return; isShuttingDown = true; setTimeout(() => { - console.warn('⚠️ Shutdown timeout reached with requests still in-flight'); + serverLogger.warn('Shutdown timeout reached with requests still in-flight'); shutdownObservability(); process.exit(0); }, SHUTDOWN_TIMEOUT_MS).unref(); @@ -86,7 +86,7 @@ const beginShutdown = () => { watchHub.shutdown(); // After the hub, so the relay waits for the ownership releases it just sent. watchRelay.stop().catch((error: unknown) => { - console.error('❌ Failed to stop the watch relay:', error); + serverLogger.error('Failed to stop the watch relay', error as Error); }); // Also closes the connections with no request in flight. httpServer?.close(() => { @@ -109,7 +109,7 @@ sessionManager.registerRefreshHook(({ userId, accessToken }) => { // No-ops unless WATCH_RELAY_ENABLED and Redis are set. watchHub.setOwnerRegistry(watchRelay); watchRelay.start().catch((error: unknown) => { - console.error('❌ Failed to start the watch relay:', error); + serverLogger.error('Failed to start the watch relay', error as Error); }); // Configure the shared control-plane client at startup. Called explicitly @@ -134,19 +134,19 @@ initPluginRegistry(); // Initialize observability (OTEL + Sentry + error handlers) initializeObservability().catch((error: unknown) => { - console.error('❌ Failed to initialize observability:', error); + serverLogger.error('Failed to initialize observability', error as Error); }); // Check Redis connection on startup (non-blocking) checkRedisHealth() .then((result) => { if (!result.available && result.error !== 'Redis not configured') { - console.warn('⚠️ Redis health check failed:', result.error); - console.warn('⚠️ Falling back to in-memory rate limiting'); + serverLogger.warn('Redis health check failed', { error: result.error }); + serverLogger.warn('Falling back to in-memory rate limiting'); } }) .catch((error: unknown) => { - console.error('❌ Unexpected error during Redis health check:', error); + serverLogger.error('Unexpected error during Redis health check', error as Error); }); const app = new Hono<{ Variables: Variables }>(); @@ -220,7 +220,7 @@ app.route('/api/plugins', createPluginRoutes()); if (isDevSessionEnabled()) { app.route('/api/auth', createDevSessionRoutes()); - console.info('[plugins] dev session exchange enabled at POST /api/auth/dev-session'); + serverLogger.info('[plugins] dev session exchange enabled at POST /api/auth/dev-session'); } // ============================================================================ diff --git a/app/server/middleware/error-handler.test.ts b/app/server/middleware/error-handler.test.ts index 44fd87f57..5f216e116 100644 --- a/app/server/middleware/error-handler.test.ts +++ b/app/server/middleware/error-handler.test.ts @@ -1,7 +1,17 @@ import { errorHandler } from './error-handler'; -import { AuthenticationError, NotFoundError } from '@/utils/errors/app-error'; +import { + AppError, + AuthenticationError, + NotFoundError, + ValidationError, +} from '@/utils/errors/app-error'; import { Hono } from 'hono'; -import { describe, expect, test } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const { logError, logWarn } = vi.hoisted(() => ({ logError: vi.fn(), logWarn: vi.fn() })); +vi.mock('@/modules/logger', () => ({ + logger: { error: logError, warn: logWarn, info: vi.fn(), debug: vi.fn() }, +})); /** * A 401 reaches this handler by three different routes, and the caller cannot @@ -83,3 +93,64 @@ describe('errorHandler auth challenge', () => { ); }); }); + +describe('errorHandler request ID', () => { + test("an AppError without a request ID gets the request's ID", async () => { + const app = new Hono<{ Variables: { requestId: string } }>(); + app.onError(errorHandler as never); + app.use('*', async (c, next) => { + c.set('requestId', 'req-1'); + await next(); + }); + app.get('/boom', () => { + throw new ValidationError('bad'); + }); + + const res = await app.request('/boom'); + + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ + code: 'VALIDATION_ERROR', + message: 'bad', + status: 400, + requestId: 'req-1', + }); + }); + + test('an AppError keeps a request ID of its own', async () => { + const res = await appThatThrows(new NotFoundError('Thing', 'x', 'own-id')).request('/boom'); + + expect(await res.json()).toMatchObject({ requestId: 'own-id' }); + }); +}); + +describe('errorHandler Sentry reporting', () => { + beforeEach(() => { + logError.mockClear(); + logWarn.mockClear(); + }); + + test('a 5xx that opted out of Sentry is logged at warn only', async () => { + const error = new AppError('gateway down', { + code: 'UPSTREAM_UNAVAILABLE', + status: 502, + captureToSentry: false, + }); + + const res = await appThatThrows(error).request('/boom'); + + expect(res.status).toBe(502); + expect(logError).not.toHaveBeenCalled(); + expect(logWarn).toHaveBeenCalledWith( + '[UPSTREAM_UNAVAILABLE] gateway down', + expect.objectContaining({ code: 'UPSTREAM_UNAVAILABLE' }) + ); + }); + + test('a plain 5xx AppError still reaches logger.error', async () => { + const res = await appThatThrows(new AppError('x', { status: 500 })).request('/boom'); + + expect(res.status).toBe(500); + expect(logError).toHaveBeenCalledTimes(1); + }); +}); diff --git a/app/server/middleware/error-handler.ts b/app/server/middleware/error-handler.ts index 08328749a..717f1b6d3 100644 --- a/app/server/middleware/error-handler.ts +++ b/app/server/middleware/error-handler.ts @@ -81,7 +81,12 @@ export const errorHandler: HonoErrorHandler<{ Variables: Variables }> = ( if (error instanceof AppError) { if (error.status >= 500) { - logger.error(`[${error.code}] ${error.message}`, error, { requestId }); + // logger.error reaches Sentry; an error that opted out is only logged. + if (error.reportToSentry) { + logger.error(`[${error.code}] ${error.message}`, error, { requestId }); + } else { + logger.warn(`[${error.code}] ${error.message}`, { requestId, code: error.code }); + } } if (error instanceof RateLimitError && error.retryAfter) { @@ -90,7 +95,10 @@ export const errorHandler: HonoErrorHandler<{ Variables: Variables }> = ( stageAuthChallenge(error.status); - return c.json(error.toJSON(), error.status as ContentfulStatusCode); + return c.json( + { ...error.toJSON(), requestId: error.requestId ?? requestId }, + error.status as ContentfulStatusCode + ); } if (isRouteErrorResponse(error)) { diff --git a/app/server/routes/api-error-shape.test.ts b/app/server/routes/api-error-shape.test.ts new file mode 100644 index 000000000..76debcb7d --- /dev/null +++ b/app/server/routes/api-error-shape.test.ts @@ -0,0 +1,267 @@ +import { errorHandler } from '@/server/middleware/error-handler'; +import type { WatchRouteDeps } from '@/server/routes/watch'; +import type { Variables } from '@/server/types'; +import { Hono } from 'hono'; +import { afterEach, describe, expect, test, vi } from 'vitest'; + +vi.mock('@/modules/axios/upstream-timeout', () => ({ UPSTREAM_TIMEOUT_MS: 30 })); +vi.mock('@/utils/env/env.server', async (importOriginal) => { + const actual = await importOriginal(); + return { + env: { + ...actual.env, + public: { ...actual.env.public, apiUrl: 'http://api.test', graphqlUrl: 'http://gql.test' }, + server: { ...actual.env.server, grafanaUrl: 'http://grafana.test' }, + }, + }; +}); +vi.mock('@/utils/auth', async (importOriginal) => ({ + ...(await importOriginal()), + AuthService: {}, +})); +vi.mock('@/modules/logger', () => ({ + logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }, +})); +vi.mock('@/server/watch', () => ({ watchHub: {}, watchRelay: {} })); +vi.mock('@/server/observability/watch-metrics', () => ({ countWatchSubscribe: vi.fn() })); +vi.mock('@/modules/billing/usage.server', () => ({ + loadOrgUsageDashboard: vi.fn(), + resolveUsageProjectSelection: vi.fn(), +})); +vi.mock('@/modules/entitlements/entitled-services.server', () => ({ + resolveEntitledServiceIds: vi.fn(), +})); +vi.mock('@/resources/projects', () => ({ createProjectService: vi.fn() })); +const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() })); +vi.mock('@/modules/rbac/server/rbac.service', () => ({ + RbacService: class { + checkPermission = checkPermission; + }, +})); + +const { proxyRoutes } = await import('./proxy'); +const { graphqlRoutes } = await import('./graphql'); +const { usageRoutes } = await import('./usage'); +const { permissionsRoutes } = await import('./permissions'); +const { userRoutes } = await import('./user'); +const { createWatchRoutes } = await import('./watch'); +const { grafanaRoutes } = await import('./grafana'); +const { authGuardMiddleware } = await import('@/server/middleware/auth'); + +type Session = Variables['session']; + +function fakeWatchDeps({ hasClient }: { hasClient: boolean }): WatchRouteDeps { + return { + hub: { + hasClient: () => hasClient, + isClientOwnedBy: () => false, + } as unknown as WatchRouteDeps['hub'], + relay: { + relaySubscribe: vi.fn(() => Promise.resolve({ kind: 'not_owner' as const })), + relayUnsubscribe: vi.fn(() => Promise.resolve({ kind: 'not_owner' as const })), + }, + }; +} + +function apiApp(session?: Session, watch = fakeWatchDeps({ hasClient: true })) { + const app = new Hono<{ Variables: Variables }>(); + app.onError(errorHandler); + app.use('*', async (c, next) => { + if (session) c.set('session', session); + c.set('requestId', 'req-1'); + await next(); + }); + app.route('/api/proxy', proxyRoutes); + app.route('/api/graphql', graphqlRoutes); + app.route('/api/permissions', permissionsRoutes); + app.route('/api/user', userRoutes); + app.route('/api/watch', createWatchRoutes(watch)); + app.route('/api/grafana', grafanaRoutes); + app.use('/api/usage', authGuardMiddleware()); + app.route('/api/usage', usageRoutes); + return app; +} + +const session = { sub: 'u1', accessToken: 't' } as Session; +const post = (body: unknown) => ({ + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), +}); +const subscribeBody = { + clientId: '00000000-0000-4000-8000-000000000000', + resourceType: 'apis/resourcemanager.miloapis.com/v1alpha1/projects', +}; + +function upstreamRefuses() { + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('connect ECONNREFUSED'))) + ); +} + +/** Every error body is the serialized AppError, nothing more. */ +async function expectErrorShape(res: Response, status: number, code: string) { + const body = (await res.json()) as Record; + expect(res.status).toBe(status); + expect(body).toMatchObject({ code, status, requestId: 'req-1' }); + expect(typeof body.message).toBe('string'); + const allowed = ['code', 'message', 'status', 'requestId', 'details']; + expect(Object.keys(body).filter((key) => !allowed.includes(key))).toEqual([]); + return body; +} + +describe('/api error shape', () => { + afterEach(() => { + vi.unstubAllGlobals(); + checkPermission.mockReset(); + }); + + test.each(['/api/proxy/x', '/api/graphql', '/api/graphql/org/acme'])( + 'a request with no session to %s is a 401 the client re-authenticates on', + async (path) => { + const res = await apiApp().request(path, post({})); + + const body = await expectErrorShape(res, 401, 'AUTHENTICATION_ERROR'); + expect(body.message).toBe('Unauthorized'); + } + ); + + test('the Grafana connection test without a session is a 401 and never calls Grafana', async () => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + + const res = await apiApp().request('/api/grafana/test-connection'); + + await expectErrorShape(res, 401, 'AUTHENTICATION_ERROR'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test('an unreachable Grafana keeps its 503 status payload', async () => { + upstreamRefuses(); + + const res = await apiApp(session).request('/api/grafana/test-connection'); + + expect(res.status).toBe(503); + expect(await res.json()).toEqual({ + configured: true, + connected: false, + error: 'Connection failed', + }); + }); + + test('usage with no session is a 401 the client re-authenticates on', async () => { + const res = await apiApp().request('/api/usage'); + + await expectErrorShape(res, 401, 'AUTHENTICATION_ERROR'); + }); + + test('the permission check without a session is a 401', async () => { + const res = await apiApp().request('/api/permissions/check', post({})); + + const body = await expectErrorShape(res, 401, 'AUTHENTICATION_ERROR'); + expect(body.message).toBe('Unauthorized'); + }); + + test('an invalid permission check is a 400 validation error', async () => { + const res = await apiApp(session).request('/api/permissions/check', post({})); + + const body = await expectErrorShape(res, 400, 'VALIDATION_ERROR'); + expect(body.message).toMatch(/^Invalid request: /); + }); + + test('an invalid bulk permission check is a 400 validation error', async () => { + const res = await apiApp(session).request('/api/permissions/bulk-check', post({})); + + await expectErrorShape(res, 400, 'VALIDATION_ERROR'); + }); + + test('a failing permission check is a 500 carrying the failure message', async () => { + checkPermission.mockRejectedValue(new Error('control plane down')); + const res = await apiApp(session).request( + '/api/permissions/check', + post({ organizationId: 'org', resource: 'projects', verb: 'list', group: '' }) + ); + + const body = await expectErrorShape(res, 500, 'INTERNAL_ERROR'); + expect(body.message).toBe('control plane down'); + }); + + test('a graphql request with an unknown scope is a 400 validation error', async () => { + const res = await apiApp(session).request('/api/graphql/galaxy/far-away', post({})); + + await expectErrorShape(res, 400, 'VALIDATION_ERROR'); + }); + + test('an unreachable graphql gateway is a 502', async () => { + upstreamRefuses(); + + const res = await apiApp(session).request('/api/graphql', post({ query: '{ a }' })); + + const body = await expectErrorShape(res, 502, 'UPSTREAM_UNAVAILABLE'); + expect(body.message).toBe('connect ECONNREFUSED'); + }); + + test('an unreachable API server is a 502', async () => { + upstreamRefuses(); + + const res = await apiApp(session).request('/api/proxy/apis/example/v1/things'); + + await expectErrorShape(res, 502, 'UPSTREAM_UNAVAILABLE'); + }); + + test('usage without an org is a 400 validation error', async () => { + const res = await apiApp(session).request('/api/usage'); + + const body = await expectErrorShape(res, 400, 'VALIDATION_ERROR'); + expect(body.message).toBe('orgId must be an organization name'); + }); + + test('usage in project scope without a project is a 400 validation error', async () => { + const res = await apiApp(session).request('/api/usage?orgId=acme&scope=project'); + + await expectErrorShape(res, 400, 'VALIDATION_ERROR'); + }); + + test('a user update with a forged CSRF token keeps its 403 and message', async () => { + const res = await apiApp(session).request('/api/user', { + ...post({ csrf: 'forged' }), + method: 'PATCH', + }); + + const body = await expectErrorShape(res, 403, 'AUTHORIZATION_ERROR'); + expect(body.message).toMatch(/CSRF/); + }); + + test('watch subscribe to a stream another user holds is a 403', async () => { + const res = await apiApp(session, fakeWatchDeps({ hasClient: true })).request( + '/api/watch/subscribe', + post(subscribeBody) + ); + + const body = await expectErrorShape(res, 403, 'AUTHORIZATION_ERROR'); + expect(body.message).toBe('Client not owned by this user'); + }); + + test('watch subscribe to a stream no pod owns is a 409', async () => { + const res = await apiApp(session, fakeWatchDeps({ hasClient: false })).request( + '/api/watch/subscribe', + post(subscribeBody) + ); + + const body = await expectErrorShape(res, 409, 'CONFLICT'); + expect(body.message).toBe('not-owner'); + }); + + test('watch unsubscribe with a bad body is a 400 validation error', async () => { + const res = await apiApp(session).request('/api/watch/unsubscribe', post({})); + + await expectErrorShape(res, 400, 'VALIDATION_ERROR'); + }); + + test('a watch stream with no client ID is a 400 validation error', async () => { + const res = await apiApp(session).request('/api/watch/stream'); + + await expectErrorShape(res, 400, 'VALIDATION_ERROR'); + }); +}); diff --git a/app/server/routes/grafana.ts b/app/server/routes/grafana.ts index 0af407183..b620d745c 100644 --- a/app/server/routes/grafana.ts +++ b/app/server/routes/grafana.ts @@ -1,17 +1,20 @@ // app/server/routes/grafana.ts import type { Variables } from '../types'; +import { logger } from '@/modules/logger'; import { env } from '@/utils/env/env.server'; +import { AuthenticationError } from '@/utils/errors/app-error'; import { Hono } from 'hono'; const grafana = new Hono<{ Variables: Variables }>(); grafana.get('/test-connection', async (c) => { - try { - const session = c.get('session'); - if (!session?.accessToken) { - return c.json({ error: 'Unauthorized' }, 401); - } + // Outside the try: its catch reports any failure as a Grafana outage. + const session = c.get('session'); + if (!session?.accessToken) { + throw new AuthenticationError('Unauthorized'); + } + try { const grafanaUrl = env.server.grafanaUrl; if (!grafanaUrl) { return c.json({ configured: false }); @@ -27,10 +30,7 @@ grafana.get('/test-connection', async (c) => { status: response.status, }); } catch (error) { - console.error( - 'Grafana connection error:', - error instanceof Error ? error.message : 'Unknown error' - ); + logger.error('Grafana connection error', error as Error, { requestId: c.get('requestId') }); return c.json({ configured: true, connected: false, error: 'Connection failed' }, 503); } }); diff --git a/app/server/routes/graphql.ts b/app/server/routes/graphql.ts index 662c9a5ce..544a5bb9d 100644 --- a/app/server/routes/graphql.ts +++ b/app/server/routes/graphql.ts @@ -1,10 +1,12 @@ // app/server/routes/graphql.ts -import { isUpstreamTimeout, UPSTREAM_TIMEOUT_BODY, upstreamSignal } from './upstream-deadline'; +import { isUpstreamTimeout, UpstreamTimeoutError, upstreamSignal } from './upstream-deadline'; import { parseScope, buildScopedEndpoint } from '@/modules/graphql/endpoints'; +import { logger } from '@/modules/logger'; import type { Variables } from '@/server/types'; import { AuthService } from '@/utils/auth'; import type { IAccessTokenSession } from '@/utils/auth/auth.types'; import { env } from '@/utils/env/env.server'; +import { AppError, AuthenticationError, ValidationError } from '@/utils/errors/app-error'; import { appendSetCookieHeaders } from '@/utils/fraud/user-access'; import { type Context, Hono } from 'hono'; @@ -20,7 +22,7 @@ graphqlRoutes.all('/:scopeType/:scopeId', async (c) => { const session = c.get('session'); if (!session) { - return c.json({ error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } try { @@ -36,16 +38,21 @@ graphqlRoutes.all('/:scopeType/:scopeId', async (c) => { return new Response(null, { status: 499 }); } if (error.message.includes('Unknown scope type')) { - return c.json({ error: error.message }, 400); + throw new ValidationError(error.message); } } if (isUpstreamTimeout(error)) { - console.error('[graphql-proxy] Upstream timed out'); - return c.json(UPSTREAM_TIMEOUT_BODY, 504); + logger.warn('[graphql-proxy] Upstream timed out', { requestId: c.get('requestId') }); + throw new UpstreamTimeoutError(); } - console.error('[graphql-proxy] Error:', error); - return c.json({ error: error instanceof Error ? error.message : 'Proxy error' }, 502); + logger.warn('[graphql-proxy] Error', { error: String(error), requestId: c.get('requestId') }); + throw new AppError(error instanceof Error ? error.message : 'Proxy error', { + code: 'UPSTREAM_UNAVAILABLE', + status: 502, + cause: error, + captureToSentry: false, + }); } }); @@ -54,7 +61,7 @@ graphqlRoutes.all('/', async (c) => { const session = c.get('session'); if (!session) { - return c.json({ error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } try { @@ -66,12 +73,17 @@ graphqlRoutes.all('/', async (c) => { return new Response(null, { status: 499 }); } if (isUpstreamTimeout(error)) { - console.error('[graphql-proxy] Upstream timed out'); - return c.json(UPSTREAM_TIMEOUT_BODY, 504); + logger.warn('[graphql-proxy] Upstream timed out', { requestId: c.get('requestId') }); + throw new UpstreamTimeoutError(); } - console.error('[graphql-proxy] Error:', error); - return c.json({ error: error instanceof Error ? error.message : 'Proxy error' }, 502); + logger.warn('[graphql-proxy] Error', { error: String(error), requestId: c.get('requestId') }); + throw new AppError(error instanceof Error ? error.message : 'Proxy error', { + code: 'UPSTREAM_UNAVAILABLE', + status: 502, + cause: error, + captureToSentry: false, + }); } }); diff --git a/app/server/routes/permissions.ts b/app/server/routes/permissions.ts index 949d89589..dfebedcd5 100644 --- a/app/server/routes/permissions.ts +++ b/app/server/routes/permissions.ts @@ -3,6 +3,7 @@ import type { Variables } from '../types'; import { logger } from '@/modules/logger'; import { RbacService } from '@/modules/rbac/server/rbac.service'; import { BulkPermissionCheckSchema, PermissionCheckSchema } from '@/modules/rbac/types'; +import { AppError, AuthenticationError, ValidationError } from '@/utils/errors/app-error'; import { Hono } from 'hono'; const permissions = new Hono<{ Variables: Variables }>(); @@ -12,18 +13,14 @@ permissions.post('/check', async (c) => { try { const session = c.get('session'); if (!session?.accessToken || !session?.sub) { - return c.json({ success: false, error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } const body = await c.req.json(); const parsed = PermissionCheckSchema.safeParse(body); if (!parsed.success) { - return c.json( - { - success: false, - error: `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}`, - }, - 400 + throw new ValidationError( + `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}` ); } @@ -50,9 +47,13 @@ permissions.post('/check', async (c) => { }); return c.json({ success: true, data: result }, 200); } catch (error) { - logger.error('[permissions] unexpected error in POST /check', error as Error); + if (error instanceof AppError) throw error; + logger.warn('[permissions] unexpected error in POST /check', { + error: String(error), + requestId: c.get('requestId'), + }); const message = error instanceof Error ? error.message : 'Failed to check permission'; - return c.json({ success: false, error: message }, 500); + throw new AppError(message, { status: 500, cause: error, captureToSentry: false }); } }); @@ -61,18 +62,14 @@ permissions.post('/bulk-check', async (c) => { try { const session = c.get('session'); if (!session?.accessToken || !session?.sub) { - return c.json({ success: false, error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } const body = await c.req.json(); const parsed = BulkPermissionCheckSchema.safeParse(body); if (!parsed.success) { - return c.json( - { - success: false, - error: `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}`, - }, - 400 + throw new ValidationError( + `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}` ); } @@ -80,9 +77,13 @@ permissions.post('/bulk-check', async (c) => { const results = await new RbacService().checkPermissions(organizationId, checks); return c.json({ success: true, data: { results } }, 200); } catch (error) { - logger.error('[permissions] unexpected error in POST /bulk-check', error as Error); + if (error instanceof AppError) throw error; + logger.warn('[permissions] unexpected error in POST /bulk-check', { + error: String(error), + requestId: c.get('requestId'), + }); const message = error instanceof Error ? error.message : 'Failed to check permissions'; - return c.json({ success: false, error: message }, 500); + throw new AppError(message, { status: 500, cause: error, captureToSentry: false }); } }); diff --git a/app/server/routes/proxy.ts b/app/server/routes/proxy.ts index b19d48550..46782ca3a 100644 --- a/app/server/routes/proxy.ts +++ b/app/server/routes/proxy.ts @@ -1,7 +1,7 @@ import { isUpstreamTimeout, reportDeadlineCutoff, - UPSTREAM_TIMEOUT_BODY, + UpstreamTimeoutError, upstreamSignal, } from './upstream-deadline'; import { isEmailNotVerifiedDenial } from '@/features/account/email-verification/email-verification-error'; @@ -11,6 +11,7 @@ import { extractQuotaDenialLabels, quotaDeniedTotal } from '@/server/observabili import type { Variables } from '@/server/types'; import { AuthService } from '@/utils/auth'; import { env } from '@/utils/env/env.server'; +import { AppError, AuthenticationError } from '@/utils/errors/app-error'; import { Hono } from 'hono'; /** @@ -27,7 +28,7 @@ proxyRoutes.all('/*', async (c) => { const isWatch = url.searchParams.get('watch') === 'true'; if (!session) { - return c.json({ error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } // Replace /users/me/ with actual user ID from session @@ -157,12 +158,21 @@ proxyRoutes.all('/*', async (c) => { } if (isUpstreamTimeout(error)) { - console.error('[proxy] Upstream timed out:', c.req.method, path); - return c.json(UPSTREAM_TIMEOUT_BODY, 504); + logger.warn('[proxy] Upstream timed out', { + method: c.req.method, + path, + requestId: c.get('requestId'), + }); + throw new UpstreamTimeoutError(); } - console.error('[proxy] Error:', isWatch ? '(watch)' : '', error); - return c.json({ error: error instanceof Error ? error.message : 'Proxy error' }, 502); + logger.warn('[proxy] Error', { error: String(error), isWatch, requestId: c.get('requestId') }); + throw new AppError(error instanceof Error ? error.message : 'Proxy error', { + code: 'UPSTREAM_UNAVAILABLE', + status: 502, + cause: error, + captureToSentry: false, + }); } }); diff --git a/app/server/routes/upstream-deadline.test.ts b/app/server/routes/upstream-deadline.test.ts index 475434cf6..3466f6b7c 100644 --- a/app/server/routes/upstream-deadline.test.ts +++ b/app/server/routes/upstream-deadline.test.ts @@ -3,23 +3,31 @@ import { Hono } from 'hono'; import { afterEach, beforeEach, describe, expect, type MockInstance, test, vi } from 'vitest'; const TEST_TIMEOUT_MS = 30; +const TIMEOUT_BODY = { + code: 'UPSTREAM_TIMEOUT', + message: 'Upstream request timed out', + status: 504, + requestId: 'req-1', +}; vi.mock('@/modules/axios/upstream-timeout', () => ({ UPSTREAM_TIMEOUT_MS: 30 })); vi.mock('@/utils/env/env.server', () => ({ env: { public: { apiUrl: 'http://api.test', graphqlUrl: 'http://gql.test' } }, })); vi.mock('@/utils/auth', () => ({ AuthService: {} })); -const { warn } = vi.hoisted(() => ({ warn: vi.fn() })); +const { warn, error: logError } = vi.hoisted(() => ({ warn: vi.fn(), error: vi.fn() })); vi.mock('@/modules/logger', () => ({ - logger: { warn, error: vi.fn(), info: vi.fn(), debug: vi.fn() }, + logger: { warn, error: logError, info: vi.fn(), debug: vi.fn() }, })); const { proxyRoutes } = await import('./proxy'); const { graphqlRoutes } = await import('./graphql'); const { reportDeadlineCutoff } = await import('./upstream-deadline'); +const { errorHandler } = await import('@/server/middleware/error-handler'); function appWithSession() { const app = new Hono<{ Variables: Variables }>(); + app.onError(errorHandler); app.use('*', async (c, next) => { c.set('session', { sub: 'u1', accessToken: 't' } as Variables['session']); c.set('requestId', 'req-1'); @@ -55,14 +63,14 @@ describe('upstream deadline', () => { vi.unstubAllGlobals(); }); - test('a hung API server is a 504 with the proxy error shape', async () => { + test('a hung API server is a 504 with the AppError shape', async () => { const fetchMock = hangingFetch(); vi.stubGlobal('fetch', fetchMock); const res = await appWithSession().request('/api/proxy/apis/example/v1/things'); expect(res.status).toBe(504); - expect(await res.json()).toEqual({ error: 'Upstream request timed out' }); + expect(await res.json()).toEqual(TIMEOUT_BODY); expect(fetchMock).toHaveBeenCalledTimes(1); }); @@ -74,10 +82,41 @@ describe('upstream deadline', () => { const scoped = await appWithSession().request('/api/graphql/org/acme', init); expect(global.status).toBe(504); - expect(await global.json()).toEqual({ error: 'Upstream request timed out' }); + expect(await global.json()).toEqual(TIMEOUT_BODY); expect(scoped.status).toBe(504); }); + test('a hung GraphQL gateway logs the timeout with the request ID', async () => { + warn.mockClear(); + vi.stubGlobal('fetch', hangingFetch()); + const init = { method: 'POST', body: JSON.stringify({ query: '{ __typename }' }) }; + + await appWithSession().request('/api/graphql', init); + + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('timed out'), + expect.objectContaining({ requestId: 'req-1' }) + ); + }); + + test('a timeout is logged at warn and never reaches Sentry', async () => { + logError.mockClear(); + warn.mockClear(); + vi.stubGlobal('fetch', hangingFetch()); + + await appWithSession().request('/api/proxy/apis/example/v1/things'); + + expect(logError).not.toHaveBeenCalled(); + const handlerWarns = warn.mock.calls.filter(([message]) => + String(message).includes('UPSTREAM_TIMEOUT') + ); + expect(handlerWarns).toHaveLength(1); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('UPSTREAM_TIMEOUT'), + expect.objectContaining({ requestId: 'req-1', code: 'UPSTREAM_TIMEOUT' }) + ); + }); + test('a client disconnect is still a 499, not a timeout', async () => { vi.stubGlobal('fetch', hangingFetch()); const client = new AbortController(); diff --git a/app/server/routes/upstream-deadline.ts b/app/server/routes/upstream-deadline.ts index 9e7aa16f0..624b0cb3c 100644 --- a/app/server/routes/upstream-deadline.ts +++ b/app/server/routes/upstream-deadline.ts @@ -1,4 +1,5 @@ import { UPSTREAM_TIMEOUT_MS } from '@/modules/axios/upstream-timeout'; +import { AppError } from '@/utils/errors/app-error'; /** * Signal for an upstream `fetch`: aborts when the browser disconnects and, @@ -49,5 +50,14 @@ export function reportDeadlineCutoff( ); } -/** Body of the 504 the proxies answer with when the upstream deadline fires. */ -export const UPSTREAM_TIMEOUT_BODY = { error: 'Upstream request timed out' } as const; +/** The 504 the proxies answer with when the upstream deadline fires. */ +export class UpstreamTimeoutError extends AppError { + constructor() { + super('Upstream request timed out', { + code: 'UPSTREAM_TIMEOUT', + status: 504, + captureToSentry: false, + }); + this.name = 'UpstreamTimeoutError'; + } +} diff --git a/app/server/routes/usage.ts b/app/server/routes/usage.ts index 42e460c57..cec933e90 100644 --- a/app/server/routes/usage.ts +++ b/app/server/routes/usage.ts @@ -6,6 +6,7 @@ import { } from '@/modules/billing/usage.server'; import { resolveEntitledServiceIds } from '@/modules/entitlements/entitled-services.server'; import { createProjectService } from '@/resources/projects'; +import { ValidationError } from '@/utils/errors/app-error'; import { isResourceName } from '@/utils/helpers/validation.helper'; import { Hono } from 'hono'; @@ -23,7 +24,7 @@ usage.get('/', async (c) => { // not a plain resource name (e.g. `x/../..`) is rejected outright. const orgId = c.req.query('orgId'); if (!orgId || !isResourceName(orgId)) { - return c.json({ message: 'orgId must be an organization name' }, 400); + throw new ValidationError('orgId must be an organization name'); } const projectParam = c.req.query('project'); @@ -35,7 +36,7 @@ usage.get('/', async (c) => { let projectNames: string[] = []; if (isProjectScope) { if (!projectParam || projectParam === 'all' || !isResourceName(projectParam)) { - return c.json({ message: 'project must be a project name for project scope' }, 400); + throw new ValidationError('project must be a project name for project scope'); } selectedProject = projectParam; } else { diff --git a/app/server/routes/user.test.ts b/app/server/routes/user.test.ts index 0d4711e27..760b10fbe 100644 --- a/app/server/routes/user.test.ts +++ b/app/server/routes/user.test.ts @@ -1,3 +1,4 @@ +import { errorHandler } from '@/server/middleware/error-handler'; import type { Variables } from '@/server/types'; import { csrf } from '@/utils/cookies'; import { Hono } from 'hono'; @@ -16,6 +17,7 @@ const { userRoutes } = await import('./user'); function appWithSession() { const app = new Hono<{ Variables: Variables }>(); + app.onError(errorHandler); app.use('*', async (c, next) => { c.set('session', { sub: 'u1' } as Variables['session']); await next(); diff --git a/app/server/routes/user.ts b/app/server/routes/user.ts index c71328d11..b20bc3040 100644 --- a/app/server/routes/user.ts +++ b/app/server/routes/user.ts @@ -3,6 +3,7 @@ import type { Variables } from '../types'; import { createUserService, userSchema, userPreferencesSchema } from '@/resources/users'; import { paths } from '@/utils/config/paths.config'; import { validateCSRF } from '@/utils/cookies'; +import { AppError, ValidationError } from '@/utils/errors/app-error'; import { Hono } from 'hono'; import type { ContentfulStatusCode } from 'hono/utils/http-status'; @@ -17,6 +18,32 @@ function errorStatus(error: any): ContentfulStatusCode { return error?.status || error?.statusCode || 500; } +/** Codes the shared error classes use, for errors that arrive without one. */ +const CODE_BY_STATUS: Partial> = { + 400: 'VALIDATION_ERROR', + 401: 'AUTHENTICATION_ERROR', + 403: 'AUTHORIZATION_ERROR', + 404: 'NOT_FOUND', + 409: 'CONFLICT', + 429: 'RATE_LIMIT_EXCEEDED', +}; + +/** + * The error a failed request answers with, keeping its status and message. + * Errors that are not an `AppError` (such as `HttpError`, which a failed CSRF + * check throws) are wrapped so the global handler serializes them too. + */ +function toAppError(error: unknown): AppError { + if (error instanceof AppError) return error; + const status = errorStatus(error); + return new AppError(error instanceof Error ? error.message : 'Request failed', { + code: CODE_BY_STATUS[status] ?? 'INTERNAL_ERROR', + status, + cause: error, + captureToSentry: false, + }); +} + /** Checks the `csrf` field of a JSON body against the CSRF cookie; 403 when it does not match. */ async function validatePayloadCSRF(payload: { csrf?: unknown }, headers: Headers) { const formData = new FormData(); @@ -39,7 +66,7 @@ user.get('/', async (c) => { return c.json({ success: true, data: userData }); } catch (error: any) { - return c.json({ success: false, error: error.message }, errorStatus(error)); + throw toAppError(error); } }); @@ -58,7 +85,7 @@ user.patch('/', async (c) => { const parsed = userSchema.safeParse(payload); if (!parsed.success) { - return c.json({ success: false, error: 'Invalid form data' }, 400); + throw new ValidationError('Invalid form data'); } const userService = createUserService(); @@ -66,7 +93,7 @@ user.patch('/', async (c) => { return c.json({ success: true, data: res }); } catch (error: any) { - return c.json({ success: false, error: error.message }, errorStatus(error)); + throw toAppError(error); } }); @@ -89,7 +116,7 @@ user.delete('/', async (c) => { return c.redirect(paths.auth.logOut); } catch (error: any) { - return c.json({ success: false, error: error.message }, errorStatus(error)); + throw toAppError(error); } }); @@ -108,7 +135,7 @@ user.patch('/preferences', async (c) => { const parsed = userPreferencesSchema.safeParse(payload); if (!parsed.success) { - return c.json({ success: false, error: 'Invalid form data' }, 400); + throw new ValidationError('Invalid form data'); } const userService = createUserService(); @@ -116,7 +143,7 @@ user.patch('/preferences', async (c) => { return c.json({ success: true, data: res }); } catch (error: any) { - return c.json({ success: false, error: error.message }, errorStatus(error)); + throw toAppError(error); } }); diff --git a/app/server/routes/watch.ts b/app/server/routes/watch.ts index 1004dc6f9..3fd85268f 100644 --- a/app/server/routes/watch.ts +++ b/app/server/routes/watch.ts @@ -27,6 +27,12 @@ import { watchUnsubscribeSchema, } from '@/server/watch/watch-hub.types'; import type { RelayResult, WatchRelay } from '@/server/watch/watch-relay'; +import { + AuthenticationError, + AuthorizationError, + ConflictError, + ValidationError, +} from '@/utils/errors/app-error'; import type { Context } from 'hono'; import { Hono } from 'hono'; import { streamSSE } from 'hono/streaming'; @@ -41,9 +47,9 @@ function relayResponse(c: Context<{ Variables: Variables }>, result: RelayResult case 'relayed': return c.json({ channel: result.channel, relayed: true }, 202); case 'forbidden': - return c.json({ error: 'Client not owned by this user' }, 403); + throw new AuthorizationError('Client not owned by this user'); case 'not_owner': - return c.json({ error: 'not-owner' }, 409); + throw new ConflictError('not-owner'); } } @@ -58,17 +64,17 @@ export function createWatchRoutes({ hub: watchHub, relay }: WatchRouteDeps) { watchRoutes.get('/stream', (c) => { const clientId = c.req.query('cid'); if (!clientId || !clientIdSchema.safeParse(clientId).success) { - return c.json({ error: 'Missing or invalid cid query parameter' }, 400); + throw new ValidationError('Missing or invalid cid query parameter'); } const session = c.get('session'); if (!session) { - return c.json({ error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } // Another user's stream with this ID stays put; only a guessed or copied ID lands here. if (watchHub.hasClient(clientId) && !watchHub.isClientOwnedBy(clientId, session.sub)) { - return c.json({ error: 'Client ID in use' }, 409); + throw new ConflictError('Client ID in use'); } return streamSSE(c, async (stream) => { @@ -117,7 +123,7 @@ export function createWatchRoutes({ hub: watchHub, relay }: WatchRouteDeps) { watchRoutes.post('/subscribe', async (c) => { const session = c.get('session'); if (!session) { - return c.json({ error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } let body: unknown; @@ -125,15 +131,14 @@ export function createWatchRoutes({ hub: watchHub, relay }: WatchRouteDeps) { body = await c.req.json(); } catch { countWatchSubscribe('invalid'); - return c.json({ error: 'Invalid JSON body' }, 400); + throw new ValidationError('Invalid JSON body'); } const parsed = watchSubscribeSchema.safeParse(body); if (!parsed.success) { countWatchSubscribe('invalid'); - return c.json( - { error: `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}` }, - 400 + throw new ValidationError( + `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}` ); } @@ -142,7 +147,7 @@ export function createWatchRoutes({ hub: watchHub, relay }: WatchRouteDeps) { if (!watchHub.isClientOwnedBy(req.clientId, session.sub)) { if (watchHub.hasClient(req.clientId)) { countWatchSubscribe('forbidden'); - return c.json({ error: 'Client not owned by this user' }, 403); + throw new AuthorizationError('Client not owned by this user'); } // Tokens never cross Redis, so the owner keeps its stream's token; on // expiry a 401 triggers an `auth` resync and the client reopens. @@ -160,7 +165,7 @@ export function createWatchRoutes({ hub: watchHub, relay }: WatchRouteDeps) { return c.json({ channel }); } catch (err) { countWatchSubscribe('invalid'); - return c.json({ error: (err as Error).message }, 400); + throw new ValidationError((err as Error).message); } }); @@ -172,21 +177,20 @@ export function createWatchRoutes({ hub: watchHub, relay }: WatchRouteDeps) { watchRoutes.post('/unsubscribe', async (c) => { const session = c.get('session'); if (!session) { - return c.json({ error: 'Unauthorized' }, 401); + throw new AuthenticationError('Unauthorized'); } let body: unknown; try { body = await c.req.json(); } catch { - return c.json({ error: 'Invalid JSON body' }, 400); + throw new ValidationError('Invalid JSON body'); } const parsed = watchUnsubscribeSchema.safeParse(body); if (!parsed.success) { - return c.json( - { error: `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}` }, - 400 + throw new ValidationError( + `Invalid request: ${parsed.error.issues.map((e) => e.message).join(', ')}` ); } @@ -194,7 +198,7 @@ export function createWatchRoutes({ hub: watchHub, relay }: WatchRouteDeps) { if (!watchHub.isClientOwnedBy(req.clientId, session.sub)) { if (watchHub.hasClient(req.clientId)) { - return c.json({ error: 'Client not owned by this user' }, 403); + throw new AuthorizationError('Client not owned by this user'); } return relayResponse(c, await relay.relayUnsubscribe(req.clientId, req.channel, session.sub)); } diff --git a/app/server/routes/website/logout.ts b/app/server/routes/website/logout.ts index 4460cc016..bf21eb61e 100644 --- a/app/server/routes/website/logout.ts +++ b/app/server/routes/website/logout.ts @@ -1,4 +1,5 @@ import { zitadelIssuer } from '@/modules/auth/strategies/zitadel.server'; +import { logger } from '@/modules/logger'; import { rateLimiter } from '@/server/middleware/rate-limit'; import type { Variables } from '@/server/types'; import { AuthService, destroyAllAuthCookies } from '@/utils/auth'; @@ -71,7 +72,9 @@ export function createWebsiteLogoutRoute(options: WebsiteLogoutRouteOptions = {} // No idToken means no RP-initiated logout; local cookies still go. return clearCookiesAndRedirect(request, endSessionUrl ?? fallbackUrl); } catch (error) { - console.error('[Auth] Error during website sign out process:', error); + logger.error('[Auth] Error during website sign out process', error as Error, { + requestId: c.get('requestId'), + }); return clearCookiesAndRedirect(request, fallbackUrl); } }); diff --git a/app/utils/errors/app-error.ts b/app/utils/errors/app-error.ts index 4e4d21d37..83d9972d2 100644 --- a/app/utils/errors/app-error.ts +++ b/app/utils/errors/app-error.ts @@ -64,6 +64,12 @@ export class AppError extends Error { * describes how this error is presented to the caller (502). */ public readonly upstreamStatus?: number; + /** + * Whether this error belongs in Sentry: `captureToSentry` when given, else + * any 5xx. The global handler reads it so a 5xx that opted out is logged + * without reaching Sentry. + */ + public readonly reportToSentry: boolean; constructor( message: string, @@ -108,6 +114,7 @@ export class AppError extends Error { this.k8sDetails = options.k8sDetails; this.upstreamStatus = options.upstreamStatus; this.sentryEventId = options.sentryEventId; + this.reportToSentry = options.captureToSentry ?? status >= 500; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); diff --git a/cypress/component/mutation-error-toast.cy.tsx b/cypress/component/mutation-error-toast.cy.tsx index 6eecd7833..f87378b73 100644 --- a/cypress/component/mutation-error-toast.cy.tsx +++ b/cypress/component/mutation-error-toast.cy.tsx @@ -1,4 +1,4 @@ -import { showMutationErrorToast } from '@/modules/quota/quota-toast'; +import { showMutationErrorToast } from '@/components/error/mutation-error-toast'; import { AppError } from '@/utils/errors/app-error'; import { PERMISSION_DENIED_MESSAGE } from '@/utils/errors/authorization-message'; import { rbacDenial } from '@/utils/errors/rbac-denial.fixture';