From dcf819146b9791922d446d49b1dea27d52887ee4 Mon Sep 17 00:00:00 2001 From: Runway Date: Wed, 21 Oct 2026 11:34:34 -0600 Subject: [PATCH] Runway 1.0.0 --- .gitignore | 33 + .mvn/jvm.config | 1 + CHANGELOG.md | 22 + LICENSE | 661 ++++ LICENSE-EXCEPTION | 44 + README.md | 149 + THIRD-PARTY-NOTICES | 2579 +++++++++++++++ docs/ADMINISTRATION.md | 2786 +++++++++++++++++ docs/CONFIGURATION-AND-DATA-STABILITY.md | 633 ++++ docs/GLOSSARY.md | 127 + docs/KNOWN-LIMITATIONS.md | 160 + docs/OPERATIONS.md | 1002 ++++++ docs/PLUGIN-DEVELOPMENT.md | 1323 ++++++++ docs/README.md | 34 + docs/SETTINGS-REFERENCE.md | 278 ++ docs/SITE-MANAGER-GUIDE.md | 1409 +++++++++ docs/SPI-STABILITY.md | 244 ++ frontend/codemirror/.gitignore | 1 + frontend/codemirror/build.sh | 12 + frontend/codemirror/codemirror.css | 5 + frontend/codemirror/entry.mjs | 76 + frontend/codemirror/package-lock.json | 753 +++++ frontend/codemirror/package.json | 25 + monitoring/README.md | 222 ++ monitoring/runway-grafana-dashboard.json | 141 + monitoring/runway-prometheus-alerts.yml | 80 + plugins/README.md | 53 + plugins/demo/.gitignore | 6 + plugins/demo/CHANGELOG.md | 9 + plugins/demo/LICENSE | 202 ++ plugins/demo/NOTICE | 6 + plugins/demo/README.md | 84 + plugins/demo/docs/DEMO-PLUGIN.md | 431 +++ plugins/demo/docs/PLUGIN-AUTHORING-GUIDE.md | 9 + plugins/demo/i18n/messages.properties | 118 + plugins/demo/i18n/messages_es.properties | 108 + plugins/demo/plugin.yml | 74 + plugins/demo/pom.xml | 184 ++ plugins/demo/scripts/install-into.sh | 21 + plugins/demo/scripts/verify-against-host.sh | 269 ++ .../main/java/mx/quest/demo/DemoActivity.java | 137 + .../java/mx/quest/demo/DemoAdminModel.java | 98 + .../java/mx/quest/demo/DemoAnalyticsHead.java | 76 + .../main/java/mx/quest/demo/DemoAppProps.java | 112 + .../mx/quest/demo/DemoConsoleController.java | 309 ++ .../java/mx/quest/demo/DemoEndpoints.java | 233 ++ .../mx/quest/demo/DemoFeedbackWidget.java | 98 + .../java/mx/quest/demo/DemoLifecycle.java | 44 + .../mx/quest/demo/DemoMetaLengthCheck.java | 70 + .../java/mx/quest/demo/DemoNotesStore.java | 168 + .../java/mx/quest/demo/DemoNoticeWidget.java | 76 + .../java/mx/quest/demo/DemoPluginConfig.java | 139 + .../mx/quest/demo/DemoShowcaseSource.java | 134 + .../java/mx/quest/demo/DemoShowcaseStore.java | 179 ++ .../src/main/java/mx/quest/demo/Html.java | 23 + .../src/main/java/mx/quest/demo/Note.java | 25 + .../main/java/mx/quest/demo/NotesFile.java | 20 + .../src/main/java/mx/quest/demo/Showcase.java | 20 + .../java/mx/quest/demo/DemoActivityTest.java | 133 + .../quest/demo/DemoConsoleControllerTest.java | 239 ++ .../mx/quest/demo/DemoNotesStoreTest.java | 134 + .../mx/quest/demo/DemoPluginConfigTest.java | 369 +++ .../java/mx/quest/demo/DemoShowcaseTest.java | 202 ++ .../java/mx/quest/demo/DemoSpiUnitTest.java | 352 +++ .../java/mx/quest/demo/DemoTemplatesTest.java | 120 + plugins/demo/static/css/demo.css | 59 + plugins/demo/static/js/demo-analytics.js | 13 + plugins/demo/static/notes-help.html | 51 + plugins/demo/templates/admin.html | 17 + plugins/demo/templates/admin.th.xml | 17 + plugins/demo/templates/console.html | 194 ++ plugins/demo/templates/console.th.xml | 108 + plugins/demo/templates/dashboard.html | 9 + plugins/demo/templates/dashboard.th.xml | 12 + plugins/demo/templates/showcase.html | 22 + plugins/demo/templates/showcase.th.xml | 16 + plugins/docs/PLUGIN-AUTHORING-GUIDE.md | 721 +++++ plugins/lucene-provider/CHANGELOG.md | 10 + plugins/lucene-provider/LICENSE | 661 ++++ plugins/lucene-provider/LICENSE-EXCEPTION | 44 + plugins/lucene-provider/README.md | 98 + .../docs/LUCENE-PROVIDER-PLUGIN.md | 97 + plugins/lucene-provider/plugin.yml | 31 + plugins/lucene-provider/pom.xml | 176 ++ plugins/search-lucene/CHANGELOG.md | 10 + plugins/search-lucene/LICENSE | 661 ++++ plugins/search-lucene/LICENSE-EXCEPTION | 44 + plugins/search-lucene/README.md | 92 + .../docs/SEARCH-LUCENE-PLUGIN.md | 224 ++ .../search-lucene/i18n/messages.properties | 30 + .../search-lucene/i18n/messages_es.properties | 30 + plugins/search-lucene/plugin.yml | 78 + plugins/search-lucene/pom.xml | 195 ++ .../scripts/verify-against-host.sh | 316 ++ .../java/mx/quest/searchlucene/HtmlText.java | 33 + .../quest/searchlucene/LocaleAnalyzers.java | 123 + .../quest/searchlucene/LuceneAdminModel.java | 35 + .../searchlucene/LuceneSearchEngine.java | 690 ++++ .../quest/searchlucene/LuceneSiteEvents.java | 37 + .../searchlucene/LuceneStorageProps.java | 72 + .../mx/quest/searchlucene/MatchedForms.java | 128 + .../mx/quest/searchlucene/RankingConfig.java | 98 + .../searchlucene/SearchLuceneConfig.java | 66 + .../searchlucene/LucenePerLanguageTest.java | 243 ++ .../searchlucene/LuceneSearchEngineTest.java | 668 ++++ .../searchlucene/LuceneStoragePropsTest.java | 50 + .../quest/searchlucene/RankingConfigTest.java | 61 + .../searchlucene/SearchLuceneConfigTest.java | 291 ++ plugins/search-lucene/templates/admin.html | 28 + plugins/search-lucene/templates/admin.th.xml | 14 + .../search-lucene/templates/dashboard.html | 16 + .../search-lucene/templates/dashboard.th.xml | 8 + plugins/search/CHANGELOG.md | 12 + plugins/search/LICENSE | 661 ++++ plugins/search/LICENSE-EXCEPTION | 44 + plugins/search/README.md | 56 + plugins/search/docs/SEARCH-PLUGIN.md | 332 ++ plugins/search/i18n/messages.properties | 92 + plugins/search/i18n/messages_es.properties | 89 + plugins/search/plugin.yml | 94 + plugins/search/pom.xml | 137 + plugins/search/scripts/verify-against-host.sh | 375 +++ .../java/mx/quest/search/HighlightMarker.java | 32 + .../src/main/java/mx/quest/search/Html.java | 21 + .../main/java/mx/quest/search/HtmlText.java | 43 + .../java/mx/quest/search/MatchedWords.java | 65 + .../java/mx/quest/search/NoResultsLog.java | 440 +++ .../mx/quest/search/ResultsPageLinks.java | 61 + .../mx/quest/search/SearchAdminModel.java | 115 + .../java/mx/quest/search/SearchBoxWidget.java | 174 + .../java/mx/quest/search/SearchClientId.java | 27 + .../java/mx/quest/search/SearchConfig.java | 133 + .../java/mx/quest/search/SearchDocument.java | 30 + .../java/mx/quest/search/SearchEndpoint.java | 370 +++ .../mx/quest/search/SearchHighlightHead.java | 47 + .../mx/quest/search/SearchProperties.java | 67 + .../mx/quest/search/SearchRateLimiter.java | 119 + .../mx/quest/search/SearchSiteConfig.java | 127 + .../mx/quest/search/SearchSiteEvents.java | 50 + .../java/mx/quest/search/SearchSnippet.java | 140 + .../mx/quest/search/SimpleSearchEngine.java | 373 +++ .../mx/quest/search/SiteSearchCorpus.java | 93 + .../mx/quest/search/spi/SearchCorpus.java | 72 + .../java/mx/quest/search/spi/SearchHit.java | 81 + .../java/mx/quest/search/spi/SearchQuery.java | 23 + .../mx/quest/search/spi/SiteSearchEngine.java | 61 + .../test/java/mx/quest/search/Fixtures.java | 114 + .../java/mx/quest/search/HighlightTest.java | 142 + .../java/mx/quest/search/HtmlTextTest.java | 55 + .../java/mx/quest/search/MutableClock.java | 32 + .../mx/quest/search/NoResultsLogTest.java | 395 +++ .../quest/search/NoResultsRecordingTest.java | 194 ++ .../mx/quest/search/SearchAdminModelTest.java | 71 + .../quest/search/SearchAdminTemplateTest.java | 114 + .../mx/quest/search/SearchBoxWidgetTest.java | 190 ++ .../mx/quest/search/SearchConfigTest.java | 281 ++ .../mx/quest/search/SearchEndpointTest.java | 348 ++ .../quest/search/SearchRateLimiterTest.java | 121 + .../mx/quest/search/SearchSnippetTest.java | 96 + .../quest/search/SimpleSearchEngineTest.java | 537 ++++ .../mx/quest/search/SiteSearchCorpusTest.java | 152 + .../search/src/test/js/highlight-pattern.js | 22 + plugins/search/static/highlight-loader.js | 2 + plugins/search/static/highlight.css | 9 + plugins/search/static/highlight.js | 192 ++ plugins/search/static/search-help.html | 82 + plugins/search/static/search.css | 88 + plugins/search/templates/admin.html | 95 + plugins/search/templates/admin.th.xml | 64 + plugins/search/templates/dashboard.html | 18 + plugins/search/templates/dashboard.th.xml | 10 + pom.xml | 71 + runway-app/pom.xml | 287 ++ .../mx/quest/runway/RunwayApplication.java | 30 + .../authz/AuthorizationAdminService.java | 487 +++ .../runway/authz/AuthorizationService.java | 184 ++ .../quest/runway/authz/AuthzExpressions.java | 92 + .../runway/authz/AuthzStoreIntegrity.java | 77 + .../mx/quest/runway/authz/AuthzWebConfig.java | 29 + .../java/mx/quest/runway/authz/GrantFile.java | 161 + .../mx/quest/runway/authz/GrantStore.java | 165 + .../runway/authz/MethodSecurityConfig.java | 20 + .../mx/quest/runway/authz/Permission.java | 33 + .../authz/PermissionAuthorizationManager.java | 51 + .../quest/runway/authz/PermissionCatalog.java | 127 + .../mx/quest/runway/authz/Permissions.java | 75 + .../authz/PluginPermissionContributions.java | 96 + .../runway/authz/QuarantinedSiteFilter.java | 58 + .../runway/authz/RequestAuthorizers.java | 29 + .../mx/quest/runway/authz/ReservedRoles.java | 62 + .../main/java/mx/quest/runway/authz/Role.java | 34 + .../java/mx/quest/runway/authz/RoleFile.java | 21 + .../java/mx/quest/runway/authz/RoleGraph.java | 164 + .../java/mx/quest/runway/authz/RoleStore.java | 128 + .../mx/quest/runway/backup/BackupConfig.java | 13 + .../quest/runway/backup/BackupManifest.java | 70 + .../backup/BackupParticipantRegistry.java | 61 + .../quest/runway/backup/BackupProperties.java | 139 + .../runway/backup/BackupRestoreRecovery.java | 68 + .../mx/quest/runway/backup/BackupService.java | 1152 +++++++ .../runway/backup/ScheduledBackupConfig.java | 25 + .../runway/backup/ScheduledBackupRunner.java | 51 + .../UnsupportedBackupFormatException.java | 33 + .../mx/quest/runway/backup/ZipBackup.java | 118 + .../runway/bandwidth/BandwidthConfig.java | 39 + .../runway/bandwidth/BandwidthFilter.java | 61 + .../bandwidth/BandwidthLimitFilter.java | 59 + .../runway/bandwidth/BandwidthProperties.java | 91 + .../runway/bandwidth/BandwidthService.java | 361 +++ .../java/mx/quest/runway/bandwidth/Bytes.java | 28 + .../bandwidth/CountingResponseWrapper.java | 112 + .../runway/bandwidth/SiteBandwidthQuotas.java | 99 + .../quest/runway/cluster/ClusterConfig.java | 140 + .../runway/cluster/ClusterEventEnvelope.java | 206 ++ .../runway/cluster/ClusterEventRelay.java | 188 ++ .../cluster/HazelcastSessionRepository.java | 92 + .../cluster/RunwayClusterProperties.java | 222 ++ .../AbstractPermissionsController.java | 226 ++ .../quest/runway/console/AccountSupport.java | 209 ++ .../runway/console/AdminHomeController.java | 46 + .../runway/console/AppAboutController.java | 37 + .../runway/console/AppAccountController.java | 98 + .../runway/console/AppBackupsController.java | 229 ++ .../console/AppBandwidthController.java | 38 + .../console/AppEmbedHostsController.java | 102 + .../runway/console/AppHomeController.java | 64 + .../console/AppLogLevelsController.java | 76 + .../runway/console/AppLoginController.java | 32 + .../runway/console/AppLogsController.java | 67 + .../console/AppPermissionsController.java | 66 + .../runway/console/AppRecoveryController.java | 106 + .../runway/console/AppSettingsController.java | 298 ++ .../runway/console/AppUsersController.java | 264 ++ .../runway/console/AssetCachePolicy.java | 83 + .../mx/quest/runway/console/AssetVersion.java | 77 + .../mx/quest/runway/console/AuditView.java | 220 ++ .../runway/console/BandwidthController.java | 49 + .../runway/console/ConsoleNavigation.java | 164 + .../runway/console/ConsoleScreenAdvice.java | 32 + .../runway/console/ConsoleUserService.java | 283 ++ .../runway/console/DashboardCardRegistry.java | 67 + .../runway/console/DocumentsController.java | 126 + .../quest/runway/console/HeadFieldRules.java | 84 + .../quest/runway/console/IconsController.java | 188 ++ .../console/KernelSettingsController.java | 227 ++ .../quest/runway/console/LogsController.java | 135 + .../runway/console/MaintenanceController.java | 73 + .../mx/quest/runway/console/MenuRegistry.java | 145 + .../runway/console/OperatorAssetsConfig.java | 43 + .../console/OperatorAwareMessageSource.java | 75 + .../runway/console/OperatorI18nConfig.java | 23 + .../console/OperatorLocaleController.java | 58 + .../console/OperatorLocaleResolver.java | 111 + .../runway/console/OperatorMessageSource.java | 69 + .../runway/console/OperatorModelAdvice.java | 33 + .../quest/runway/console/OperatorPaths.java | 34 + .../runway/console/OperatorProperties.java | 39 + .../runway/console/OperatorShellModel.java | 191 ++ .../console/OperatorTemplatingConfig.java | 47 + .../mx/quest/runway/console/PageForm.java | 261 ++ .../console/PermissionLabelResolver.java | 62 + .../console/PermissionsMatrixService.java | 139 + .../console/PlatformAdminModelAdvice.java | 32 + .../runway/console/PlatformAuthority.java | 44 + .../runway/console/PluginAdminController.java | 156 + .../console/PluginSettingsController.java | 208 ++ .../console/PluginTemplateResolver.java | 96 + .../runway/console/RuntimeInfoService.java | 386 +++ .../quest/runway/console/SeoController.java | 87 + .../mx/quest/runway/console/SettingField.java | 133 + .../quest/runway/console/SettingOption.java | 13 + .../quest/runway/console/SettingRefusals.java | 33 + .../quest/runway/console/SettingSection.java | 27 + .../mx/quest/runway/console/SettingsForm.java | 306 ++ .../quest/runway/console/SiteConfigInput.java | 112 + .../console/SiteInsightsController.java | 61 + .../runway/console/SiteMastersController.java | 252 ++ .../console/SiteTemplatesController.java | 257 ++ .../runway/console/SiteUserAuthority.java | 94 + .../quest/runway/console/SitesController.java | 471 +++ .../console/TenantAccountController.java | 133 + .../quest/runway/console/TenantAuthority.java | 39 + .../console/TenantBackupsController.java | 250 ++ .../console/TenantFragmentsController.java | 277 ++ .../console/TenantMessagesController.java | 319 ++ .../console/TenantPageActionsController.java | 223 ++ .../console/TenantPageEditorController.java | 523 ++++ .../console/TenantPageNewController.java | 115 + .../console/TenantPagePreviewController.java | 311 ++ .../runway/console/TenantPagesController.java | 74 + .../console/TenantPermissionsController.java | 73 + .../TenantPluginSettingsController.java | 159 + .../console/TenantRecoveryController.java | 115 + .../console/TenantReviewController.java | 288 ++ .../console/TenantSiteConfigController.java | 310 ++ .../console/TenantStaticFilesController.java | 249 ++ .../runway/console/TenantUsersController.java | 328 ++ .../console/WidgetInstancesController.java | 124 + .../runway/console/WrongPasswordCounter.java | 49 + .../quest/runway/content/ContentCatalog.java | 409 +++ .../content/ContentCatalogViewImpl.java | 108 + .../runway/content/ContentChangedEvent.java | 45 + .../runway/content/ContentChangesImpl.java | 66 + .../quest/runway/content/ContentRouter.java | 145 + .../runway/content/ContentSourceRegistry.java | 74 + .../runway/content/PagesContentSource.java | 372 +++ .../quest/runway/content/PathOwnership.java | 141 + .../quest/runway/content/RoutableContent.java | 139 + .../runway/crypto/AesGcmSecretCipher.java | 145 + .../mx/quest/runway/crypto/SecretCipher.java | 34 + .../mx/quest/runway/demo/DemoDescriptor.java | 74 + .../quest/runway/demo/DemoSiteInstaller.java | 229 ++ .../runway/demo/FirstRunDemoInstaller.java | 81 + .../document/DisabledDocumentsGuard.java | 31 + .../runway/document/DocumentService.java | 176 ++ .../runway/editorial/EditorialException.java | 31 + .../runway/editorial/EditorialService.java | 453 +++ .../mx/quest/runway/editorial/LineDiff.java | 140 + .../mx/quest/runway/editorial/PageStatus.java | 37 + .../quest/runway/editorial/SitePagesImpl.java | 141 + .../endpoint/AnonymousRouteMatcher.java | 64 + .../runway/endpoint/BoundedBodyRequest.java | 115 + .../runway/endpoint/CapturedFormRequest.java | 215 ++ .../endpoint/EndpointContributorRegistry.java | 185 ++ .../endpoint/EndpointDispatchConfig.java | 72 + .../endpoint/EndpointDispatchFilter.java | 383 +++ .../runway/endpoint/PreAuthBodyLimit.java | 31 + .../endpoint/PreAuthBodyLimitFilter.java | 132 + .../endpoint/RouteAwareFormContentFilter.java | 92 + .../endpoint/RouteFormCaptureFilter.java | 140 + .../mx/quest/runway/event/ClusterReplay.java | 42 + .../mx/quest/runway/event/HostWriteScope.java | 142 + .../quest/runway/event/KernelEventOrder.java | 59 + .../mx/quest/runway/event/SpiEventBridge.java | 363 +++ .../runway/head/HeadContributorRegistry.java | 131 + .../runway/head/HeadInjectionConfig.java | 39 + .../runway/head/HeadInjectionFilter.java | 356 +++ .../quest/runway/head/ScriptNonceStamper.java | 959 ++++++ .../runway/head/ScriptPreloadStripper.java | 246 ++ .../runway/head/ValidatorHoldingResponse.java | 130 + .../quest/runway/health/HealthProperties.java | 72 + .../runway/health/SiteContentReadiness.java | 88 + .../mx/quest/runway/health/SiteHealth.java | 67 + .../quest/runway/health/SiteHealthConfig.java | 51 + .../quest/runway/health/SiteHealthFilter.java | 165 + .../runway/health/SiteHealthService.java | 81 + .../runway/health/StorageHealthIndicator.java | 46 + .../mx/quest/runway/i18n/I18nProperties.java | 26 + .../runway/i18n/MessageSourceWiring.java | 22 + .../mx/quest/runway/i18n/MessagesImpl.java | 82 + .../runway/i18n/SiteAwareMessageSource.java | 367 +++ .../quest/runway/i18n/SiteMessagesStore.java | 387 +++ .../mx/quest/runway/i18n/package-info.java | 11 + .../runway/icon/IconGenerationService.java | 74 + .../runway/icon/IconHeadContributor.java | 93 + .../mx/quest/runway/icon/IconRasterizer.java | 150 + .../java/mx/quest/runway/icon/SiteIcon.java | 70 + .../quest/runway/icon/SiteIconEndpoints.java | 67 + .../mx/quest/runway/icon/SiteIconService.java | 89 + .../mx/quest/runway/icon/SiteManifest.java | 32 + .../runway/icon/SiteManifestService.java | 69 + .../quest/runway/icon/TenantIconSeeder.java | 83 + .../runway/icon/WebManifestEndpoint.java | 102 + .../mx/quest/runway/log/AccessLogConfig.java | 29 + .../mx/quest/runway/log/AccessLogFilter.java | 88 + .../mx/quest/runway/log/AppActivityLog.java | 210 ++ .../runway/log/AppActivityLogProperties.java | 35 + .../runway/log/AppAuditEventListener.java | 68 + .../java/mx/quest/runway/log/AuditEntry.java | 20 + .../quest/runway/log/AuditEventListener.java | 64 + .../mx/quest/runway/log/AuditJournal.java | 236 ++ .../java/mx/quest/runway/log/AuditPage.java | 26 + .../java/mx/quest/runway/log/AuditQuery.java | 45 + .../java/mx/quest/runway/log/LogKind.java | 25 + .../mx/quest/runway/log/LogProperties.java | 69 + .../quest/runway/log/SiteInsightsService.java | 405 +++ .../mx/quest/runway/log/SiteLogConfig.java | 28 + .../runway/log/SiteLogConfigService.java | 66 + .../mx/quest/runway/log/SiteLogService.java | 393 +++ .../runway/mail/JakartaMailTransport.java | 26 + .../mx/quest/runway/mail/MailTransport.java | 30 + .../mx/quest/runway/mail/PlatformMailer.java | 158 + .../quest/runway/metrics/KernelMetrics.java | 101 + .../quest/runway/metrics/MetricsConfig.java | 64 + .../runway/metrics/MetricsProperties.java | 26 + .../metrics/PrometheusScrapeAuthFilter.java | 92 + .../metrics/SiteRequestMetricsFilter.java | 84 + .../runway/page/CanonicalFingerprint.java | 124 + .../quest/runway/page/ChromeTemplateFold.java | 159 + .../mx/quest/runway/page/ContentUrls.java | 89 + .../quest/runway/page/FragmentException.java | 27 + .../quest/runway/page/FragmentTemplates.java | 364 +++ .../quest/runway/page/LoadedSiteInputs.java | 373 +++ .../quest/runway/page/LocaleNegotiator.java | 93 + .../mx/quest/runway/page/LocaleOption.java | 14 + .../java/mx/quest/runway/page/LocaleUrls.java | 75 + .../mx/quest/runway/page/MasterTemplates.java | 80 + .../main/java/mx/quest/runway/page/Page.java | 285 ++ .../runway/page/PageAuthoringException.java | 26 + .../runway/page/PageAuthoringValidator.java | 111 + .../page/PageCacheInvalidationListener.java | 58 + .../quest/runway/page/PageChangedEvent.java | 32 + .../quest/runway/page/PageReseedService.java | 160 + .../java/mx/quest/runway/page/PageReview.java | 80 + .../mx/quest/runway/page/PageRouting.java | 141 + .../mx/quest/runway/page/PageScaffold.java | 96 + .../java/mx/quest/runway/page/PageStore.java | 168 + .../mx/quest/runway/page/PageValidator.java | 67 + .../runway/page/PageValidatorService.java | 629 ++++ .../java/mx/quest/runway/page/PageViews.java | 38 + .../quest/runway/page/PageWriteService.java | 459 +++ .../runway/page/PendingRevisionStore.java | 264 ++ .../runway/page/PreviewScratchSweeper.java | 62 + .../quest/runway/page/RenderModelBuilder.java | 203 ++ .../java/mx/quest/runway/page/Routable.java | 60 + .../mx/quest/runway/page/package-info.java | 17 + .../runway/platform/EmbedHostService.java | 166 + .../quest/runway/platform/HostSettings.java | 86 + .../quest/runway/platform/KernelSettings.java | 104 + .../platform/KernelSettingsInitializer.java | 157 + .../platform/KernelSettingsService.java | 525 ++++ .../runway/platform/LogLevelService.java | 211 ++ .../runway/platform/PlatformSettings.java | 286 ++ .../platform/PlatformSettingsStore.java | 93 + .../runway/platform/SchedulingConfig.java | 56 + .../ContainedSchedulingPostProcessor.java | 110 + .../runway/plugin/ContributionGuard.java | 395 +++ .../runway/plugin/EssentialAllowlist.java | 58 + .../quest/runway/plugin/EssentialFloor.java | 27 + .../runway/plugin/EssentialFloorFilter.java | 53 + .../runway/plugin/HostLinkageScanner.java | 365 +++ .../mx/quest/runway/plugin/LoadedPlugin.java | 24 + .../quest/runway/plugin/PlaceholderText.java | 64 + .../runway/plugin/PluginAdminService.java | 582 ++++ .../quest/runway/plugin/PluginCardDecl.java | 16 + .../quest/runway/plugin/PluginCompliance.java | 101 + .../plugin/PluginContextInitializer.java | 451 +++ .../quest/runway/plugin/PluginDescriptor.java | 290 ++ .../runway/plugin/PluginInstallation.java | 81 + .../mx/quest/runway/plugin/PluginLoader.java | 212 ++ .../mx/quest/runway/plugin/PluginManager.java | 152 + .../quest/runway/plugin/PluginMenuDecl.java | 21 + .../quest/runway/plugin/PluginOwnership.java | 207 ++ .../runway/plugin/PluginPermissionDecl.java | 23 + .../quest/runway/plugin/PluginQuarantine.java | 280 ++ .../plugin/PluginQuarantineListener.java | 63 + .../runway/plugin/PluginRequirement.java | 62 + .../quest/runway/plugin/PluginResolution.java | 275 ++ .../mx/quest/runway/plugin/PluginRuntime.java | 35 + .../runway/plugin/PluginScopedServices.java | 149 + .../quest/runway/plugin/PluginSettingDef.java | 95 + .../runway/plugin/PluginSettingGroup.java | 15 + .../runway/plugin/PluginSettingsService.java | 287 ++ .../quest/runway/plugin/PluginSiteData.java | 84 + .../plugin/PluginStaticResourceConfig.java | 200 ++ .../mx/quest/runway/plugin/PluginStatus.java | 31 + .../runway/plugin/PluginSurfaceCheck.java | 279 ++ .../mx/quest/runway/plugin/PluginVersion.java | 61 + .../quest/runway/plugin/PluginWebConfig.java | 27 + .../quest/runway/plugin/RunningPlugins.java | 16 + .../quest/runway/plugin/SecretBindings.java | 81 + .../plugin/SettingKeyListDeserializer.java | 55 + .../mx/quest/runway/plugin/SettingType.java | 166 + .../plugin/SettingValidationException.java | 51 + .../plugin/SitePluginConfigChangedEvent.java | 14 + .../plugin/SitePluginConfigService.java | 277 ++ .../runway/plugin/spi/PluginSettingsImpl.java | 158 + .../plugin/spi/PluginSiteFilesImpl.java | 281 ++ .../mx/quest/runway/protect/EdgeGuard.java | 49 + .../runway/protect/EdgeProtectionConfig.java | 56 + .../protect/EdgeProtectionProperties.java | 54 + .../runway/protect/EdgeRejectFilter.java | 74 + .../runway/protect/EdgeRejectionRecorder.java | 170 + .../mx/quest/runway/protect/EdgeRequest.java | 27 + .../mx/quest/runway/protect/EdgeVerdict.java | 71 + .../runway/protect/NoCaptchaService.java | 30 + .../protect/NoSiteLoginProtectionControl.java | 29 + .../runway/protect/PermissiveEdgeGuard.java | 15 + .../runway/protect/RejectionOutcome.java | 31 + .../runway/quality/DescriptionCheck.java | 53 + .../runway/quality/DuplicateMetaCheck.java | 86 + .../runway/quality/HeadingStructureCheck.java | 60 + .../quest/runway/quality/ImageAltCheck.java | 53 + .../quest/runway/quality/LinkTextCheck.java | 72 + .../quality/PageQualityCheckRegistry.java | 74 + .../runway/quality/PageQualityService.java | 50 + .../mx/quest/runway/quality/QualityGate.java | 107 + .../quest/runway/quality/QualityReport.java | 72 + .../mx/quest/runway/quality/RenderedHtml.java | 71 + .../runway/quality/ThinContentCheck.java | 49 + .../runway/quality/TitlePresenceCheck.java | 47 + .../recovery/PasswordRecoveryService.java | 289 ++ .../quest/runway/recovery/RecoveryToken.java | 29 + .../runway/recovery/RecoveryTokenStore.java | 166 + .../quest/runway/reload/ReloadProperties.java | 44 + .../quest/runway/reload/SiteReloadConfig.java | 38 + .../quest/runway/reload/SiteReloadFilter.java | 141 + .../runway/reload/SiteReloadService.java | 94 + .../runway/reload/SiteReloadStartupCheck.java | 62 + .../runway/security/AccountStateFilter.java | 174 + .../runway/security/AccountStatusChecks.java | 26 + .../security/ActivePasswordStrength.java | 19 + .../runway/security/AppSecurityConfig.java | 148 + .../security/AppUserDetailsService.java | 32 + .../quest/runway/security/AppUserStore.java | 177 ++ .../ConcurrencyLimitedPasswordEncoder.java | 73 + .../CsrfExpiryAccessDeniedHandler.java | 78 + .../security/LoginAttemptEventListener.java | 43 + .../runway/security/LoginAttemptGate.java | 26 + .../quest/runway/security/LoginFormGuard.java | 36 + .../runway/security/LoginFormVerdict.java | 53 + .../security/LoginProtectionConfig.java | 48 + .../security/LoginProtectionFilter.java | 137 + .../security/NoTrustedDeviceIssuer.java | 18 + .../runway/security/PasswordEncoders.java | 49 + .../PasswordHashingBusyException.java | 14 + .../runway/security/PasswordStrength.java | 28 + .../security/PermissiveLoginAttemptGate.java | 25 + .../security/PermissiveLoginFormGuard.java | 21 + .../runway/security/ProtectionScope.java | 48 + .../runway/security/RealmActivation.java | 35 + .../java/mx/quest/runway/security/Roles.java | 36 + .../security/RunwaySecurityProperties.java | 80 + .../runway/security/RunwayUserDetails.java | 110 + .../quest/runway/security/SecurityConfig.java | 60 + .../runway/security/SecurityHeaders.java | 114 + .../SiteScopedCsrfTokenRepository.java | 72 + .../SiteScopedSecurityContextRepository.java | 92 + .../security/SiteUserDetailsService.java | 81 + .../quest/runway/security/SiteUserStore.java | 89 + .../security/TenantConsoleController.java | 54 + .../runway/security/TenantMasterStore.java | 127 + .../runway/security/TenantProvisioning.java | 47 + .../runway/security/TenantSecurityConfig.java | 142 + .../TenantSiteAuthorizationManager.java | 72 + .../runway/security/TrustedDeviceIssuer.java | 34 + .../security/TrustedDeviceSuccessHandler.java | 73 + .../java/mx/quest/runway/security/User.java | 103 + .../mx/quest/runway/security/UserFile.java | 22 + .../mx/quest/runway/security/UserStore.java | 197 ++ .../security/UsernameTakenException.java | 31 + .../runway/seo/CanonicalHeadContributor.java | 94 + .../mx/quest/runway/seo/SeoConfigService.java | 73 + .../quest/runway/seo/SeoHeadContributor.java | 186 ++ .../mx/quest/runway/seo/SiteSeoConfig.java | 39 + .../runway/site/DefaultSiteMaintenance.java | 72 + .../mx/quest/runway/site/EditorialLevel.java | 87 + .../runway/site/MaintenanceSiteFilter.java | 89 + .../quest/runway/site/SeedTemplateStore.java | 522 +++ .../main/java/mx/quest/runway/site/Site.java | 178 ++ .../mx/quest/runway/site/SiteBaseUrl.java | 63 + .../quest/runway/site/SiteChangedEvent.java | 63 + .../mx/quest/runway/site/SiteContact.java | 37 + .../quest/runway/site/SiteContactService.java | 78 + .../quest/runway/site/SiteContextFilter.java | 42 + .../mx/quest/runway/site/SiteCspService.java | 127 + .../java/mx/quest/runway/site/SiteHosts.java | 141 + .../runway/site/SiteLifecycleService.java | 286 ++ .../quest/runway/site/SiteParamsService.java | 133 + .../mx/quest/runway/site/SiteResolver.java | 139 + .../java/mx/quest/runway/site/SiteStatus.java | 14 + .../runway/site/SiteStorageCeilings.java | 229 ++ .../java/mx/quest/runway/site/SiteStore.java | 118 + .../java/mx/quest/runway/site/SiteViews.java | 27 + .../mx/quest/runway/site/SiteWebConfig.java | 49 + .../java/mx/quest/runway/site/SitesImpl.java | 31 + .../quest/runway/site/StaticFilesService.java | 288 ++ .../runway/site/SuspendedSiteFilter.java | 52 + .../mx/quest/runway/site/TenantSeeder.java | 89 + .../mx/quest/runway/site/package-info.java | 23 + .../mx/quest/runway/storage/AtomicFiles.java | 65 + .../mx/quest/runway/storage/DataLayout.java | 165 + .../runway/storage/DataLayoutException.java | 43 + .../storage/DataLayoutFailureAnalyzer.java | 24 + .../runway/storage/DataLayoutInitializer.java | 66 + .../mx/quest/runway/storage/FileStamp.java | 211 ++ .../quest/runway/storage/OwnerOnlyFiles.java | 59 + .../mx/quest/runway/storage/PathSafety.java | 183 ++ .../runway/storage/RetiredStorageKeys.java | 53 + .../quest/runway/storage/SiteFileStore.java | 315 ++ .../quest/runway/storage/StorageConfig.java | 39 + .../quest/runway/storage/StorageLayout.java | 186 ++ .../runway/storage/StorageProperties.java | 51 + .../mx/quest/runway/storage/StoreCache.java | 72 + .../mx/quest/runway/storage/UploadNames.java | 34 + .../java/mx/quest/runway/storage/Yaml.java | 51 + .../mx/quest/runway/storage/YamlStore.java | 86 + .../java/mx/quest/runway/storage/Zips.java | 67 + .../mx/quest/runway/storage/package-info.java | 24 + .../mx/quest/runway/web/AppRealmPaths.java | 72 + .../runway/web/BufferingResponseWrapper.java | 266 ++ .../java/mx/quest/runway/web/CidrSet.java | 176 ++ .../java/mx/quest/runway/web/ClientIp.java | 24 + .../quest/runway/web/CompressionConfig.java | 37 + .../quest/runway/web/CompressionFilter.java | 290 ++ .../quest/runway/web/ConsoleHostConfig.java | 33 + .../quest/runway/web/ConsoleHostFilter.java | 201 ++ .../runway/web/ConsoleHostProperties.java | 32 + .../java/mx/quest/runway/web/CspConfig.java | 70 + .../java/mx/quest/runway/web/CspFilter.java | 418 +++ .../quest/runway/web/CspHostContributor.java | 31 + .../mx/quest/runway/web/CspNonceAdvice.java | 31 + .../quest/runway/web/CspReportController.java | 100 + .../quest/runway/web/CspScriptAllowlist.java | 463 +++ .../mx/quest/runway/web/DraftRenderer.java | 138 + .../java/mx/quest/runway/web/ErrorPages.java | 146 + .../quest/runway/web/FileStampValidity.java | 51 + .../quest/runway/web/FilterContribution.java | 34 + .../java/mx/quest/runway/web/FilterOrder.java | 210 ++ .../runway/web/ForwardedHeaderConfig.java | 50 + .../mx/quest/runway/web/HttpCacheConfig.java | 15 + .../web/HttpToHttpsRedirectHandler.java | 159 + .../runway/web/JettyFormLimitsConfig.java | 59 + .../mx/quest/runway/web/KeystoreWatcher.java | 129 + .../java/mx/quest/runway/web/LogSafe.java | 42 + .../quest/runway/web/MultipartCsrfConfig.java | 39 + .../mx/quest/runway/web/PageController.java | 473 +++ .../mx/quest/runway/web/PageRenderer.java | 77 + .../runway/web/PluginFilterPlacement.java | 54 + .../runway/web/PluginFilterRegistrar.java | 42 + .../mx/quest/runway/web/PublicPageNonce.java | 246 ++ .../quest/runway/web/RequestContextImpl.java | 45 + .../mx/quest/runway/web/RequestOrigin.java | 55 + .../mx/quest/runway/web/RequestPaths.java | 122 + .../mx/quest/runway/web/ReservedPaths.java | 54 + .../web/RunwayCompressionProperties.java | 135 + .../quest/runway/web/RunwayCspProperties.java | 481 +++ .../runway/web/RunwayErrorController.java | 130 + .../runway/web/RunwayHttpCacheProperties.java | 194 ++ .../runway/web/RunwayProxyProperties.java | 40 + .../quest/runway/web/RunwayTlsProperties.java | 165 + .../mx/quest/runway/web/SiteCspPolicies.java | 45 + .../mx/quest/runway/web/SiteHealthPaths.java | 19 + .../mx/quest/runway/web/SiteReloadPaths.java | 32 + .../runway/web/SiteStaticController.java | 202 ++ .../mx/quest/runway/web/SiteStaticGuard.java | 21 + .../runway/web/SiteTemplateResolver.java | 132 + .../runway/web/TemplateCacheService.java | 114 + .../mx/quest/runway/web/TemplatingConfig.java | 24 + .../quest/runway/web/TenantConsolePaths.java | 45 + .../runway/web/TlsCertificateReloader.java | 104 + .../java/mx/quest/runway/web/TlsConfig.java | 119 + .../java/mx/quest/runway/web/TlsStartup.java | 104 + .../web/TrustedForwardedHeaderFilter.java | 100 + .../mx/quest/runway/web/UnmeteredPaths.java | 39 + .../WidgetAwareDecoupledLogicResolver.java | 96 + .../runway/widget/ContentWidgetRegistry.java | 82 + .../mx/quest/runway/widget/WidgetBinding.java | 22 + .../widget/WidgetInstanceConfigService.java | 309 ++ .../widget/WidgetInstanceDiscovery.java | 98 + .../runway/widget/WidgetModelBuilder.java | 160 + .../mx/quest/runway/widget/WidgetScanner.java | 71 + .../runway/widget/WidgetSettingsCatalog.java | 81 + .../mx/quest/runway/widget/WidgetWiring.java | 22 + .../runway/wizard/ActiveModeCondition.java | 23 + .../quest/runway/wizard/ActiveRestarter.java | 53 + .../mx/quest/runway/wizard/Restarter.java | 21 + .../runway/wizard/SupervisedRestarter.java | 47 + .../quest/runway/wizard/WizardController.java | 150 + .../runway/wizard/WizardModeCondition.java | 22 + .../runway/wizard/WizardSecurityConfig.java | 45 + .../mx/quest/runway/wizard/WizardService.java | 230 ++ ...itional-spring-configuration-metadata.json | 99 + .../main/resources/META-INF/spring.factories | 23 + runway-app/src/main/resources/application.yml | 371 +++ .../src/main/resources/codemirror.version | 1 + .../i18n/operator-messages.properties | 1573 ++++++++++ .../i18n/operator-messages_es.properties | 1574 ++++++++++ .../src/main/resources/kernel-settings.yml | 93 + .../resources/seed/site-icons/favicon.svg | 7 + .../src/main/resources/seed/site/_master.html | 184 ++ .../main/resources/seed/site/_master.th.xml | 35 + .../src/main/resources/seed/site/about.html | 52 + .../main/resources/seed/site/about.meta.yml | 7 + .../src/main/resources/seed/site/about.th.xml | 12 + .../src/main/resources/seed/site/index.html | 67 + .../main/resources/seed/site/index.meta.yml | 7 + .../src/main/resources/seed/site/index.th.xml | 19 + .../src/main/resources/static/captcha-v3.js | 44 + .../main/resources/static/listing-tables.css | 178 ++ .../main/resources/static/listing-tables.js | 763 +++++ .../src/main/resources/static/messages.js | 170 + .../src/main/resources/static/page-editor.js | 431 +++ .../src/main/resources/static/restarting.js | 16 + .../main/resources/static/runway-chrome.css | 239 ++ .../main/resources/static/runway-chrome.js | 155 + .../src/main/resources/static/runway.svg | 1 + .../resources/static/vendor/alpine.min.js | 5 + .../main/resources/static/vendor/chart.min.js | 14 + .../static/vendor/codemirror.min.css | 5 + .../resources/static/vendor/codemirror.min.js | 24 + .../static/vendor/fontawesome/css/all.min.css | 9 + .../fontawesome/webfonts/fa-brands-400.woff2 | Bin 0 -> 114412 bytes .../fontawesome/webfonts/fa-regular-400.woff2 | Bin 0 -> 19480 bytes .../fontawesome/webfonts/fa-solid-900.woff2 | Bin 0 -> 119156 bytes .../webfonts/fa-v4compatibility.woff2 | Bin 0 -> 4204 bytes .../main/resources/static/vendor/htmx.min.js | 1 + .../resources/static/vendor/tabler.min.css | 9 + .../resources/static/vendor/tabler.min.js | 13 + .../resources/templates/operator/account.html | 57 + .../templates/operator/account.th.xml | 28 + .../templates/operator/admin/backups.html | 103 + .../templates/operator/admin/backups.th.xml | 62 + .../templates/operator/admin/bandwidth.html | 53 + .../templates/operator/admin/bandwidth.th.xml | 23 + .../templates/operator/admin/documents.html | 69 + .../templates/operator/admin/documents.th.xml | 40 + .../operator/admin/fragment-editor.html | 71 + .../operator/admin/fragment-editor.th.xml | 42 + .../templates/operator/admin/fragments.html | 98 + .../templates/operator/admin/fragments.th.xml | 64 + .../templates/operator/admin/home.html | 35 + .../templates/operator/admin/home.th.xml | 11 + .../templates/operator/admin/icons.html | 62 + .../templates/operator/admin/icons.th.xml | 36 + .../templates/operator/admin/insights.html | 96 + .../templates/operator/admin/insights.th.xml | 53 + .../templates/operator/admin/logs.html | 51 + .../templates/operator/admin/logs.th.xml | 25 + .../templates/operator/admin/maintenance.html | 48 + .../operator/admin/maintenance.th.xml | 24 + .../templates/operator/admin/messages.html | 121 + .../templates/operator/admin/messages.th.xml | 67 + .../templates/operator/admin/page-editor.html | 389 +++ .../operator/admin/page-editor.th.xml | 205 ++ .../templates/operator/admin/page-new.html | 50 + .../templates/operator/admin/page-new.th.xml | 20 + .../templates/operator/admin/pages.html | 73 + .../templates/operator/admin/pages.th.xml | 50 + .../templates/operator/admin/review-item.html | 146 + .../operator/admin/review-item.th.xml | 78 + .../templates/operator/admin/review.html | 49 + .../templates/operator/admin/review.th.xml | 27 + .../templates/operator/admin/seo.html | 99 + .../templates/operator/admin/seo.th.xml | 47 + .../templates/operator/admin/site-config.html | 172 + .../operator/admin/site-config.th.xml | 91 + .../operator/admin/static-files.html | 104 + .../operator/admin/static-files.th.xml | 62 + .../templates/operator/admin/users.html | 135 + .../templates/operator/admin/users.th.xml | 93 + .../operator/admin/web-manifest.html | 65 + .../operator/admin/web-manifest.th.xml | 28 + .../operator/admin/widget-instances.html | 64 + .../operator/admin/widget-instances.th.xml | 49 + .../templates/operator/app/about.html | 73 + .../templates/operator/app/about.th.xml | 32 + .../templates/operator/app/backups.html | 89 + .../templates/operator/app/backups.th.xml | 57 + .../templates/operator/app/bandwidth.html | 58 + .../templates/operator/app/bandwidth.th.xml | 27 + .../templates/operator/app/embed-hosts.html | 73 + .../templates/operator/app/embed-hosts.th.xml | 42 + .../templates/operator/app/home.html | 49 + .../templates/operator/app/home.th.xml | 23 + .../templates/operator/app/log-levels.html | 67 + .../templates/operator/app/log-levels.th.xml | 37 + .../templates/operator/app/logs.html | 29 + .../templates/operator/app/logs.th.xml | 15 + .../templates/operator/app/masters.html | 135 + .../templates/operator/app/masters.th.xml | 70 + .../templates/operator/app/plugins.html | 122 + .../templates/operator/app/plugins.th.xml | 90 + .../templates/operator/app/settings.html | 172 + .../templates/operator/app/settings.th.xml | 79 + .../operator/app/site-template-edit.html | 51 + .../operator/app/site-template-edit.th.xml | 31 + .../operator/app/site-template-files.html | 82 + .../operator/app/site-template-files.th.xml | 50 + .../operator/app/site-templates.html | 130 + .../operator/app/site-templates.th.xml | 55 + .../templates/operator/app/sites.html | 188 ++ .../templates/operator/app/sites.th.xml | 134 + .../templates/operator/app/users.html | 135 + .../templates/operator/app/users.th.xml | 87 + .../templates/operator/audit-journal.html | 72 + .../templates/operator/audit-journal.th.xml | 40 + .../operator/fragments/admin-topbar.html | 101 + .../operator/fragments/admin-topbar.th.xml | 113 + .../operator/fragments/app-topbar.html | 95 + .../operator/fragments/app-topbar.th.xml | 94 + .../templates/operator/login-app.html | 110 + .../templates/operator/login-app.th.xml | 73 + .../templates/operator/login-tenant.html | 105 + .../templates/operator/login-tenant.th.xml | 71 + .../templates/operator/op-layout.html | 68 + .../templates/operator/op-layout.th.xml | 85 + .../templates/operator/permissions.html | 174 + .../templates/operator/permissions.th.xml | 93 + .../templates/operator/plugin-settings.html | 77 + .../templates/operator/plugin-settings.th.xml | 68 + .../templates/operator/recovery-forgot.html | 81 + .../templates/operator/recovery-forgot.th.xml | 64 + .../templates/operator/recovery-reset.html | 67 + .../templates/operator/recovery-reset.th.xml | 49 + .../templates/operator/restarting.html | 26 + .../templates/operator/restarting.th.xml | 16 + .../templates/operator/setting-row.html | 41 + .../templates/operator/setting-row.th.xml | 60 + .../runway/ConfigurationMetadataTest.java | 83 + .../authz/AuthorizationAdminServiceTest.java | 364 +++ .../authz/AuthorizationServiceTest.java | 145 + .../runway/authz/AuthzExpressionsTest.java | 107 + .../runway/authz/AuthzStoreIntegrityTest.java | 82 + .../authz/GrantWriteConcurrencyTest.java | 146 + .../authz/MethodSecurityIntegrationTest.java | 96 + .../PermissionAuthorizationManagerTest.java | 102 + .../runway/authz/PermissionCatalogTest.java | 49 + .../mx/quest/runway/authz/PermissionTest.java | 26 + .../authz/PluginPermissionMergeTest.java | 72 + .../authz/QuarantinedSiteFilterTest.java | 101 + .../mx/quest/runway/authz/RoleDeltaTest.java | 191 ++ .../mx/quest/runway/authz/RoleGraphTest.java | 77 + .../mx/quest/runway/authz/RoleStoreTest.java | 76 + .../backup/BackupFormatVersionTest.java | 233 ++ .../backup/BackupParticipantRegistryTest.java | 49 + .../backup/BackupRestoreRecoveryTest.java | 79 + .../runway/backup/BackupRetentionTest.java | 103 + .../runway/backup/BackupServiceTest.java | 620 ++++ .../runway/backup/DemoExportRestoreTest.java | 282 ++ .../backup/ScheduledAndOffsiteBackupTest.java | 115 + .../runway/backup/TransferExportTest.java | 393 +++ .../backup/TransferPersonalDataTest.java | 255 ++ .../runway/backup/ZipBackupEntryNameTest.java | 52 + .../bandwidth/BandwidthLimitFilterTest.java | 79 + .../bandwidth/BandwidthServiceTest.java | 128 + .../CountingResponseWrapperTest.java | 27 + .../cluster/ClusterActiveModeGatingTest.java | 42 + .../cluster/ClusterDisabledByDefaultTest.java | 69 + .../cluster/ClusterEnabledActiveTest.java | 93 + .../runway/cluster/ClusterEventRelayTest.java | 295 ++ .../cluster/ClusterEventRelayTwoNodeTest.java | 233 ++ .../HazelcastSessionRepositoryTest.java | 173 + .../SessionPrincipalSerializationTest.java | 82 + .../AccountPasswordCheckLimitTest.java | 342 ++ .../runway/console/AccountProfileTest.java | 201 ++ .../runway/console/AccountScreenTest.java | 125 + .../runway/console/AppAboutPageTest.java | 172 + .../runway/console/AppBackupsScreenTest.java | 200 ++ .../console/AppBandwidthScreenTest.java | 77 + .../console/AppConsolePermissionsTest.java | 177 ++ .../runway/console/AppLogLevelsTest.java | 175 ++ .../runway/console/AppLogsScreenTest.java | 270 ++ .../runway/console/AppSettingsScreenTest.java | 320 ++ .../runway/console/AppSiteEditScreenTest.java | 182 ++ .../console/AppSiteHostsScreenTest.java | 184 ++ .../runway/console/AppSiteQuotaTest.java | 186 ++ .../console/AppUserEditSuspendTest.java | 275 ++ .../console/AppUsersAndMastersTest.java | 223 ++ .../runway/console/AssetCachePolicyTest.java | 82 + .../runway/console/AssetVersionAudit.java | 68 + .../quest/runway/console/AuditViewTest.java | 190 ++ .../console/BackupFormatMessagesTest.java | 40 + .../runway/console/BandwidthScreenTest.java | 108 + .../console/CompressionHostLockTest.java | 84 + .../console/ConsoleMessagesInSpanishTest.java | 128 + .../runway/console/ConsoleNavigationTest.java | 119 + .../ConsoleNavigationVisibilityTest.java | 237 ++ .../console/ConsoleUserServiceTest.java | 196 ++ .../runway/console/DocumentsScreenTest.java | 154 + .../console/EditorialWorkflowScreenTest.java | 505 +++ .../runway/console/FragmentsScreenTest.java | 369 +++ .../quest/runway/console/IconsScreenTest.java | 200 ++ .../console/KernelSettingsAdoptTest.java | 359 +++ .../console/KernelSettingsScreenTest.java | 345 ++ .../quest/runway/console/LogsScreenTest.java | 194 ++ .../runway/console/MaintenanceScreenTest.java | 132 + .../runway/console/MenuAndDashboardTest.java | 176 ++ .../runway/console/MessageApostropheTest.java | 44 + .../runway/console/MessagesScreenTest.java | 390 +++ .../runway/console/OperatorA11yAudit.java | 209 ++ .../runway/console/OperatorA11yAuditTest.java | 105 + .../runway/console/OperatorA11yGuardTest.java | 564 ++++ .../console/OperatorLocaleResolverTest.java | 78 + .../console/OperatorLocaleSwitcherTest.java | 144 + .../OperatorMessagePluginI18nTest.java | 87 + .../runway/console/OperatorPathsTest.java | 43 + .../console/OperatorShellModelTest.java | 162 + .../runway/console/OperatorShellTest.java | 196 ++ .../console/OperatorSpanishRegisterTest.java | 76 + .../console/OperatorTemplateIdGuardTest.java | 140 + .../runway/console/PageActionsScreenTest.java | 158 + .../runway/console/PageEditorScreenTest.java | 425 +++ .../console/PageEditorScriptsSeamTest.java | 101 + .../mx/quest/runway/console/PageFormTest.java | 55 + .../runway/console/PageNewScreenTest.java | 186 ++ .../runway/console/PagePreviewI18nTest.java | 137 + .../runway/console/PagePreviewScreenTest.java | 262 ++ .../runway/console/PageRenameScreenTest.java | 204 ++ .../PasswordChangeEndsSessionsTest.java | 340 ++ .../console/PermissionLabelResolverTest.java | 69 + .../runway/console/PermissionsMatrixTest.java | 216 ++ .../runway/console/PluginAdminScreenTest.java | 217 ++ .../runway/console/PluginFragmentTest.java | 123 + .../console/PluginHealthScreenTest.java | 227 ++ .../PluginPermissionEnforcementTest.java | 130 + .../console/PluginSettingsFormTest.java | 346 ++ .../console/PluginTemplateOnDiskEditTest.java | 86 + .../runway/console/RecoveryScreenTest.java | 173 + .../console/RuntimeInfoVersionParseTest.java | 43 + .../SecretBoundSettingsScreenTest.java | 163 + .../quest/runway/console/SeoScreenTest.java | 148 + .../runway/console/SettingRefusalsTest.java | 44 + .../runway/console/SettingsFormTest.java | 399 +++ .../runway/console/SiteConfigInputTest.java | 62 + .../runway/console/SiteConfigScreenTest.java | 259 ++ .../console/SiteInsightsScreenTest.java | 195 ++ .../runway/console/SiteMasterSuspendTest.java | 209 ++ .../SiteStorageCeilingScreensTest.java | 199 ++ .../console/SiteTemplatesControllerTest.java | 256 ++ .../console/SiteTemplatesScreenTest.java | 103 + .../quest/runway/console/SitesScreenTest.java | 153 + .../runway/console/StaticFilesScreenTest.java | 222 ++ .../console/TenantAuditRecordingTest.java | 196 ++ .../console/TenantBackupsScreenTest.java | 317 ++ .../console/TenantConsolePagesTest.java | 210 ++ .../console/TenantPluginSettingsGateTest.java | 148 + .../runway/console/TenantScreensTest.java | 219 ++ .../console/TenantUserEditSuspendTest.java | 255 ++ .../console/TenantUserPermissionsTest.java | 352 +++ .../console/UrlLocalizationAdvisoryTest.java | 204 ++ .../console/WidgetInstancesScreenTest.java | 170 + ...ntentCatalogCacheAndReservedPathsTest.java | 132 + .../runway/content/ContentCatalogTest.java | 161 + .../ContentCatalogViewIntegrationTest.java | 225 ++ .../content/ContentChangesImplTest.java | 106 + .../content/ContentSourceRegistryTest.java | 63 + .../content/PagesContentSourceTest.java | 177 ++ .../PagesRenderedIndexableTextTest.java | 239 ++ .../runway/content/PathOwnershipTest.java | 111 + .../content/PluginBodyTemplateRenderTest.java | 271 ++ .../content/VirtualContentRoutingTest.java | 430 +++ .../runway/crypto/AesGcmSecretCipherTest.java | 102 + .../runway/crypto/SecretCipherFuzzTest.java | 98 + .../runway/demo/DemoSiteInstallerTest.java | 139 + .../document/DisabledDocumentsGuardTest.java | 49 + .../runway/document/DocumentServiceTest.java | 140 + .../editorial/EditorialServiceTest.java | 520 +++ .../quest/runway/editorial/LineDiffTest.java | 85 + .../runway/editorial/SitePagesImplTest.java | 218 ++ .../endpoint/AnonymousRouteSecurityTest.java | 179 ++ .../endpoint/BoundedBodyRequestTest.java | 65 + .../EndpointContributorRegistryTest.java | 89 + .../runway/endpoint/EndpointDispatchTest.java | 333 ++ .../endpoint/KernelContributionsTest.java | 35 + .../endpoint/PreAuthBodyLimitE2ETest.java | 384 +++ .../RouteAwareFormContentFilterTest.java | 92 + .../endpoint/RouteBodyMethodsE2ETest.java | 218 ++ .../runway/endpoint/RouteFormBodyE2ETest.java | 218 ++ .../runway/endpoint/RouteFormCapE2ETest.java | 231 ++ .../endpoint/RouteFormCaptureFilterTest.java | 348 ++ .../runway/endpoint/RouteRequestK2Test.java | 374 +++ .../runway/event/HostWriteScopeTest.java | 152 + .../runway/event/KernelEventOrderTest.java | 124 + .../KernelListenerOrderIntegrationTest.java | 182 ++ .../runway/event/SpiEventBridgeTest.java | 452 +++ .../SpiEventDispatchIntegrationTest.java | 335 ++ .../head/HeadContributorRegistryTest.java | 89 + .../runway/head/HeadInjectionFilterTest.java | 655 ++++ .../runway/head/ScriptNonceStamperTest.java | 616 ++++ .../head/ScriptPreloadStripperTest.java | 677 ++++ .../health/SiteContentReadinessTest.java | 97 + .../runway/health/SiteHealthEndToEndTest.java | 202 ++ .../runway/health/SiteHealthServiceTest.java | 125 + .../health/StorageHealthIndicatorTest.java | 36 + .../runway/i18n/LanguageTagBundlesTest.java | 56 + .../quest/runway/i18n/MessagesImplTest.java | 143 + .../mx/quest/runway/i18n/PageI18nTest.java | 137 + .../i18n/SiteAwareMessageSourceTest.java | 215 ++ .../runway/i18n/SiteAwarePluginI18nTest.java | 75 + .../runway/i18n/SiteMessagesStoreTest.java | 416 +++ .../icon/IconGenerationServiceTest.java | 61 + .../runway/icon/IconHeadContributorTest.java | 58 + .../quest/runway/icon/IconRasterizerTest.java | 82 + .../mx/quest/runway/icon/SiteIconTest.java | 107 + .../runway/icon/SiteManifestServiceTest.java | 63 + .../runway/icon/TenantIconSeederTest.java | 60 + .../runway/icon/WebManifestEndpointTest.java | 76 + .../quest/runway/log/AccessLogFilterTest.java | 97 + .../quest/runway/log/AppActivityLogTest.java | 118 + .../runway/log/AppAuditEventListenerTest.java | 58 + .../runway/log/AuditEventListenerTest.java | 110 + .../mx/quest/runway/log/AuditJournalTest.java | 238 ++ .../runway/log/SiteInsightsServiceTest.java | 352 +++ .../quest/runway/log/SiteLogServiceTest.java | 164 + .../quest/runway/mail/PlatformMailerTest.java | 213 ++ .../runway/metrics/MetricsEndpointTest.java | 86 + .../metrics/PrometheusScrapeTokenTest.java | 83 + .../metrics/SiteRequestMetricsFilterTest.java | 90 + .../metrics/StorageDiskMetricsTest.java | 68 + .../mx/quest/runway/page/ContentUrlsTest.java | 135 + .../runway/page/LoadedSiteInputsTest.java | 499 +++ .../runway/page/LocaleNegotiatorTest.java | 54 + .../mx/quest/runway/page/LocaleUrlsTest.java | 106 + .../quest/runway/page/LocalizedPathTest.java | 166 + .../page/PageChangeEventEvictionTest.java | 150 + .../runway/page/PageReseedServiceTest.java | 113 + .../mx/quest/runway/page/PageRoutingTest.java | 136 + .../quest/runway/page/PageScaffoldTest.java | 49 + .../mx/quest/runway/page/PageStoreTest.java | 132 + .../java/mx/quest/runway/page/PageTest.java | 99 + .../runway/page/PageValidatorServiceTest.java | 533 ++++ .../quest/runway/page/PageValidatorTest.java | 71 + .../mx/quest/runway/page/PageViewsTest.java | 38 + .../quest/runway/page/PageWriteAuditTest.java | 87 + .../runway/page/PageWriteServiceTest.java | 354 +++ .../runway/page/PendingRevisionTest.java | 265 ++ .../page/PreviewScratchSweeperTest.java | 39 + .../runway/page/RenderModelBuilderTest.java | 165 + .../runway/platform/HostSettingsTest.java | 75 + .../KernelSettingsHostListGapTest.java | 58 + .../KernelSettingsInitializerTest.java | 134 + .../runway/platform/LogLevelServiceTest.java | 130 + .../platform/PlatformSettingsSmtpTest.java | 74 + .../platform/PlatformSettingsStoreTest.java | 169 + .../runway/platform/SchedulingConfigTest.java | 93 + .../platform/SchedulingWithBackupsTest.java | 27 + .../runway/platform/SettingsParityTest.java | 119 + .../runway/platform/TestPlatformSettings.java | 31 + .../plugin/ContainedSchedulingTest.java | 126 + .../runway/plugin/ContributionGuardTest.java | 216 ++ .../runway/plugin/EssentialAllowlistTest.java | 17 + .../plugin/EssentialFloorArmedTest.java | 70 + .../plugin/EssentialFloorArmingTest.java | 57 + .../plugin/EssentialFloorBrokenTest.java | 51 + .../plugin/EssentialFloorFilterTest.java | 90 + .../plugin/EssentialRepairAdviceTest.java | 168 + .../runway/plugin/HostLinkageScannerTest.java | 351 +++ .../runway/plugin/KernelBeanNamesTest.java | 65 + .../runway/plugin/PlaceholderTextTest.java | 70 + .../runway/plugin/PluginAdminServiceTest.java | 501 +++ .../plugin/PluginAssetCacheControlTest.java | 71 + .../runway/plugin/PluginClassLoaderTest.java | 34 + .../plugin/PluginContextInitializerTest.java | 112 + .../plugin/PluginContributionPolicyTest.java | 464 +++ .../plugin/PluginDescriptorParseTest.java | 198 ++ .../runway/plugin/PluginDiscoveryTest.java | 71 + .../PluginEventTierIntegrationTest.java | 282 ++ .../mx/quest/runway/plugin/PluginFixture.java | 196 ++ .../runway/plugin/PluginManagerTest.java | 135 + .../runway/plugin/PluginQuarantineTest.java | 290 ++ .../runway/plugin/PluginRequirementTest.java | 46 + .../runway/plugin/PluginResolutionTest.java | 344 ++ ...inScheduledContainmentIntegrationTest.java | 128 + .../PluginServiceTierIntegrationTest.java | 316 ++ .../PluginSettingsEtagIntegrationTest.java | 195 ++ .../plugin/PluginSettingsPlaceholderTest.java | 54 + .../plugin/PluginSettingsServiceTest.java | 193 ++ .../plugin/PluginStaticResourceTest.java | 98 + .../runway/plugin/PluginSurfaceCheckTest.java | 129 + .../runway/plugin/PluginVersionTest.java | 32 + .../runway/plugin/PluginWizardModeTest.java | 44 + .../runway/plugin/SecretBoundToTest.java | 290 ++ .../plugin/SettingTypeDecimalRangeTest.java | 37 + .../plugin/SitePluginConfigServiceTest.java | 190 ++ .../plugin/spi/PluginSettingsImplTest.java | 194 ++ .../plugin/spi/PluginSiteFilesImplTest.java | 288 ++ .../protect/EdgeProtectionConfigTest.java | 80 + .../runway/protect/EdgeRejectFilterTest.java | 78 + .../protect/EdgeRejectionRecorderTest.java | 284 ++ .../NoSiteLoginProtectionControlTest.java | 25 + .../runway/quality/CoreQualityChecksTest.java | 206 ++ .../quality/PageQualityCheckRegistryTest.java | 59 + .../quality/PageQualityServiceTest.java | 101 + .../recovery/PasswordRecoveryServiceTest.java | 269 ++ .../recovery/RecoveryTokenStoreTest.java | 100 + .../runway/reload/SiteReloadEndToEndTest.java | 276 ++ .../runway/reload/SiteReloadFilterTest.java | 93 + .../security/AccountStateFilterTest.java | 198 ++ .../security/AccountStatusChecksTest.java | 52 + .../runway/security/AppRealmSecurityTest.java | 112 + .../security/AppUserDetailsServiceTest.java | 64 + .../runway/security/AppUserStoreTest.java | 141 + ...ConcurrencyLimitedPasswordEncoderTest.java | 78 + .../runway/security/CsrfExpiryPageTest.java | 102 + .../security/FailClosedStartupTest.java | 44 + .../security/LoginProtectionFilterTest.java | 196 ++ .../LoginProtectionIntegrationTest.java | 119 + .../runway/security/PasswordEncodersTest.java | 44 + .../security/RealmCsrfIsolationTest.java | 99 + .../SecurityFilterMetricNamesTest.java | 56 + .../security/SecurityHardeningTest.java | 96 + .../security/SiteScopedRepositoriesTest.java | 106 + .../security/SiteUserDetailsServiceTest.java | 100 + .../security/TenantRealmSecurityTest.java | 135 + .../TenantSiteAuthorizationManagerTest.java | 113 + .../TrustedDeviceSuccessHandlerTest.java | 76 + .../quest/runway/security/UserStoreTest.java | 95 + .../mx/quest/runway/security/UserTest.java | 63 + .../security/UsernameUniquenessTest.java | 247 ++ .../seo/CanonicalHeadContributorTest.java | 111 + .../runway/seo/SeoConfigServiceTest.java | 86 + .../runway/seo/SeoHeadContributorTest.java | 154 + .../site/DefaultSiteMaintenanceTest.java | 88 + .../site/MaintenanceSiteFilterTest.java | 96 + .../runway/site/SeedTemplateStoreTest.java | 247 ++ .../mx/quest/runway/site/SiteBaseUrlTest.java | 33 + .../runway/site/SiteContextFilterTest.java | 63 + .../runway/site/SiteLifecycleServiceTest.java | 244 ++ .../runway/site/SiteParamsServiceTest.java | 115 + .../quest/runway/site/SiteResolverTest.java | 110 + .../quest/runway/site/SiteServicesK2Test.java | 101 + .../runway/site/SiteStorageCeilingsTest.java | 162 + .../mx/quest/runway/site/SiteStoreTest.java | 128 + .../java/mx/quest/runway/site/SiteTest.java | 81 + .../mx/quest/runway/site/SiteViewsTest.java | 37 + .../site/StarterTemplateRenderTest.java | 196 ++ .../runway/site/StaticFilesServiceTest.java | 239 ++ .../runway/site/SuspendedSiteFilterTest.java | 69 + .../quest/runway/site/TenantSeederTest.java | 159 + .../quest/runway/storage/AtomicFilesTest.java | 73 + .../storage/DataLayoutInitializerTest.java | 223 ++ .../quest/runway/storage/DataLayoutTest.java | 183 ++ .../quest/runway/storage/FileStampTest.java | 220 ++ .../runway/storage/OwnerOnlyFilesTest.java | 32 + .../runway/storage/PathSafetyFuzzTest.java | Bin 0 -> 5517 bytes .../storage/PathSafetyPagePathTest.java | Bin 0 -> 2092 bytes .../quest/runway/storage/PathSafetyTest.java | 68 + .../storage/RetiredStorageKeysTest.java | 85 + .../runway/storage/SiteFileStoreTest.java | 168 + .../runway/storage/StorageLayoutTest.java | 90 + .../runway/storage/StorageWiringTest.java | 36 + .../quest/runway/storage/StoreCacheTest.java | 130 + .../quest/runway/storage/YamlStoreTest.java | 142 + .../mx/quest/runway/storage/ZipsTest.java | 50 + ...AssetHeadContentLengthIntegrationTest.java | 88 + .../runway/web/AssetNotFoundLogTest.java | 105 + .../web/BufferingResponseWrapperTest.java | 97 + .../java/mx/quest/runway/web/CidrSetTest.java | 127 + .../runway/web/CompressionFilterTest.java | 175 ++ .../runway/web/ConfigOnDiskEditTest.java | 229 ++ .../ConsoleCacheControlIntegrationTest.java | 172 + .../runway/web/ConsoleHostEndToEndTest.java | 191 ++ .../runway/web/ConsoleHostFilterTest.java | 88 + .../web/ConsoleHostListEndToEndTest.java | 90 + .../ConsoleHostNoDefaultSiteEndToEndTest.java | 61 + .../web/ConsoleHostWizardEndToEndTest.java | 58 + .../mx/quest/runway/web/CspFilterTest.java | 519 +++ .../runway/web/CspHeaderBindingTest.java | 60 + .../quest/runway/web/CspNonceAdviceTest.java | 28 + .../mx/quest/runway/web/CspNonceE2ETest.java | 119 + .../runway/web/CspReportControllerTest.java | 119 + .../runway/web/CspScriptAllowlistTest.java | 194 ++ .../runway/web/EncodedPathEndToEndTest.java | 497 +++ .../web/EncodedPathFloorEndToEndTest.java | 60 + .../runway/web/FilterChainOrderTest.java | 120 + .../mx/quest/runway/web/FilterOrderTest.java | 110 + .../ForwardedHeaderCatchAllWarningTest.java | 44 + .../runway/web/ForwardedHeaderConfigTest.java | 35 + .../web/HttpToHttpsRedirectHandlerTest.java | 176 ++ .../runway/web/JettyFormLimitsConfigTest.java | 44 + .../quest/runway/web/KeystoreWatcherTest.java | 57 + .../runway/web/NoInlineScriptGuardTest.java | 113 + .../runway/web/PageConditionalGetTest.java | 138 + .../mx/quest/runway/web/PageErrorTest.java | 248 ++ .../runway/web/PageHeadInjectionTest.java | 255 ++ .../runway/web/PageLocaleLadderTest.java | 158 + .../runway/web/PageLocalizedPathTest.java | 199 ++ .../mx/quest/runway/web/PageServeTest.java | 222 ++ .../mx/quest/runway/web/PageWidgetTest.java | 160 + .../runway/web/PluginFilterPlacementTest.java | 68 + .../runway/web/PluginFilterRegistrarTest.java | 66 + .../runway/web/PublicPageNonceE2ETest.java | 507 +++ .../quest/runway/web/PublicPageNonceTest.java | 163 + .../java/mx/quest/runway/web/RawHttp.java | 118 + .../runway/web/RenderInputsEtagTest.java | 515 +++ .../mx/quest/runway/web/RenderSpikeTest.java | 175 ++ .../mx/quest/runway/web/RequestPathsTest.java | 121 + .../runway/web/RunwayCspPropertiesTest.java | 220 ++ .../runway/web/RunwayErrorControllerTest.java | 73 + .../web/RunwayHttpCachePropertiesTest.java | 86 + .../mx/quest/runway/web/SiteCspE2ETest.java | 218 ++ .../runway/web/SiteStaticControllerTest.java | 254 ++ .../runway/web/SiteTemplateIsolationTest.java | 208 ++ .../runway/web/SvgSandboxEndToEndTest.java | 113 + .../runway/web/TemplateCacheServiceTest.java | 195 ++ .../runway/web/TemplateOnDiskEditTest.java | 315 ++ .../TenantTemplateIsolationEndToEndTest.java | 212 ++ .../runway/web/ThymeleafBufferingTest.java | 32 + .../quest/runway/web/TlsIntegrationTest.java | 152 + .../mx/quest/runway/web/TlsStartupTest.java | 128 + .../web/TrustedForwardedHeaderFilterTest.java | 92 + .../quest/runway/web/UnmeteredPathsTest.java | 52 + .../quest/runway/web/WidgetFillSpikeTest.java | 82 + .../widget/ContentWidgetRegistryTest.java | 72 + .../WidgetInstanceConfigServiceTest.java | 192 ++ .../widget/WidgetInstanceDiscoveryTest.java | 62 + .../widget/WidgetModelBuilderConfigTest.java | 144 + .../runway/widget/WidgetScannerTest.java | 65 + .../widget/WidgetSettingsCatalogTest.java | 59 + .../runway/wizard/RestarterModeTest.java | 50 + .../wizard/SetupFormBodyLimitE2ETest.java | 108 + .../runway/wizard/WizardActiveModeTest.java | 77 + .../quest/runway/wizard/WizardModeTest.java | 95 + .../runway/wizard/WizardServiceTest.java | 167 + .../kernel-adopt-host/application.yml | 9 + .../runway/head/preload-corpus-chrome155.txt | 33 + .../test/resources/seed/demo/kettle/demo.yml | 20 + .../seed/demo/kettle/i18n/messages.properties | 1 + .../demo/kettle/i18n/messages_es.properties | 1 + .../demo/kettle/plugins/discoverability.yml | 2 + .../test/resources/seed/demo/kettle/seo.yml | 2 + .../seed/demo/kettle/static/css/site.css | 1 + .../seed/demo/kettle/templates/_master.html | 9 + .../seed/demo/kettle/templates/_master.th.xml | 4 + .../seed/demo/kettle/templates/index.html | 9 + .../seed/demo/kettle/templates/index.meta.yml | 5 + .../seed/demo/kettle/templates/index.th.xml | 6 + .../templates/operator/testkit-shell.html | 13 + .../templates/operator/testkit-shell.th.xml | 3 + .../src/test/resources/tls/test-keystore.p12 | Bin 0 -> 2632 bytes runway-dist/pom.xml | 171 + runway-dist/src/assembly/dist.xml | 102 + .../i18n/messages.properties | 124 + .../i18n/messages_es.properties | 124 + runway-plugin-protection/plugin.yml | 110 + runway-plugin-protection/pom.xml | 95 + .../protection/AppProtectionController.java | 84 + .../quest/protection/AppProtectionPanel.java | 75 + .../protection/CaptchaCspContributor.java | 38 + .../CaptchaLoginViewContributor.java | 138 + .../mx/quest/protection/CaptchaVerifier.java | 224 ++ .../protection/CaptchaWidgetService.java | 102 + .../mx/quest/protection/DosController.java | 150 + .../java/mx/quest/protection/IpBlocklist.java | 400 +++ .../protection/LoginFormPolicyGuard.java | 102 + .../mx/quest/protection/ProtectionConfig.java | 227 ++ .../protection/ProtectionConfigStore.java | 302 ++ .../mx/quest/protection/ProtectionForm.java | 80 + .../protection/ProtectionProperties.java | 263 ++ .../quest/protection/ProtectionSettings.java | 89 + .../ProtectionSiteLoginControl.java | 35 + .../quest/protection/RateLimitEdgeGuard.java | 96 + .../protection/SiteProtectionController.java | 100 + .../quest/protection/SiteVerifyResponse.java | 56 + .../protection/SlidingWindowLoginGate.java | 112 + .../mx/quest/protection/StoredBlocklist.java | 76 + .../mx/quest/protection/StoredProtection.java | 141 + .../protection/StoredSiteProtection.java | 60 + .../protection/TokenBucketRateLimiter.java | 180 ++ .../protection/TrustedDeviceService.java | 172 + .../protection/AppProtectionPanelTest.java | 96 + .../AutoBlockSettingsSchemaTest.java | 187 ++ .../CaptchaLoginProtectionFilterTest.java | 140 + .../CaptchaLoginViewContributorTest.java | 290 ++ .../quest/protection/CaptchaVerifierTest.java | 214 ++ .../protection/CaptchaWidgetServiceTest.java | 103 + .../mx/quest/protection/ConsoleA11yAudit.java | 213 ++ .../protection/DescriptorSpiFloorTest.java | 57 + .../quest/protection/DosScreenGatingTest.java | 193 ++ .../quest/protection/DosScreenRenderTest.java | 233 ++ .../mx/quest/protection/IpBlocklistTest.java | 279 ++ .../protection/LoginFormPolicyGuardTest.java | 254 ++ .../protection/MessageApostropheTest.java | 45 + .../protection/ProtectionAppScopeTest.java | 138 + .../protection/ProtectionConfigStoreTest.java | 277 ++ .../protection/ProtectionConfigTest.java | 128 + .../ProtectionConfigurationMetadataTest.java | 71 + .../ProtectionConsoleScreensTest.java | 43 + .../ProtectionControllerLogicTest.java | 199 ++ .../ProtectionDescriptorK4Test.java | 51 + .../quest/protection/ProtectionFormTest.java | 77 + .../ProtectionScreenGatingTest.java | 219 ++ .../ProtectionScreenRenderTest.java | 257 ++ .../protection/RateLimitEdgeGuardTest.java | 211 ++ .../RateLimiterAutoEscalationTest.java | 109 + .../SlidingWindowLoginGateTest.java | 96 + .../TokenBucketRateLimiterTest.java | 39 + .../protection/TrustedDeviceServiceTest.java | 264 ++ .../templates/admin-app.html | 77 + .../templates/admin-app.th.xml | 57 + .../templates/app-dos.html | 144 + .../templates/app-dos.th.xml | 70 + .../templates/site-protection.html | 77 + .../templates/site-protection.th.xml | 44 + runway-spi-testkit/pom.xml | 67 + .../runway/spi/testkit/EventDispatch.java | 172 + .../spi/testkit/FakeContentCatalog.java | 161 + .../spi/testkit/FakePluginSettings.java | 78 + .../runway/spi/testkit/FakeSiteServices.java | 157 + .../runway/spi/testkit/TempDirSiteFiles.java | 242 ++ .../runway/spi/testkit/package-info.java | 15 + .../spi/testkit/FakePluginSettingsTest.java | 50 + .../quest/runway/spi/testkit/K2FakesTest.java | 72 + .../quest/runway/spi/testkit/K3FakesTest.java | 139 + runway-spi/pom.xml | 69 + .../quest/runway/spi/BackupParticipant.java | 77 + .../mx/quest/runway/spi/CaptchaService.java | 58 + .../mx/quest/runway/spi/ContentSource.java | 199 ++ .../mx/quest/runway/spi/ContentWidget.java | 63 + .../quest/runway/spi/EndpointContributor.java | 78 + .../java/mx/quest/runway/spi/FilterBand.java | 38 + .../mx/quest/runway/spi/HeadContributor.java | 106 + .../mx/quest/runway/spi/PageQualityCheck.java | 61 + .../java/mx/quest/runway/spi/RunwaySpi.java | 116 + .../spi/SiteLoginProtectionControl.java | 51 + .../mx/quest/runway/spi/model/Alternate.java | 39 + .../quest/runway/spi/model/BackupReader.java | 31 + .../quest/runway/spi/model/BackupWriter.java | 27 + .../quest/runway/spi/model/Capabilities.java | 81 + .../quest/runway/spi/model/CaptchaWidget.java | 30 + .../quest/runway/spi/model/CatalogChange.java | 65 + .../quest/runway/spi/model/CatalogEntry.java | 79 + .../quest/runway/spi/model/ContentBody.java | 62 + .../mx/quest/runway/spi/model/ContentRef.java | 221 ++ .../mx/quest/runway/spi/model/FileEntry.java | 23 + .../mx/quest/runway/spi/model/Finding.java | 38 + .../quest/runway/spi/model/HeadContext.java | 88 + .../mx/quest/runway/spi/model/IconHints.java | 30 + .../quest/runway/spi/model/InstallResult.java | 38 + .../quest/runway/spi/model/LocalizedUrl.java | 58 + .../mx/quest/runway/spi/model/PageMeta.java | 86 + .../mx/quest/runway/spi/model/PageView.java | 31 + .../mx/quest/runway/spi/model/PluginInfo.java | 24 + .../mx/quest/runway/spi/model/Provenance.java | 70 + .../java/mx/quest/runway/spi/model/Realm.java | 22 + .../runway/spi/model/RenderFragment.java | 33 + .../java/mx/quest/runway/spi/model/Route.java | 75 + .../quest/runway/spi/model/RouteRequest.java | 134 + .../quest/runway/spi/model/RouteResponse.java | 49 + .../mx/quest/runway/spi/model/SeoTags.java | 51 + .../runway/spi/model/SettingsChange.java | 23 + .../quest/runway/spi/model/SettingsView.java | 196 ++ .../mx/quest/runway/spi/model/Severity.java | 19 + .../runway/spi/model/SiteLifecycleEvent.java | 48 + .../mx/quest/runway/spi/model/SiteRef.java | 19 + .../mx/quest/runway/spi/model/SiteView.java | 42 + .../quest/runway/spi/model/StarterPage.java | 37 + .../runway/spi/model/SurfacePosture.java | 33 + .../mx/quest/runway/spi/model/WidgetView.java | 70 + .../quest/runway/spi/model/package-info.java | 27 + .../mx/quest/runway/spi/package-info.java | 24 + .../quest/runway/spi/service/AccessCheck.java | 26 + .../runway/spi/service/ConsoleScreen.java | 56 + .../spi/service/ContentCatalogView.java | 93 + .../runway/spi/service/ContentChanges.java | 40 + .../mx/quest/runway/spi/service/Messages.java | 36 + .../runway/spi/service/PluginLifecycle.java | 41 + .../runway/spi/service/PluginSettings.java | 54 + .../runway/spi/service/PluginSiteFiles.java | 113 + .../runway/spi/service/RequestContext.java | 28 + .../runway/spi/service/SiteEventListener.java | 101 + .../quest/runway/spi/service/SitePages.java | 56 + .../mx/quest/runway/spi/service/Sites.java | 24 + .../runway/spi/service/package-info.java | 31 + .../runway/spi/ContentSourceDefaultsTest.java | 65 + .../mx/quest/runway/spi/RunwaySpiTest.java | 22 + .../mx/quest/runway/spi/SpiContractTest.java | 227 ++ .../runway/spi/model/BoundaryRecordsTest.java | 321 ++ .../runway/spi/model/CapabilitiesTest.java | 90 + .../runway/spi/model/ContentRefTest.java | 148 + .../quest/runway/spi/model/FactoriesTest.java | 117 + .../quest/runway/spi/model/K2RecordsTest.java | 118 + .../quest/runway/spi/model/K3RecordsTest.java | 150 + .../quest/runway/spi/model/K4RecordsTest.java | 75 + .../runway/spi/model/SettingsViewTest.java | 138 + scripts/dev/gen-kernel-settings.py | 131 + scripts/dev/gen-settings-reference.py | 183 ++ scripts/dev/settings-homes.yml | 83 + scripts/install.sh | 637 ++++ scripts/make-release-aliases.sh | 54 + scripts/make-selfextract.sh | 99 + scripts/make-spi-assets.sh | 136 + scripts/plugin-seed.sh | 155 + scripts/release-notes.sh | 56 + scripts/runway.service | 45 + scripts/runway.sh | 186 ++ scripts/selfextract-stub.sh | 54 + scripts/test-install-config.sh | 148 + scripts/test-plugin-seed.sh | 215 ++ scripts/test-release-assets.sh | 165 + scripts/test-release-notes.sh | 130 + 1372 files changed, 188168 insertions(+) create mode 100644 .gitignore create mode 100644 .mvn/jvm.config create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 LICENSE-EXCEPTION create mode 100644 README.md create mode 100644 THIRD-PARTY-NOTICES create mode 100644 docs/ADMINISTRATION.md create mode 100644 docs/CONFIGURATION-AND-DATA-STABILITY.md create mode 100644 docs/GLOSSARY.md create mode 100644 docs/KNOWN-LIMITATIONS.md create mode 100644 docs/OPERATIONS.md create mode 100644 docs/PLUGIN-DEVELOPMENT.md create mode 100644 docs/README.md create mode 100644 docs/SETTINGS-REFERENCE.md create mode 100644 docs/SITE-MANAGER-GUIDE.md create mode 100644 docs/SPI-STABILITY.md create mode 100644 frontend/codemirror/.gitignore create mode 100755 frontend/codemirror/build.sh create mode 100644 frontend/codemirror/codemirror.css create mode 100644 frontend/codemirror/entry.mjs create mode 100644 frontend/codemirror/package-lock.json create mode 100644 frontend/codemirror/package.json create mode 100644 monitoring/README.md create mode 100644 monitoring/runway-grafana-dashboard.json create mode 100644 monitoring/runway-prometheus-alerts.yml create mode 100644 plugins/README.md create mode 100644 plugins/demo/.gitignore create mode 100644 plugins/demo/CHANGELOG.md create mode 100644 plugins/demo/LICENSE create mode 100644 plugins/demo/NOTICE create mode 100644 plugins/demo/README.md create mode 100644 plugins/demo/docs/DEMO-PLUGIN.md create mode 100644 plugins/demo/docs/PLUGIN-AUTHORING-GUIDE.md create mode 100644 plugins/demo/i18n/messages.properties create mode 100644 plugins/demo/i18n/messages_es.properties create mode 100644 plugins/demo/plugin.yml create mode 100644 plugins/demo/pom.xml create mode 100755 plugins/demo/scripts/install-into.sh create mode 100755 plugins/demo/scripts/verify-against-host.sh create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoActivity.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoAdminModel.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoAnalyticsHead.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoAppProps.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoConsoleController.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoEndpoints.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoFeedbackWidget.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoLifecycle.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoMetaLengthCheck.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoNotesStore.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoNoticeWidget.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoPluginConfig.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoShowcaseSource.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/DemoShowcaseStore.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/Html.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/Note.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/NotesFile.java create mode 100644 plugins/demo/src/main/java/mx/quest/demo/Showcase.java create mode 100644 plugins/demo/src/test/java/mx/quest/demo/DemoActivityTest.java create mode 100644 plugins/demo/src/test/java/mx/quest/demo/DemoConsoleControllerTest.java create mode 100644 plugins/demo/src/test/java/mx/quest/demo/DemoNotesStoreTest.java create mode 100644 plugins/demo/src/test/java/mx/quest/demo/DemoPluginConfigTest.java create mode 100644 plugins/demo/src/test/java/mx/quest/demo/DemoShowcaseTest.java create mode 100644 plugins/demo/src/test/java/mx/quest/demo/DemoSpiUnitTest.java create mode 100644 plugins/demo/src/test/java/mx/quest/demo/DemoTemplatesTest.java create mode 100644 plugins/demo/static/css/demo.css create mode 100644 plugins/demo/static/js/demo-analytics.js create mode 100644 plugins/demo/static/notes-help.html create mode 100644 plugins/demo/templates/admin.html create mode 100644 plugins/demo/templates/admin.th.xml create mode 100644 plugins/demo/templates/console.html create mode 100644 plugins/demo/templates/console.th.xml create mode 100644 plugins/demo/templates/dashboard.html create mode 100644 plugins/demo/templates/dashboard.th.xml create mode 100644 plugins/demo/templates/showcase.html create mode 100644 plugins/demo/templates/showcase.th.xml create mode 100644 plugins/docs/PLUGIN-AUTHORING-GUIDE.md create mode 100644 plugins/lucene-provider/CHANGELOG.md create mode 100644 plugins/lucene-provider/LICENSE create mode 100644 plugins/lucene-provider/LICENSE-EXCEPTION create mode 100644 plugins/lucene-provider/README.md create mode 100644 plugins/lucene-provider/docs/LUCENE-PROVIDER-PLUGIN.md create mode 100644 plugins/lucene-provider/plugin.yml create mode 100644 plugins/lucene-provider/pom.xml create mode 100644 plugins/search-lucene/CHANGELOG.md create mode 100644 plugins/search-lucene/LICENSE create mode 100644 plugins/search-lucene/LICENSE-EXCEPTION create mode 100644 plugins/search-lucene/README.md create mode 100644 plugins/search-lucene/docs/SEARCH-LUCENE-PLUGIN.md create mode 100644 plugins/search-lucene/i18n/messages.properties create mode 100644 plugins/search-lucene/i18n/messages_es.properties create mode 100644 plugins/search-lucene/plugin.yml create mode 100644 plugins/search-lucene/pom.xml create mode 100755 plugins/search-lucene/scripts/verify-against-host.sh create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/HtmlText.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/LocaleAnalyzers.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/LuceneAdminModel.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/LuceneSearchEngine.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/LuceneSiteEvents.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/LuceneStorageProps.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/MatchedForms.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/RankingConfig.java create mode 100644 plugins/search-lucene/src/main/java/mx/quest/searchlucene/SearchLuceneConfig.java create mode 100644 plugins/search-lucene/src/test/java/mx/quest/searchlucene/LucenePerLanguageTest.java create mode 100644 plugins/search-lucene/src/test/java/mx/quest/searchlucene/LuceneSearchEngineTest.java create mode 100644 plugins/search-lucene/src/test/java/mx/quest/searchlucene/LuceneStoragePropsTest.java create mode 100644 plugins/search-lucene/src/test/java/mx/quest/searchlucene/RankingConfigTest.java create mode 100644 plugins/search-lucene/src/test/java/mx/quest/searchlucene/SearchLuceneConfigTest.java create mode 100644 plugins/search-lucene/templates/admin.html create mode 100644 plugins/search-lucene/templates/admin.th.xml create mode 100644 plugins/search-lucene/templates/dashboard.html create mode 100644 plugins/search-lucene/templates/dashboard.th.xml create mode 100644 plugins/search/CHANGELOG.md create mode 100644 plugins/search/LICENSE create mode 100644 plugins/search/LICENSE-EXCEPTION create mode 100644 plugins/search/README.md create mode 100644 plugins/search/docs/SEARCH-PLUGIN.md create mode 100644 plugins/search/i18n/messages.properties create mode 100644 plugins/search/i18n/messages_es.properties create mode 100644 plugins/search/plugin.yml create mode 100644 plugins/search/pom.xml create mode 100755 plugins/search/scripts/verify-against-host.sh create mode 100644 plugins/search/src/main/java/mx/quest/search/HighlightMarker.java create mode 100644 plugins/search/src/main/java/mx/quest/search/Html.java create mode 100644 plugins/search/src/main/java/mx/quest/search/HtmlText.java create mode 100644 plugins/search/src/main/java/mx/quest/search/MatchedWords.java create mode 100644 plugins/search/src/main/java/mx/quest/search/NoResultsLog.java create mode 100644 plugins/search/src/main/java/mx/quest/search/ResultsPageLinks.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchAdminModel.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchBoxWidget.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchClientId.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchConfig.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchDocument.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchEndpoint.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchHighlightHead.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchProperties.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchRateLimiter.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchSiteConfig.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchSiteEvents.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SearchSnippet.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SimpleSearchEngine.java create mode 100644 plugins/search/src/main/java/mx/quest/search/SiteSearchCorpus.java create mode 100644 plugins/search/src/main/java/mx/quest/search/spi/SearchCorpus.java create mode 100644 plugins/search/src/main/java/mx/quest/search/spi/SearchHit.java create mode 100644 plugins/search/src/main/java/mx/quest/search/spi/SearchQuery.java create mode 100644 plugins/search/src/main/java/mx/quest/search/spi/SiteSearchEngine.java create mode 100644 plugins/search/src/test/java/mx/quest/search/Fixtures.java create mode 100644 plugins/search/src/test/java/mx/quest/search/HighlightTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/HtmlTextTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/MutableClock.java create mode 100644 plugins/search/src/test/java/mx/quest/search/NoResultsLogTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/NoResultsRecordingTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SearchAdminModelTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SearchAdminTemplateTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SearchBoxWidgetTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SearchConfigTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SearchEndpointTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SearchRateLimiterTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SearchSnippetTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SimpleSearchEngineTest.java create mode 100644 plugins/search/src/test/java/mx/quest/search/SiteSearchCorpusTest.java create mode 100644 plugins/search/src/test/js/highlight-pattern.js create mode 100644 plugins/search/static/highlight-loader.js create mode 100644 plugins/search/static/highlight.css create mode 100644 plugins/search/static/highlight.js create mode 100644 plugins/search/static/search-help.html create mode 100644 plugins/search/static/search.css create mode 100644 plugins/search/templates/admin.html create mode 100644 plugins/search/templates/admin.th.xml create mode 100644 plugins/search/templates/dashboard.html create mode 100644 plugins/search/templates/dashboard.th.xml create mode 100644 pom.xml create mode 100644 runway-app/pom.xml create mode 100644 runway-app/src/main/java/mx/quest/runway/RunwayApplication.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/AuthorizationAdminService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/AuthorizationService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/AuthzExpressions.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/AuthzStoreIntegrity.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/AuthzWebConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/GrantFile.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/GrantStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/MethodSecurityConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/Permission.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/PermissionAuthorizationManager.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/PermissionCatalog.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/Permissions.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/PluginPermissionContributions.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/QuarantinedSiteFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/RequestAuthorizers.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/ReservedRoles.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/Role.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/RoleFile.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/RoleGraph.java create mode 100644 runway-app/src/main/java/mx/quest/runway/authz/RoleStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/BackupConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/BackupManifest.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/BackupParticipantRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/BackupProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/BackupRestoreRecovery.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/BackupService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/ScheduledBackupConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/ScheduledBackupRunner.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/UnsupportedBackupFormatException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/backup/ZipBackup.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/BandwidthConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/BandwidthFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/BandwidthLimitFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/BandwidthProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/BandwidthService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/Bytes.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/CountingResponseWrapper.java create mode 100644 runway-app/src/main/java/mx/quest/runway/bandwidth/SiteBandwidthQuotas.java create mode 100644 runway-app/src/main/java/mx/quest/runway/cluster/ClusterConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/cluster/ClusterEventEnvelope.java create mode 100644 runway-app/src/main/java/mx/quest/runway/cluster/ClusterEventRelay.java create mode 100644 runway-app/src/main/java/mx/quest/runway/cluster/HazelcastSessionRepository.java create mode 100644 runway-app/src/main/java/mx/quest/runway/cluster/RunwayClusterProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AbstractPermissionsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AccountSupport.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AdminHomeController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppAboutController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppAccountController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppBackupsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppBandwidthController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppEmbedHostsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppHomeController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppLogLevelsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppLoginController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppLogsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppPermissionsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppRecoveryController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppSettingsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AppUsersController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AssetCachePolicy.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AssetVersion.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/AuditView.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/BandwidthController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/ConsoleNavigation.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/ConsoleScreenAdvice.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/ConsoleUserService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/DashboardCardRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/DocumentsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/HeadFieldRules.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/IconsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/KernelSettingsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/LogsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/MaintenanceController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/MenuRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorAssetsConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorAwareMessageSource.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorI18nConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorLocaleController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorLocaleResolver.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorMessageSource.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorModelAdvice.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorPaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorShellModel.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/OperatorTemplatingConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PageForm.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PermissionLabelResolver.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PermissionsMatrixService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PlatformAdminModelAdvice.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PlatformAuthority.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PluginAdminController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PluginSettingsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/PluginTemplateResolver.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/RuntimeInfoService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SeoController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SettingField.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SettingOption.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SettingRefusals.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SettingSection.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SettingsForm.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SiteConfigInput.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SiteInsightsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SiteMastersController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SiteTemplatesController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SiteUserAuthority.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/SitesController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantAccountController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantAuthority.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantBackupsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantFragmentsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantMessagesController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantPageActionsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantPageEditorController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantPageNewController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantPagePreviewController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantPagesController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantPermissionsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantPluginSettingsController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantRecoveryController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantReviewController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantSiteConfigController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantStaticFilesController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/TenantUsersController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/WidgetInstancesController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/console/WrongPasswordCounter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/ContentCatalog.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/ContentCatalogViewImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/ContentChangedEvent.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/ContentChangesImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/ContentRouter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/ContentSourceRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/PagesContentSource.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/PathOwnership.java create mode 100644 runway-app/src/main/java/mx/quest/runway/content/RoutableContent.java create mode 100644 runway-app/src/main/java/mx/quest/runway/crypto/AesGcmSecretCipher.java create mode 100644 runway-app/src/main/java/mx/quest/runway/crypto/SecretCipher.java create mode 100644 runway-app/src/main/java/mx/quest/runway/demo/DemoDescriptor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/demo/DemoSiteInstaller.java create mode 100644 runway-app/src/main/java/mx/quest/runway/demo/FirstRunDemoInstaller.java create mode 100644 runway-app/src/main/java/mx/quest/runway/document/DisabledDocumentsGuard.java create mode 100644 runway-app/src/main/java/mx/quest/runway/document/DocumentService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/editorial/EditorialException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/editorial/EditorialService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/editorial/LineDiff.java create mode 100644 runway-app/src/main/java/mx/quest/runway/editorial/PageStatus.java create mode 100644 runway-app/src/main/java/mx/quest/runway/editorial/SitePagesImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/AnonymousRouteMatcher.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/BoundedBodyRequest.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/CapturedFormRequest.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/EndpointContributorRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/EndpointDispatchConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/EndpointDispatchFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/PreAuthBodyLimit.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/PreAuthBodyLimitFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/RouteAwareFormContentFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/endpoint/RouteFormCaptureFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/event/ClusterReplay.java create mode 100644 runway-app/src/main/java/mx/quest/runway/event/HostWriteScope.java create mode 100644 runway-app/src/main/java/mx/quest/runway/event/KernelEventOrder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/event/SpiEventBridge.java create mode 100644 runway-app/src/main/java/mx/quest/runway/head/HeadContributorRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/head/HeadInjectionConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/head/HeadInjectionFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/head/ScriptNonceStamper.java create mode 100644 runway-app/src/main/java/mx/quest/runway/head/ScriptPreloadStripper.java create mode 100644 runway-app/src/main/java/mx/quest/runway/head/ValidatorHoldingResponse.java create mode 100644 runway-app/src/main/java/mx/quest/runway/health/HealthProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/health/SiteContentReadiness.java create mode 100644 runway-app/src/main/java/mx/quest/runway/health/SiteHealth.java create mode 100644 runway-app/src/main/java/mx/quest/runway/health/SiteHealthConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/health/SiteHealthFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/health/SiteHealthService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/health/StorageHealthIndicator.java create mode 100644 runway-app/src/main/java/mx/quest/runway/i18n/I18nProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/i18n/MessageSourceWiring.java create mode 100644 runway-app/src/main/java/mx/quest/runway/i18n/MessagesImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/i18n/SiteAwareMessageSource.java create mode 100644 runway-app/src/main/java/mx/quest/runway/i18n/SiteMessagesStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/i18n/package-info.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/IconGenerationService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/IconHeadContributor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/IconRasterizer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/SiteIcon.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/SiteIconEndpoints.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/SiteIconService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/SiteManifest.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/SiteManifestService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/TenantIconSeeder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/icon/WebManifestEndpoint.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AccessLogConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AccessLogFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AppActivityLog.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AppActivityLogProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AppAuditEventListener.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AuditEntry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AuditEventListener.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AuditJournal.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AuditPage.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/AuditQuery.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/LogKind.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/LogProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/SiteInsightsService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/SiteLogConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/SiteLogConfigService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/log/SiteLogService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/mail/JakartaMailTransport.java create mode 100644 runway-app/src/main/java/mx/quest/runway/mail/MailTransport.java create mode 100644 runway-app/src/main/java/mx/quest/runway/mail/PlatformMailer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/metrics/KernelMetrics.java create mode 100644 runway-app/src/main/java/mx/quest/runway/metrics/MetricsConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/metrics/MetricsProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/metrics/PrometheusScrapeAuthFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/metrics/SiteRequestMetricsFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/CanonicalFingerprint.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/ChromeTemplateFold.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/ContentUrls.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/FragmentException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/FragmentTemplates.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/LoadedSiteInputs.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/LocaleNegotiator.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/LocaleOption.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/LocaleUrls.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/MasterTemplates.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/Page.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageAuthoringException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageAuthoringValidator.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageCacheInvalidationListener.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageChangedEvent.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageReseedService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageReview.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageRouting.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageScaffold.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageValidator.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageValidatorService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageViews.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PageWriteService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PendingRevisionStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/PreviewScratchSweeper.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/RenderModelBuilder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/Routable.java create mode 100644 runway-app/src/main/java/mx/quest/runway/page/package-info.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/EmbedHostService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/HostSettings.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/KernelSettings.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/KernelSettingsInitializer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/KernelSettingsService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/LogLevelService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/PlatformSettings.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/PlatformSettingsStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/platform/SchedulingConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/ContainedSchedulingPostProcessor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/ContributionGuard.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/EssentialAllowlist.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/EssentialFloor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/EssentialFloorFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/HostLinkageScanner.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/LoadedPlugin.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PlaceholderText.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginAdminService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginCardDecl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginCompliance.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginContextInitializer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginDescriptor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginInstallation.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginLoader.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginManager.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginMenuDecl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginOwnership.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginPermissionDecl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginQuarantine.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginQuarantineListener.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginRequirement.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginResolution.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginRuntime.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginScopedServices.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginSettingDef.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginSettingGroup.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginSettingsService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginSiteData.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginStaticResourceConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginStatus.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginSurfaceCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginVersion.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/PluginWebConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/RunningPlugins.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/SecretBindings.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/SettingKeyListDeserializer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/SettingType.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/SettingValidationException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/SitePluginConfigChangedEvent.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/SitePluginConfigService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/spi/PluginSettingsImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/plugin/spi/PluginSiteFilesImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/EdgeGuard.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/EdgeProtectionConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/EdgeProtectionProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/EdgeRejectFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/EdgeRejectionRecorder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/EdgeRequest.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/EdgeVerdict.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/NoCaptchaService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/NoSiteLoginProtectionControl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/PermissiveEdgeGuard.java create mode 100644 runway-app/src/main/java/mx/quest/runway/protect/RejectionOutcome.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/DescriptionCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/DuplicateMetaCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/HeadingStructureCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/ImageAltCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/LinkTextCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/PageQualityCheckRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/PageQualityService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/QualityGate.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/QualityReport.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/RenderedHtml.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/ThinContentCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/quality/TitlePresenceCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/recovery/PasswordRecoveryService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/recovery/RecoveryToken.java create mode 100644 runway-app/src/main/java/mx/quest/runway/recovery/RecoveryTokenStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/reload/ReloadProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/reload/SiteReloadConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/reload/SiteReloadFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/reload/SiteReloadService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/reload/SiteReloadStartupCheck.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/AccountStateFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/AccountStatusChecks.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/ActivePasswordStrength.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/AppSecurityConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/AppUserDetailsService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/AppUserStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/ConcurrencyLimitedPasswordEncoder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/CsrfExpiryAccessDeniedHandler.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/LoginAttemptEventListener.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/LoginAttemptGate.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/LoginFormGuard.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/LoginFormVerdict.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/LoginProtectionConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/LoginProtectionFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/NoTrustedDeviceIssuer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/PasswordEncoders.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/PasswordHashingBusyException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/PasswordStrength.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/PermissiveLoginAttemptGate.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/PermissiveLoginFormGuard.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/ProtectionScope.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/RealmActivation.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/Roles.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/RunwaySecurityProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/RunwayUserDetails.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/SecurityConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/SecurityHeaders.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/SiteScopedCsrfTokenRepository.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/SiteScopedSecurityContextRepository.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/SiteUserDetailsService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/SiteUserStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/TenantConsoleController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/TenantMasterStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/TenantProvisioning.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/TenantSecurityConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/TenantSiteAuthorizationManager.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/TrustedDeviceIssuer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/TrustedDeviceSuccessHandler.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/User.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/UserFile.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/UserStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/security/UsernameTakenException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/seo/CanonicalHeadContributor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/seo/SeoConfigService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/seo/SeoHeadContributor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/seo/SiteSeoConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/DefaultSiteMaintenance.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/EditorialLevel.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/MaintenanceSiteFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SeedTemplateStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/Site.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteBaseUrl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteChangedEvent.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteContact.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteContactService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteContextFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteCspService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteHosts.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteLifecycleService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteParamsService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteResolver.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteStatus.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteStorageCeilings.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteViews.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SiteWebConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SitesImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/StaticFilesService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/SuspendedSiteFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/TenantSeeder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/site/package-info.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/AtomicFiles.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/DataLayout.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/DataLayoutException.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/DataLayoutFailureAnalyzer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/DataLayoutInitializer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/FileStamp.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/OwnerOnlyFiles.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/PathSafety.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/RetiredStorageKeys.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/SiteFileStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/StorageConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/StorageLayout.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/StorageProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/StoreCache.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/UploadNames.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/Yaml.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/YamlStore.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/Zips.java create mode 100644 runway-app/src/main/java/mx/quest/runway/storage/package-info.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/AppRealmPaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/BufferingResponseWrapper.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CidrSet.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/ClientIp.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CompressionConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CompressionFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/ConsoleHostConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/ConsoleHostFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/ConsoleHostProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CspConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CspFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CspHostContributor.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CspNonceAdvice.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CspReportController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/CspScriptAllowlist.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/DraftRenderer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/ErrorPages.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/FileStampValidity.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/FilterContribution.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/FilterOrder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/ForwardedHeaderConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/HttpCacheConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/HttpToHttpsRedirectHandler.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/JettyFormLimitsConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/KeystoreWatcher.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/LogSafe.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/MultipartCsrfConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/PageController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/PageRenderer.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/PluginFilterPlacement.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/PluginFilterRegistrar.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/PublicPageNonce.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RequestContextImpl.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RequestOrigin.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RequestPaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/ReservedPaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RunwayCompressionProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RunwayCspProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RunwayErrorController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RunwayHttpCacheProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RunwayProxyProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/RunwayTlsProperties.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/SiteCspPolicies.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/SiteHealthPaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/SiteReloadPaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/SiteStaticController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/SiteStaticGuard.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/SiteTemplateResolver.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/TemplateCacheService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/TemplatingConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/TenantConsolePaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/TlsCertificateReloader.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/TlsConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/TlsStartup.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/TrustedForwardedHeaderFilter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/UnmeteredPaths.java create mode 100644 runway-app/src/main/java/mx/quest/runway/web/WidgetAwareDecoupledLogicResolver.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/ContentWidgetRegistry.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/WidgetBinding.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/WidgetInstanceConfigService.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/WidgetInstanceDiscovery.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/WidgetModelBuilder.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/WidgetScanner.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/WidgetSettingsCatalog.java create mode 100644 runway-app/src/main/java/mx/quest/runway/widget/WidgetWiring.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/ActiveModeCondition.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/ActiveRestarter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/Restarter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/SupervisedRestarter.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/WizardController.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/WizardModeCondition.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/WizardSecurityConfig.java create mode 100644 runway-app/src/main/java/mx/quest/runway/wizard/WizardService.java create mode 100644 runway-app/src/main/resources/META-INF/additional-spring-configuration-metadata.json create mode 100644 runway-app/src/main/resources/META-INF/spring.factories create mode 100644 runway-app/src/main/resources/application.yml create mode 100644 runway-app/src/main/resources/codemirror.version create mode 100644 runway-app/src/main/resources/i18n/operator-messages.properties create mode 100644 runway-app/src/main/resources/i18n/operator-messages_es.properties create mode 100644 runway-app/src/main/resources/kernel-settings.yml create mode 100644 runway-app/src/main/resources/seed/site-icons/favicon.svg create mode 100644 runway-app/src/main/resources/seed/site/_master.html create mode 100644 runway-app/src/main/resources/seed/site/_master.th.xml create mode 100644 runway-app/src/main/resources/seed/site/about.html create mode 100644 runway-app/src/main/resources/seed/site/about.meta.yml create mode 100644 runway-app/src/main/resources/seed/site/about.th.xml create mode 100644 runway-app/src/main/resources/seed/site/index.html create mode 100644 runway-app/src/main/resources/seed/site/index.meta.yml create mode 100644 runway-app/src/main/resources/seed/site/index.th.xml create mode 100644 runway-app/src/main/resources/static/captcha-v3.js create mode 100644 runway-app/src/main/resources/static/listing-tables.css create mode 100644 runway-app/src/main/resources/static/listing-tables.js create mode 100644 runway-app/src/main/resources/static/messages.js create mode 100644 runway-app/src/main/resources/static/page-editor.js create mode 100644 runway-app/src/main/resources/static/restarting.js create mode 100644 runway-app/src/main/resources/static/runway-chrome.css create mode 100644 runway-app/src/main/resources/static/runway-chrome.js create mode 100644 runway-app/src/main/resources/static/runway.svg create mode 100644 runway-app/src/main/resources/static/vendor/alpine.min.js create mode 100644 runway-app/src/main/resources/static/vendor/chart.min.js create mode 100644 runway-app/src/main/resources/static/vendor/codemirror.min.css create mode 100644 runway-app/src/main/resources/static/vendor/codemirror.min.js create mode 100644 runway-app/src/main/resources/static/vendor/fontawesome/css/all.min.css create mode 100644 runway-app/src/main/resources/static/vendor/fontawesome/webfonts/fa-brands-400.woff2 create mode 100644 runway-app/src/main/resources/static/vendor/fontawesome/webfonts/fa-regular-400.woff2 create mode 100644 runway-app/src/main/resources/static/vendor/fontawesome/webfonts/fa-solid-900.woff2 create mode 100644 runway-app/src/main/resources/static/vendor/fontawesome/webfonts/fa-v4compatibility.woff2 create mode 100644 runway-app/src/main/resources/static/vendor/htmx.min.js create mode 100644 runway-app/src/main/resources/static/vendor/tabler.min.css create mode 100644 runway-app/src/main/resources/static/vendor/tabler.min.js create mode 100644 runway-app/src/main/resources/templates/operator/account.html create mode 100644 runway-app/src/main/resources/templates/operator/account.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/backups.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/backups.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/bandwidth.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/bandwidth.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/documents.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/documents.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/fragment-editor.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/fragment-editor.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/fragments.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/fragments.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/home.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/home.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/icons.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/icons.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/insights.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/insights.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/logs.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/logs.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/maintenance.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/maintenance.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/messages.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/messages.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/page-editor.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/page-editor.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/page-new.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/page-new.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/pages.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/pages.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/review-item.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/review-item.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/review.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/review.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/seo.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/seo.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/site-config.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/site-config.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/static-files.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/static-files.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/users.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/users.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/web-manifest.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/web-manifest.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/admin/widget-instances.html create mode 100644 runway-app/src/main/resources/templates/operator/admin/widget-instances.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/about.html create mode 100644 runway-app/src/main/resources/templates/operator/app/about.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/backups.html create mode 100644 runway-app/src/main/resources/templates/operator/app/backups.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/bandwidth.html create mode 100644 runway-app/src/main/resources/templates/operator/app/bandwidth.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/embed-hosts.html create mode 100644 runway-app/src/main/resources/templates/operator/app/embed-hosts.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/home.html create mode 100644 runway-app/src/main/resources/templates/operator/app/home.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/log-levels.html create mode 100644 runway-app/src/main/resources/templates/operator/app/log-levels.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/logs.html create mode 100644 runway-app/src/main/resources/templates/operator/app/logs.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/masters.html create mode 100644 runway-app/src/main/resources/templates/operator/app/masters.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/plugins.html create mode 100644 runway-app/src/main/resources/templates/operator/app/plugins.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/settings.html create mode 100644 runway-app/src/main/resources/templates/operator/app/settings.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/site-template-edit.html create mode 100644 runway-app/src/main/resources/templates/operator/app/site-template-edit.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/site-template-files.html create mode 100644 runway-app/src/main/resources/templates/operator/app/site-template-files.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/site-templates.html create mode 100644 runway-app/src/main/resources/templates/operator/app/site-templates.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/sites.html create mode 100644 runway-app/src/main/resources/templates/operator/app/sites.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/app/users.html create mode 100644 runway-app/src/main/resources/templates/operator/app/users.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/audit-journal.html create mode 100644 runway-app/src/main/resources/templates/operator/audit-journal.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/fragments/admin-topbar.html create mode 100644 runway-app/src/main/resources/templates/operator/fragments/admin-topbar.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/fragments/app-topbar.html create mode 100644 runway-app/src/main/resources/templates/operator/fragments/app-topbar.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/login-app.html create mode 100644 runway-app/src/main/resources/templates/operator/login-app.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/login-tenant.html create mode 100644 runway-app/src/main/resources/templates/operator/login-tenant.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/op-layout.html create mode 100644 runway-app/src/main/resources/templates/operator/op-layout.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/permissions.html create mode 100644 runway-app/src/main/resources/templates/operator/permissions.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/plugin-settings.html create mode 100644 runway-app/src/main/resources/templates/operator/plugin-settings.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/recovery-forgot.html create mode 100644 runway-app/src/main/resources/templates/operator/recovery-forgot.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/recovery-reset.html create mode 100644 runway-app/src/main/resources/templates/operator/recovery-reset.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/restarting.html create mode 100644 runway-app/src/main/resources/templates/operator/restarting.th.xml create mode 100644 runway-app/src/main/resources/templates/operator/setting-row.html create mode 100644 runway-app/src/main/resources/templates/operator/setting-row.th.xml create mode 100644 runway-app/src/test/java/mx/quest/runway/ConfigurationMetadataTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/AuthorizationAdminServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/AuthorizationServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/AuthzExpressionsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/AuthzStoreIntegrityTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/GrantWriteConcurrencyTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/MethodSecurityIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/PermissionAuthorizationManagerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/PermissionCatalogTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/PermissionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/PluginPermissionMergeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/QuarantinedSiteFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/RoleDeltaTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/RoleGraphTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/authz/RoleStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/BackupFormatVersionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/BackupParticipantRegistryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/BackupRestoreRecoveryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/BackupRetentionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/BackupServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/DemoExportRestoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/ScheduledAndOffsiteBackupTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/TransferExportTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/TransferPersonalDataTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/backup/ZipBackupEntryNameTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthLimitFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/bandwidth/CountingResponseWrapperTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/cluster/ClusterActiveModeGatingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/cluster/ClusterDisabledByDefaultTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/cluster/ClusterEnabledActiveTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTwoNodeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/cluster/HazelcastSessionRepositoryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/cluster/SessionPrincipalSerializationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AccountPasswordCheckLimitTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AccountProfileTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AccountScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppAboutPageTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppBackupsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppBandwidthScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppConsolePermissionsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppLogLevelsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppLogsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppSettingsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppSiteEditScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppSiteHostsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppSiteQuotaTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppUserEditSuspendTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AppUsersAndMastersTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AssetCachePolicyTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AssetVersionAudit.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/AuditViewTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/BackupFormatMessagesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/BandwidthScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/CompressionHostLockTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/ConsoleMessagesInSpanishTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/ConsoleNavigationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/ConsoleNavigationVisibilityTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/ConsoleUserServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/DocumentsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/EditorialWorkflowScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/FragmentsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/IconsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/KernelSettingsAdoptTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/KernelSettingsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/LogsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/MaintenanceScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/MenuAndDashboardTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/MessageApostropheTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/MessagesScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorA11yAudit.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorA11yAuditTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorA11yGuardTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorLocaleResolverTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorLocaleSwitcherTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorMessagePluginI18nTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorPathsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorShellModelTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorShellTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorSpanishRegisterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/OperatorTemplateIdGuardTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PageActionsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PageEditorScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PageEditorScriptsSeamTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PageFormTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PageNewScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PagePreviewI18nTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PagePreviewScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PageRenameScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PasswordChangeEndsSessionsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PermissionLabelResolverTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PermissionsMatrixTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PluginAdminScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PluginFragmentTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PluginHealthScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PluginPermissionEnforcementTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PluginSettingsFormTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/PluginTemplateOnDiskEditTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/RecoveryScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/RuntimeInfoVersionParseTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SecretBoundSettingsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SeoScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SettingRefusalsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SettingsFormTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SiteConfigInputTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SiteConfigScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SiteInsightsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SiteMasterSuspendTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SiteStorageCeilingScreensTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SiteTemplatesControllerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SiteTemplatesScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/SitesScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/StaticFilesScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/TenantAuditRecordingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/TenantBackupsScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/TenantConsolePagesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/TenantPluginSettingsGateTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/TenantScreensTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/TenantUserEditSuspendTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/TenantUserPermissionsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/UrlLocalizationAdvisoryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/console/WidgetInstancesScreenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/ContentCatalogCacheAndReservedPathsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/ContentCatalogTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/ContentCatalogViewIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/ContentChangesImplTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/ContentSourceRegistryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/PagesContentSourceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/PagesRenderedIndexableTextTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/PathOwnershipTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/PluginBodyTemplateRenderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/content/VirtualContentRoutingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/crypto/AesGcmSecretCipherTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/crypto/SecretCipherFuzzTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/demo/DemoSiteInstallerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/document/DisabledDocumentsGuardTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/document/DocumentServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/editorial/EditorialServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/editorial/LineDiffTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/editorial/SitePagesImplTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/AnonymousRouteSecurityTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/BoundedBodyRequestTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/EndpointContributorRegistryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/EndpointDispatchTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/KernelContributionsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/PreAuthBodyLimitE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/RouteAwareFormContentFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/RouteBodyMethodsE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/RouteFormBodyE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/RouteFormCapE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/RouteFormCaptureFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/endpoint/RouteRequestK2Test.java create mode 100644 runway-app/src/test/java/mx/quest/runway/event/HostWriteScopeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/event/KernelEventOrderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/event/KernelListenerOrderIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/event/SpiEventBridgeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/event/SpiEventDispatchIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/head/HeadContributorRegistryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/head/HeadInjectionFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/head/ScriptNonceStamperTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/head/ScriptPreloadStripperTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/health/SiteContentReadinessTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/health/SiteHealthEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/health/SiteHealthServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/health/StorageHealthIndicatorTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/i18n/LanguageTagBundlesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/i18n/MessagesImplTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/i18n/PageI18nTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/i18n/SiteAwareMessageSourceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/i18n/SiteAwarePluginI18nTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/i18n/SiteMessagesStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/icon/IconGenerationServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/icon/IconHeadContributorTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/icon/IconRasterizerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/icon/SiteIconTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/icon/SiteManifestServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/icon/TenantIconSeederTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/icon/WebManifestEndpointTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/log/AccessLogFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/log/AppActivityLogTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/log/AppAuditEventListenerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/log/AuditEventListenerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/log/AuditJournalTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/log/SiteInsightsServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/log/SiteLogServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/mail/PlatformMailerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/metrics/MetricsEndpointTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/metrics/PrometheusScrapeTokenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/metrics/SiteRequestMetricsFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/metrics/StorageDiskMetricsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/ContentUrlsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/LoadedSiteInputsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/LocaleNegotiatorTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/LocaleUrlsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/LocalizedPathTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageChangeEventEvictionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageReseedServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageRoutingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageScaffoldTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageValidatorServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageValidatorTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageViewsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageWriteAuditTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PageWriteServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PendingRevisionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/PreviewScratchSweeperTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/page/RenderModelBuilderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/HostSettingsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/KernelSettingsHostListGapTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/KernelSettingsInitializerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/LogLevelServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/PlatformSettingsSmtpTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/PlatformSettingsStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/SchedulingConfigTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/SchedulingWithBackupsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/SettingsParityTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/platform/TestPlatformSettings.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/ContainedSchedulingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/ContributionGuardTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/EssentialAllowlistTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/EssentialFloorArmedTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/EssentialFloorArmingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/EssentialFloorBrokenTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/EssentialFloorFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/EssentialRepairAdviceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/HostLinkageScannerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/KernelBeanNamesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PlaceholderTextTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginAdminServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginAssetCacheControlTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginClassLoaderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginContextInitializerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginContributionPolicyTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginDescriptorParseTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginDiscoveryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginEventTierIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginFixture.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginManagerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginQuarantineTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginRequirementTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginResolutionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginScheduledContainmentIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginServiceTierIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginSettingsEtagIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginSettingsPlaceholderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginSettingsServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginStaticResourceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginSurfaceCheckTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginVersionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/PluginWizardModeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/SecretBoundToTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/SettingTypeDecimalRangeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/SitePluginConfigServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/spi/PluginSettingsImplTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/plugin/spi/PluginSiteFilesImplTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/protect/EdgeProtectionConfigTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/protect/EdgeRejectFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/protect/EdgeRejectionRecorderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/protect/NoSiteLoginProtectionControlTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/quality/CoreQualityChecksTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/quality/PageQualityCheckRegistryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/quality/PageQualityServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/recovery/PasswordRecoveryServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/recovery/RecoveryTokenStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/reload/SiteReloadEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/reload/SiteReloadFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/AccountStateFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/AccountStatusChecksTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/AppRealmSecurityTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/AppUserDetailsServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/AppUserStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/ConcurrencyLimitedPasswordEncoderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/CsrfExpiryPageTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/FailClosedStartupTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/LoginProtectionFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/LoginProtectionIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/PasswordEncodersTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/RealmCsrfIsolationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/SecurityFilterMetricNamesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/SecurityHardeningTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/SiteScopedRepositoriesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/SiteUserDetailsServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/TenantRealmSecurityTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/TenantSiteAuthorizationManagerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/TrustedDeviceSuccessHandlerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/UserStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/UserTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/security/UsernameUniquenessTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/seo/CanonicalHeadContributorTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/seo/SeoConfigServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/seo/SeoHeadContributorTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/DefaultSiteMaintenanceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/MaintenanceSiteFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SeedTemplateStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteBaseUrlTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteContextFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteLifecycleServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteParamsServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteResolverTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteServicesK2Test.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteStorageCeilingsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SiteViewsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/StarterTemplateRenderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/StaticFilesServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/SuspendedSiteFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/site/TenantSeederTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/AtomicFilesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/DataLayoutInitializerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/DataLayoutTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/FileStampTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/OwnerOnlyFilesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/PathSafetyFuzzTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/PathSafetyPagePathTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/PathSafetyTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/RetiredStorageKeysTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/SiteFileStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/StorageLayoutTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/StorageWiringTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/StoreCacheTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/YamlStoreTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/storage/ZipsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/AssetHeadContentLengthIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/AssetNotFoundLogTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/BufferingResponseWrapperTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CidrSetTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CompressionFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ConfigOnDiskEditTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ConsoleCacheControlIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ConsoleHostEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ConsoleHostFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ConsoleHostListEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ConsoleHostNoDefaultSiteEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ConsoleHostWizardEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CspFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CspHeaderBindingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CspNonceAdviceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CspNonceE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CspReportControllerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/CspScriptAllowlistTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/EncodedPathEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/EncodedPathFloorEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/FilterChainOrderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/FilterOrderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ForwardedHeaderCatchAllWarningTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ForwardedHeaderConfigTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/HttpToHttpsRedirectHandlerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/JettyFormLimitsConfigTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/KeystoreWatcherTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/NoInlineScriptGuardTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PageConditionalGetTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PageErrorTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PageHeadInjectionTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PageLocaleLadderTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PageLocalizedPathTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PageServeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PageWidgetTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PluginFilterPlacementTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PluginFilterRegistrarTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PublicPageNonceE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/PublicPageNonceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/RawHttp.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/RenderInputsEtagTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/RenderSpikeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/RequestPathsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/RunwayCspPropertiesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/RunwayErrorControllerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/RunwayHttpCachePropertiesTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/SiteCspE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/SiteStaticControllerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/SiteTemplateIsolationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/SvgSandboxEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/TemplateCacheServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/TemplateOnDiskEditTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/TenantTemplateIsolationEndToEndTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/ThymeleafBufferingTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/TlsIntegrationTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/TlsStartupTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/TrustedForwardedHeaderFilterTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/UnmeteredPathsTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/web/WidgetFillSpikeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/widget/ContentWidgetRegistryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/widget/WidgetInstanceConfigServiceTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/widget/WidgetInstanceDiscoveryTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/widget/WidgetModelBuilderConfigTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/widget/WidgetScannerTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/widget/WidgetSettingsCatalogTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/wizard/RestarterModeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/wizard/SetupFormBodyLimitE2ETest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/wizard/WizardActiveModeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/wizard/WizardModeTest.java create mode 100644 runway-app/src/test/java/mx/quest/runway/wizard/WizardServiceTest.java create mode 100644 runway-app/src/test/resources/kernel-adopt-host/application.yml create mode 100644 runway-app/src/test/resources/mx/quest/runway/head/preload-corpus-chrome155.txt create mode 100644 runway-app/src/test/resources/seed/demo/kettle/demo.yml create mode 100644 runway-app/src/test/resources/seed/demo/kettle/i18n/messages.properties create mode 100644 runway-app/src/test/resources/seed/demo/kettle/i18n/messages_es.properties create mode 100644 runway-app/src/test/resources/seed/demo/kettle/plugins/discoverability.yml create mode 100644 runway-app/src/test/resources/seed/demo/kettle/seo.yml create mode 100644 runway-app/src/test/resources/seed/demo/kettle/static/css/site.css create mode 100644 runway-app/src/test/resources/seed/demo/kettle/templates/_master.html create mode 100644 runway-app/src/test/resources/seed/demo/kettle/templates/_master.th.xml create mode 100644 runway-app/src/test/resources/seed/demo/kettle/templates/index.html create mode 100644 runway-app/src/test/resources/seed/demo/kettle/templates/index.meta.yml create mode 100644 runway-app/src/test/resources/seed/demo/kettle/templates/index.th.xml create mode 100644 runway-app/src/test/resources/templates/operator/testkit-shell.html create mode 100644 runway-app/src/test/resources/templates/operator/testkit-shell.th.xml create mode 100644 runway-app/src/test/resources/tls/test-keystore.p12 create mode 100644 runway-dist/pom.xml create mode 100644 runway-dist/src/assembly/dist.xml create mode 100644 runway-plugin-protection/i18n/messages.properties create mode 100644 runway-plugin-protection/i18n/messages_es.properties create mode 100644 runway-plugin-protection/plugin.yml create mode 100644 runway-plugin-protection/pom.xml create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/AppProtectionController.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/AppProtectionPanel.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/CaptchaCspContributor.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/CaptchaLoginViewContributor.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/CaptchaVerifier.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/CaptchaWidgetService.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/DosController.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/IpBlocklist.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/LoginFormPolicyGuard.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/ProtectionConfig.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/ProtectionConfigStore.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/ProtectionForm.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/ProtectionProperties.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/ProtectionSettings.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/ProtectionSiteLoginControl.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/RateLimitEdgeGuard.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/SiteProtectionController.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/SiteVerifyResponse.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/SlidingWindowLoginGate.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/StoredBlocklist.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/StoredProtection.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/StoredSiteProtection.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/TokenBucketRateLimiter.java create mode 100644 runway-plugin-protection/src/main/java/mx/quest/protection/TrustedDeviceService.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/AppProtectionPanelTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/AutoBlockSettingsSchemaTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/CaptchaLoginProtectionFilterTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/CaptchaLoginViewContributorTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/CaptchaVerifierTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/CaptchaWidgetServiceTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ConsoleA11yAudit.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/DescriptorSpiFloorTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/DosScreenGatingTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/DosScreenRenderTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/IpBlocklistTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/LoginFormPolicyGuardTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/MessageApostropheTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionAppScopeTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionConfigStoreTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionConfigTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionConfigurationMetadataTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionConsoleScreensTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionControllerLogicTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionDescriptorK4Test.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionFormTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionScreenGatingTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/ProtectionScreenRenderTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/RateLimitEdgeGuardTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/RateLimiterAutoEscalationTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/SlidingWindowLoginGateTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/TokenBucketRateLimiterTest.java create mode 100644 runway-plugin-protection/src/test/java/mx/quest/protection/TrustedDeviceServiceTest.java create mode 100644 runway-plugin-protection/templates/admin-app.html create mode 100644 runway-plugin-protection/templates/admin-app.th.xml create mode 100644 runway-plugin-protection/templates/app-dos.html create mode 100644 runway-plugin-protection/templates/app-dos.th.xml create mode 100644 runway-plugin-protection/templates/site-protection.html create mode 100644 runway-plugin-protection/templates/site-protection.th.xml create mode 100644 runway-spi-testkit/pom.xml create mode 100644 runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/EventDispatch.java create mode 100644 runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/FakeContentCatalog.java create mode 100644 runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/FakePluginSettings.java create mode 100644 runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/FakeSiteServices.java create mode 100644 runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/TempDirSiteFiles.java create mode 100644 runway-spi-testkit/src/main/java/mx/quest/runway/spi/testkit/package-info.java create mode 100644 runway-spi-testkit/src/test/java/mx/quest/runway/spi/testkit/FakePluginSettingsTest.java create mode 100644 runway-spi-testkit/src/test/java/mx/quest/runway/spi/testkit/K2FakesTest.java create mode 100644 runway-spi-testkit/src/test/java/mx/quest/runway/spi/testkit/K3FakesTest.java create mode 100644 runway-spi/pom.xml create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/BackupParticipant.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/CaptchaService.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/ContentSource.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/ContentWidget.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/EndpointContributor.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/FilterBand.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/HeadContributor.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/PageQualityCheck.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/RunwaySpi.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/SiteLoginProtectionControl.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/Alternate.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/BackupReader.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/BackupWriter.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/Capabilities.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/CaptchaWidget.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/CatalogChange.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/CatalogEntry.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/ContentBody.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/ContentRef.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/FileEntry.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/Finding.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/HeadContext.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/IconHints.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/InstallResult.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/LocalizedUrl.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/PageMeta.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/PageView.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/PluginInfo.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/Provenance.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/Realm.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/RenderFragment.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/Route.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/RouteRequest.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/RouteResponse.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/SeoTags.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/SettingsChange.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/SettingsView.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/Severity.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/SiteLifecycleEvent.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/SiteRef.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/SiteView.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/StarterPage.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/SurfacePosture.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/WidgetView.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/model/package-info.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/package-info.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/AccessCheck.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/ConsoleScreen.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/ContentCatalogView.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/ContentChanges.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/Messages.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/PluginLifecycle.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/PluginSettings.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/PluginSiteFiles.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/RequestContext.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/SiteEventListener.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/SitePages.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/Sites.java create mode 100644 runway-spi/src/main/java/mx/quest/runway/spi/service/package-info.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/ContentSourceDefaultsTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/RunwaySpiTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/SpiContractTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/BoundaryRecordsTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/CapabilitiesTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/ContentRefTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/FactoriesTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/K2RecordsTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/K3RecordsTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/K4RecordsTest.java create mode 100644 runway-spi/src/test/java/mx/quest/runway/spi/model/SettingsViewTest.java create mode 100644 scripts/dev/gen-kernel-settings.py create mode 100644 scripts/dev/gen-settings-reference.py create mode 100644 scripts/dev/settings-homes.yml create mode 100755 scripts/install.sh create mode 100755 scripts/make-release-aliases.sh create mode 100755 scripts/make-selfextract.sh create mode 100755 scripts/make-spi-assets.sh create mode 100644 scripts/plugin-seed.sh create mode 100644 scripts/release-notes.sh create mode 100644 scripts/runway.service create mode 100755 scripts/runway.sh create mode 100755 scripts/selfextract-stub.sh create mode 100644 scripts/test-install-config.sh create mode 100644 scripts/test-plugin-seed.sh create mode 100755 scripts/test-release-assets.sh create mode 100644 scripts/test-release-notes.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..02e817b --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# Build output +target/ +*.class + +# Runtime / operator-editable state (seeded into a deployment, not source) +/external/ +/uploads/ +/logs/ +/backups/ +# Safety net: surefire runs with CWD = the module dir, where the deployment-root-relative +# logs/ and backups/ defaults would otherwise land if a test forgets to redirect them. +/runway-app/logs/ +/runway-app/backups/ +*.pid + +# Local release artifacts +*.bin + +# IDE / editor +.idea/ +*.iml +.vscode/ +nbproject/private/ +.settings/ +.project +.classpath + +# OS +.DS_Store +Thumbs.db + +# Scratch (never commit) +tmp_do_not_commit/ diff --git a/.mvn/jvm.config b/.mvn/jvm.config new file mode 100644 index 0000000..37543d7 --- /dev/null +++ b/.mvn/jvm.config @@ -0,0 +1 @@ +-Duser.timezone=UTC diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..45b7833 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/). + +## [1.0.0] — 2026-10-21 + +The first public release of Runway: a multi-site web platform built as a small multi-tenant kernel, with every +domain feature delivered as a plugin. + +- **Kernel**: sites with their own hosts, pages, templates, messages and static files; the operator console + (application and per-site realms) with the setup wizard, the page editor, roles and permissions, per-site + backups, platform mail and password recovery; optional in-app TLS termination; Prometheus metrics; an + optional cluster mode. The essential `protection` plugin (rate limiting and login protection) is bundled. +- **Plugin contract**: SPI `1.0.0`, frozen for the `1.x` line — it changes only additively + ([docs/SPI-STABILITY.md](docs/SPI-STABILITY.md)). Plugin authors build against the `runway-spi` and + `runway-spi-testkit` jars attached to each release ([docs/PLUGIN-DEVELOPMENT.md](docs/PLUGIN-DEVELOPMENT.md)). +- **Public plugins** in `plugins/`, attached to this release: `runway-demo` 2.1.0 (the reference plugin, Apache-2.0), + `search` 2.3.0, `search-lucene` 3.3.0 and `lucene-provider` 10.4.0. +- **Install**: `runway-1.0.0.bin` (self-extracting installer) or `runway-1.0.0-dist.zip`, verified against + `SHA256SUMS` ([docs/ADMINISTRATION.md](docs/ADMINISTRATION.md) §3). +- **License**: GNU AGPL v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`); + third-party components are listed in `THIRD-PARTY-NOTICES`. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/LICENSE-EXCEPTION b/LICENSE-EXCEPTION new file mode 100644 index 0000000..b634521 --- /dev/null +++ b/LICENSE-EXCEPTION @@ -0,0 +1,44 @@ +Runway — additional permission for plugins +(an additional permission under section 7 of the GNU Affero General Public License, version 3) + +Copyright (C) 2026 Quest ICT SAS de CV + +Runway is free software: you can redistribute it and/or modify it under the terms of the +GNU Affero General Public License as published by the Free Software Foundation, version 3 +(the file LICENSE), with the additional permission below. Runway is distributed in the hope +that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public +License for more details. + +1. Definitions + + "Runway" means the Runway kernel and every Runway plugin whose source carries this file. + + "Published SPI" means the public classes and interfaces of the runway-spi artifact + (the package mx.quest.runway.spi and its subpackages), together with the public classes + and interfaces of any package named "spi" that a part of Runway publishes for other + plugins to use (for example mx.quest.search.spi). + + "Plugin" means an independent module that Runway loads as a plugin, that interacts with + Runway only through the Published SPI, and that is not based on any part of Runway other + than the Published SPI. + +2. Permission + + As an additional permission, the copyright holder gives you permission to combine Runway + with Plugins, and to convey and run the resulting combination, without the terms of the + GNU Affero General Public License applying to those Plugins. You may license, convey and + run your Plugins under terms of your choice, provided that you continue to meet the terms + of the GNU Affero General Public License for Runway itself, including offering the + Corresponding Source of Runway, and of any modification you make to it, as that license + requires. + +3. Testing + + Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does + not by itself make the Plugin subject to the GNU Affero General Public License. + +4. Modified versions + + If you modify Runway, you may extend this additional permission to your version, but you + are not obliged to do so. If you do not wish to, delete this file from your version. diff --git a/README.md b/README.md new file mode 100644 index 0000000..36e6f92 --- /dev/null +++ b/README.md @@ -0,0 +1,149 @@ +# Runway + +**Runway** is a multi-site web platform — a **kernel + plugins** server: a small, +multi-tenant content/website core that ships only the essential bytes, with every domain +feature delivered as a plugin or a first-class SPI implementation. + +| | | +|---|---| +| Coordinates | `mx.quest:runway` | +| Version | `1.0.0` (plugin contract: SPI `1.0.0`) — the exact version is in the root `pom.xml` and each release in [CHANGELOG.md](CHANGELOG.md) | +| Java | 25+ | +| Framework | Spring Boot 4 on embedded Jetty | +| Storage | Filesystem / YAML (no database) | +| Status | **Stable.** Semantic Versioning from `1.0.0`. The kernel, both realms, the setup wizard (with a catch-all default site), the page editor, per-site backups and optional in-app TLS termination run today; open items are in [docs/KNOWN-LIMITATIONS.md](docs/KNOWN-LIMITATIONS.md). | + +## Modules + +``` +runway/ reactor (this pom) +├── runway-spi/ dependency-free extension API (interfaces + immutable model records) +├── runway-spi-testkit/ in-memory fakes of the SPI services, for plugins' unit tests (test scope) +├── runway-app/ the Spring Boot kernel (Jetty) — collects SPI impls + plugin contributions +├── runway-plugin-protection/ the essential protection plugin (rate-limit edge guard, login gate, CAPTCHA; +│ shipped inside the installer and seeded on a fresh install) +├── runway-dist/ packaging only: the dist zip, the self-extracting .bin installer, checksums +└── plugins/ the plugins demo, search, search-lucene, lucene-provider (not reactor modules) +``` + +The plugins under `plugins/` are **standalone** projects, each with its own build; one with code is built +against `runway-spi` alone as a `provided` dependency (with `runway-spi-testkit` for its tests). A plugin that links `runway-app` classes is refused at +load time — the 1.0 plugin contract is the SPI ([SPI-STABILITY.md](docs/SPI-STABILITY.md)). + +## Quick start + +Two audiences: **operators** install the packaged release and finish setup in the browser; +**developers** build the reactor and run the jar. Both end at the same first-run wizard. + +### Operator — install the release + +The Linux release is a single self-extracting `.bin` (a shell stub with the deployment +bundle appended — no `makeself`, only stock `bash`/`tar`/`gzip`). Run it as root; it is +**idempotent**, so re-running the same or a newer `.bin` upgrades in place: + +```sh +sudo ./runway-.bin # interactive: prompts on a TTY +sudo ./runway-.bin -y # unattended, all defaults +sudo ./runway-.bin -y --no-firewall # ...and never touch the host firewall +``` + +Get it from the releases page () and check it against the +release's `SHA256SUMS` before running it ([Administration §3](docs/ADMINISTRATION.md)). The stable +`…/releases/latest` page and `runway-latest.bin` link serve the newest published release — install an explicit +version in production. + +The installer lays the code under `/opt/runway-`, points `/opt/runway` at it, +keeps editable state (`external/`, `logs/`, `backups/`) in the version-independent +`/opt/runway-data/` so upgrades never clobber it, installs a systemd unit, relabels +SELinux contexts (required on enforcing RHEL-family hosts), and starts the service. +There is **no database to configure** — Runway is filesystem/YAML-backed; first-run +configuration happens in the app's own wizard (below). + +Confirm it is up: + +```sh +systemctl status runway # active (running) +journalctl -u runway -f # startup log; also /opt/runway-data/logs/ +``` + +### Developer — build and run from source + +**Prerequisites:** a JDK 25+ (with `javac`) and Maven. + +```sh +# build the reactor (spi + spi-testkit + app + protection plugin + dist) and run the tests +JAVA_HOME=/path/to/jdk-25 mvn -e install + +# run the packaged app (the -exec jar is the runnable one; the plain jar is the +# thin library other modules compile against) +java -jar runway-app/target/runway-app--exec.jar +``` + +The app listens on **:8080** by default and expects its `external/`, `logs/` (and +`backups/`) folders in the working directory — run it from the deployment root, or use +the launcher `scripts/runway.sh` which `cd`s there for you. + +To produce the deployment artifacts — the dist zip (`runway--dist.zip`), the `.bin` +installer (`runway-.bin`), stable-named `runway-latest.*` aliases of both, the plugin author's +`runway-spi` / `runway-spi-testkit` jars with their sources jars and poms, and a `SHA256SUMS` over all of +them, landing in `runway-dist/target/`: + +```sh +JAVA_HOME=/path/to/jdk-25 mvn -P dist package +``` + +### First access — the setup wizard + +On first boot Runway comes up in **wizard mode**: it has no accounts yet, so **every URL +redirects to `/setup`**. Open the site in a browser (e.g. `http://:8080/`) and you +land on the setup form. Because the surface is open before setup completes, reach it only +over localhost or behind your reverse proxy until it is done. + +The wizard collects **two administrators, one per realm** — the two realms never cross +(authenticating in one never grants the other), which is why setup creates both up front: + +- **Application superadmin** — runs the *platform*: creates and manages sites, plugins, and + application users. It cannot operate inside a site. This account is pinned and can never be + deleted or demoted, so there is always a way back in. +- **Default site administrator** — manages the seeded default site (a separate identity in + the *site* realm). Unbound hosts resolve to this default site. + +Submit the form; Runway writes the external `application.yml` (the superadmin pin, `chmod 600`) +and **restarts into normal mode**, after which the whole wizard layer is gone. The restart is a supervised +relaunch (the JVM exits with code 42): under systemd or the launcher `scripts/runway.sh` (detached mode) it comes +back by itself; a bare `java -jar` simply exits, so start it again. Then sign in: + +- **Operator console** — [`/app/login`](http://localhost:8080/app/login) (application superadmin) +- **Site management** — [`/login`](http://localhost:8080/login) (default site administrator) + +To confirm setup took: once it is back up, requesting `/` no longer redirects to `/setup`, +`/opt/runway-data/external/application.yml` exists with a `runway.security.app-master-id` +line, and both login pages authenticate their respective account. + +## Versioning & release cycle + +Runway follows [Semantic Versioning](https://semver.org/) with a `SNAPSHOT → beta → rc → +release` lifecycle. `1.0.0` is the first stable release, with the plugin contract frozen at SPI `1.0.0`. +From `1.0.0` a breaking change costs a MAJOR. What stays compatible within a MAJOR line is in [SPI-STABILITY.md](docs/SPI-STABILITY.md) and [CONFIGURATION-AND-DATA-STABILITY.md](docs/CONFIGURATION-AND-DATA-STABILITY.md). + +## Documentation + +The documentation delivered with Runway lives in **[`docs/`](docs/README.md)** — start at the +[documentation index](docs/README.md). It covers: + +- **[Plugin Development](docs/PLUGIN-DEVELOPMENT.md)** — for plugin authors +- **[Administration](docs/ADMINISTRATION.md)** — for the operators who install and run the platform +- **[Site Manager & Designer Guide](docs/SITE-MANAGER-GUIDE.md)** — for the people who manage a site (and designers who edit pages) +- **[Operations](docs/OPERATIONS.md)** and a **[Glossary](docs/GLOSSARY.md)** +- **[SPI stability](docs/SPI-STABILITY.md)** and **[Configuration & data stability](docs/CONFIGURATION-AND-DATA-STABILITY.md)** — what stays compatible from `1.0.0` +- **[Settings reference](docs/SETTINGS-REFERENCE.md)** — every setting, its values and default, and where it is set +- **[Known limitations](docs/KNOWN-LIMITATIONS.md)** — what Runway does not do yet + +## License + +Copyright (C) 2026 Quest ICT SAS de CV. + +Runway is licensed under the [GNU Affero General Public License, version 3](LICENSE), with an +[additional permission for plugins](LICENSE-EXCEPTION): a plugin that interacts with Runway only through the +published SPI (`runway-spi`) may carry any license, including a proprietary one. Runway itself stays under +the AGPL: if you run a modified Runway for others over a network, you must offer them its source. diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES new file mode 100644 index 0000000..9c798d9 --- /dev/null +++ b/THIRD-PARTY-NOTICES @@ -0,0 +1,2579 @@ +THIRD-PARTY NOTICES +=================== + +Runway includes the third-party components listed below. Each component remains under its own +license, reproduced or referenced in part 3. Where a component is offered under a choice of +licenses, the line names the license under which Runway uses it. Runway itself is licensed under the +GNU Affero General Public License, version 3, with the additional permission in LICENSE-EXCEPTION; +that license does not change the terms of the components listed here. + +Contents + 1. Java libraries bundled in the executable jar (bin/runway-app-*-exec.jar, BOOT-INF/lib) + 2. Front-end assets bundled with the console (static/vendor) + 3. License texts + 4. Notices of Apache-licensed components + 5. Notices of Eclipse-licensed components + + +1. Java libraries bundled in the executable jar +------------------------------------------------ + +Format: groupId:artifactId version — license (SPDX) [license Runway relies on, for a choice] — +copyright holder. + +ch.qos.logback:logback-classic 1.5.32 — EPL-2.0 OR LGPL-2.1-only [Runway uses EPL-2.0] — QOS.ch (logback) +ch.qos.logback:logback-core 1.5.32 — EPL-2.0 OR LGPL-2.1-only [Runway uses EPL-2.0] — QOS.ch (logback) +com.aayushatharva.brotli4j:brotli4j 1.18.0 — Apache-2.0 — the Brotli4j project contributors +com.aayushatharva.brotli4j:native-linux-x86_64 1.18.0 — Apache-2.0 — the Brotli4j project contributors +com.aayushatharva.brotli4j:service 1.18.0 — Apache-2.0 — the Brotli4j project contributors +com.fasterxml.jackson.core:jackson-annotations 2.21 — Apache-2.0 — Tatu Saloranta and the Jackson project contributors (FasterXML) +com.github.ben-manes.caffeine:caffeine 3.2.3 — Apache-2.0 — Ben Manes (Caffeine) +com.github.weisj:jsvg 2.1.0 — MIT — Jannis Weis +com.google.errorprone:error_prone_annotations 2.43.0 — Apache-2.0 — Google LLC +com.hazelcast:hazelcast 5.6.0 — Apache-2.0 — Hazelcast, Inc. +commons-logging:commons-logging 1.3.6 — Apache-2.0 — The Apache Software Foundation +io.micrometer:micrometer-commons 1.16.5 — Apache-2.0 — VMware, Inc. (Micrometer) +io.micrometer:micrometer-core 1.16.5 — Apache-2.0 — VMware, Inc. (Micrometer) +io.micrometer:micrometer-jakarta9 1.16.5 — Apache-2.0 — VMware, Inc. (Micrometer) +io.micrometer:micrometer-observation 1.16.5 — Apache-2.0 — VMware, Inc. (Micrometer) +io.micrometer:micrometer-registry-prometheus 1.16.5 — Apache-2.0 — VMware, Inc. (Micrometer) +io.prometheus:prometheus-metrics-config 1.4.3 — Apache-2.0 — the Prometheus Java client project contributors +io.prometheus:prometheus-metrics-core 1.4.3 — Apache-2.0 — the Prometheus Java client project contributors +io.prometheus:prometheus-metrics-exposition-formats 1.4.3 — Apache-2.0 — the Prometheus Java client project contributors +io.prometheus:prometheus-metrics-exposition-textformats 1.4.3 — Apache-2.0 — the Prometheus Java client project contributors +io.prometheus:prometheus-metrics-model 1.4.3 — Apache-2.0 — the Prometheus Java client project contributors +io.prometheus:prometheus-metrics-tracer-common 1.4.3 — Apache-2.0 — the Prometheus Java client project contributors +jakarta.activation:jakarta.activation-api 2.1.4 — BSD-3-Clause (EDL-1.0) — Oracle and/or its affiliates (Eclipse Jakarta Activation) +jakarta.annotation:jakarta.annotation-api 3.0.0 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 [Runway uses EPL-2.0] — the Eclipse Jakarta EE project contributors +jakarta.enterprise:jakarta.enterprise.cdi-api 4.1.0 — Apache-2.0 — the Eclipse Jakarta EE project contributors +jakarta.enterprise:jakarta.enterprise.lang-model 4.1.0 — Apache-2.0 — the Eclipse Jakarta EE project contributors +jakarta.inject:jakarta.inject-api 2.0.1 — Apache-2.0 — the Eclipse Jakarta EE project contributors +jakarta.interceptor:jakarta.interceptor-api 2.2.0 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 [Runway uses EPL-2.0] — the Eclipse Jakarta EE project contributors +jakarta.mail:jakarta.mail-api 2.1.5 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause (EDL-1.0) [Runway uses EPL-2.0] — the Eclipse Jakarta Mail project contributors +jakarta.servlet:jakarta.servlet-api 6.1.0 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 [Runway uses EPL-2.0] — the Eclipse Jakarta EE project contributors +jakarta.transaction:jakarta.transaction-api 2.0.1 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 [Runway uses EPL-2.0] — the Eclipse Jakarta EE project contributors +jakarta.websocket:jakarta.websocket-api 2.2.0 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 [Runway uses EPL-2.0] — the Eclipse Jakarta EE project contributors +jakarta.websocket:jakarta.websocket-client-api 2.2.0 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 [Runway uses EPL-2.0] — the Eclipse Jakarta EE project contributors +org.apache.logging.log4j:log4j-api 2.25.4 — Apache-2.0 — The Apache Software Foundation +org.apache.logging.log4j:log4j-to-slf4j 2.25.4 — Apache-2.0 — The Apache Software Foundation +org.apache.tomcat.embed:tomcat-embed-el 11.0.21 — Apache-2.0 — The Apache Software Foundation +org.attoparser:attoparser 2.0.7.RELEASE — Apache-2.0 — The ATTOPARSER team +org.bouncycastle:bcprov-jdk18on 1.80 — MIT (Bouncy Castle Licence) — The Legion of the Bouncy Castle Inc. +org.eclipse.angus:angus-activation 2.0.3 — BSD-3-Clause (EDL-1.0) — Oracle and/or its affiliates (Eclipse Angus) +org.eclipse.angus:angus-mail 2.0.5 — EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause (EDL-1.0) [Runway uses EPL-2.0] — the Eclipse Angus project contributors +org.eclipse.jetty:jetty-alpn-client 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-annotations 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-client 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-http 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-io 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-plus 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-security 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-server 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-session 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-util 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty:jetty-xml 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.compression:jetty-compression-common 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.compression:jetty-compression-gzip 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.compression:jetty-compression-server 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee:jetty-ee-webapp 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11:jetty-ee11-annotations 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11:jetty-ee11-plus 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11:jetty-ee11-servlet 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11:jetty-ee11-webapp 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11.websocket:jetty-ee11-websocket-jakarta-client 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11.websocket:jetty-ee11-websocket-jakarta-common 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11.websocket:jetty-ee11-websocket-jakarta-server 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11.websocket:jetty-ee11-websocket-jetty-server 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.ee11.websocket:jetty-ee11-websocket-servlet 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.websocket:jetty-websocket-core-client 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.websocket:jetty-websocket-core-common 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.websocket:jetty-websocket-core-server 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.websocket:jetty-websocket-jetty-api 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.websocket:jetty-websocket-jetty-common 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.eclipse.jetty.websocket:jetty-websocket-jetty-server 12.1.8 — EPL-2.0 OR Apache-2.0 [Runway uses Apache-2.0] — Webtide and the Eclipse Jetty project contributors +org.hdrhistogram:HdrHistogram 2.2.2 — CC0-1.0 OR BSD-2-Clause [Runway uses CC0-1.0] — Gil Tene, Michael Barker and Matt Warren (dedicated to the public domain) +org.jsoup:jsoup 1.18.3 — MIT — Jonathan Hedley +org.jspecify:jspecify 1.0.0 — Apache-2.0 — The JSpecify Authors +org.latencyutils:LatencyUtils 2.0.3 — CC0-1.0 — the LatencyUtils authors (dedicated to the public domain) +org.ow2.asm:asm 9.7.1 — BSD-3-Clause — INRIA, France Telecom +org.ow2.asm:asm-commons 9.9.1 — BSD-3-Clause — INRIA, France Telecom +org.ow2.asm:asm-tree 9.9.1 — BSD-3-Clause — INRIA, France Telecom +org.slf4j:jul-to-slf4j 2.0.17 — MIT — QOS.ch Sarl (Switzerland) +org.slf4j:slf4j-api 2.0.17 — MIT — QOS.ch Sarl (Switzerland) +org.snakeyaml:snakeyaml-engine 3.0.1 — Apache-2.0 — the SnakeYAML project contributors +org.springframework:spring-aop 7.0.7 — Apache-2.0 — Pivotal, Inc. (Spring Framework) +org.springframework:spring-beans 7.0.7 — Apache-2.0 — Pivotal, Inc. (Spring Framework) +org.springframework:spring-context 7.0.7 — Apache-2.0 — Pivotal, Inc. (Spring Framework) +org.springframework:spring-core 7.0.7 — Apache-2.0 — Pivotal, Inc. (Spring Framework) +org.springframework:spring-expression 7.0.7 — Apache-2.0 — Pivotal, Inc. (Spring Framework) +org.springframework:spring-web 7.0.7 — Apache-2.0 — Pivotal, Inc. (Spring Framework) +org.springframework:spring-webmvc 7.0.7 — Apache-2.0 — Pivotal, Inc. (Spring Framework) +org.springframework.boot:spring-boot 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-actuator 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-actuator-autoconfigure 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-autoconfigure 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-health 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-http-converter 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-jackson 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-jarmode-tools 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-jetty 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-micrometer-metrics 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-micrometer-observation 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-security 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-servlet 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-thymeleaf 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-web-server 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.boot:spring-boot-webmvc 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) +org.springframework.security:spring-security-config 7.0.5 — Apache-2.0 — Pivotal Software, Inc. (Spring Security) +org.springframework.security:spring-security-core 7.0.5 — Apache-2.0 — Pivotal Software, Inc. (Spring Security) +org.springframework.security:spring-security-crypto 7.0.5 — Apache-2.0 — Pivotal Software, Inc. (Spring Security) +org.springframework.security:spring-security-web 7.0.5 — Apache-2.0 — Pivotal Software, Inc. (Spring Security) +org.springframework.session:spring-session-core 4.0.3 — Apache-2.0 — Pivotal Software, Inc. (Spring Session) +org.thymeleaf:thymeleaf 3.1.5.RELEASE — Apache-2.0 — Thymeleaf (thymeleaf.org) +org.thymeleaf:thymeleaf-spring6 3.1.5.RELEASE — Apache-2.0 — Thymeleaf (thymeleaf.org) +org.unbescape:unbescape 1.1.6.RELEASE — Apache-2.0 — The UNBESCAPE team +org.yaml:snakeyaml 2.5 — Apache-2.0 — the SnakeYAML project contributors +tools.jackson.core:jackson-core 3.1.2 — Apache-2.0 — Tatu Saloranta and the Jackson project contributors (FasterXML) +tools.jackson.core:jackson-databind 3.1.2 — Apache-2.0 — Tatu Saloranta and the Jackson project contributors (FasterXML) +tools.jackson.dataformat:jackson-dataformat-yaml 3.1.2 — Apache-2.0 — Tatu Saloranta and the Jackson project contributors (FasterXML) +org.springframework.boot:spring-boot-loader 4.0.6 — Apache-2.0 — VMware, Inc. (Spring Boot) (the launcher classes at the root of the executable jar) + +Code embedded inside the jars above (each jar carries the texts named): +- in spring-core: ASM 9.9.1, CGLIB 3.3, JavaPoet 0.10.0, Objenesis 3.5 (repackaged under + org.springframework; BSD-3-Clause for ASM, Apache-2.0 for the others; listed in the jar's + META-INF/license.txt). +- in hazelcast: Jackson-core/annotations and Jackson-jr, everit-json-schema, HikariCP, Java + Concurrency Tools Core Library, Objenesis, SnakeYAML Engine (Apache-2.0); ClassGraph (MIT, Luke + Hutchison); JSON in Java (public domain); FastDoubleParser (MIT). Listed with their texts in + THIRD-PARTY.txt and LICENSE-ClassGraph.txt inside the jar. +- in jackson-core: FastDoubleParser (MIT, Werner Randelshofer), which carries portions of fast_float + (MIT), fast_double_parser (BSL-1.0) and bigint (BSD-2-Clause); texts in + META-INF/FastDoubleParser-* and META-INF/thirdparty-LICENSE inside the jar, reproduced in part 3. +- in native-linux-x86_64: the Brotli compression library, native build (MIT, the Brotli Authors). + +115 jars, plus the launcher classes at the root of the executable jar. + + +2. Front-end assets bundled with the console +-------------------------------------------- + +Served from /__assets/vendor/ inside the executable jar (BOOT-INF/classes/static/vendor). Versions +are read from the files themselves. + +Alpine.js 3.15.12 — MIT — Copyright the Alpine.js contributors (the shipped file carries no copyright line) + files: alpine.min.js +htmx 2.0.10 — 0BSD — the htmx contributors (0BSD asks for no attribution) + files: htmx.min.js +Chart.js 4.5.1 — MIT — (c) 2025 Chart.js Contributors + files: chart.min.js +Tabler 1.4.0 — MIT — Copyright 2018-2025 The Tabler Authors; Copyright 2018-2025 codecalm.net Paweł Kuna + files: tabler.min.js, tabler.min.css +Bootstrap (bundled inside tabler.min.js) 5.3.7 — MIT — Copyright 2011-2025 The Bootstrap Authors + files: tabler.min.js +Popper (bundled inside tabler.min.js) 2.x (exact version not stated in the file) — MIT — Copyright the Popper contributors (the bundle carries no copyright line for it) + files: tabler.min.js +Font Awesome Free 7.3.0 — MIT (code) AND OFL-1.1 (fonts) AND CC-BY-4.0 (icons) — Copyright 2026 Fonticons, Inc. (https://fontawesome.com, license summary at https://fontawesome.com/license/free) + files: fontawesome/css/all.min.css, fontawesome/webfonts/*.woff2 + +CodeMirror 6 (codemirror.min.js) — a single minified bundle of the following MIT-licensed npm +packages (versions from frontend/codemirror/package-lock.json): + @codemirror/autocomplete 6.20.3 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/commands 6.10.4 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/lang-css 6.3.1 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/lang-html 6.4.11 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/lang-javascript 6.2.5 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/lang-xml 6.1.0 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/language 6.12.4 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/lint 6.9.7 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/search 6.7.1 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/state 6.7.0 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/theme-one-dark 6.1.3 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @codemirror/view 6.43.4 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + @lezer/common 1.5.2 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + @lezer/css 1.3.4 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + @lezer/highlight 1.2.3 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + @lezer/html 1.3.13 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + @lezer/javascript 1.5.4 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + @lezer/lr 1.4.10 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + @lezer/xml 1.0.6 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + @marijn/find-cluster-break 1.0.3 — MIT — Copyright (C) 2024 by Marijn Haverbeke + codemirror 6.0.2 — MIT — Copyright (C) 2018-2021 by Marijn Haverbeke and others + crelt 1.0.7 — MIT — Copyright (C) 2020 by Marijn Haverbeke + style-mod 4.1.3 — MIT — Copyright (C) 2018 by Marijn Haverbeke and others + w3c-keyname 2.2.8 — MIT — Copyright (C) 2016 by Marijn Haverbeke and others + +codemirror.min.css is part of Runway (it only frames the editor) and is not third-party. + +7 front-end components and 24 CodeMirror packages. + + +3. License texts +---------------- + +==================================================================================================== +3.1 Apache License, Version 2.0 +==================================================================================================== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +==================================================================================================== +3.2 Eclipse Public License, Version 2.0 +==================================================================================================== + +Eclipse Public License - v 2.0 + + THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE + PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION + OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + + 1. DEFINITIONS + + "Contribution" means: + + a) in the case of the initial Contributor, the initial content + Distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + i) changes to the Program, and + ii) additions to the Program; + where such changes and/or additions to the Program originate from + and are Distributed by that particular Contributor. A Contribution + "originates" from a Contributor if it was added to the Program by + such Contributor itself or anyone acting on such Contributor's behalf. + Contributions do not include changes or additions to the Program that + are not Modified Works. + + "Contributor" means any person or entity that Distributes the Program. + + "Licensed Patents" mean patent claims licensable by a Contributor which + are necessarily infringed by the use or sale of its Contribution alone + or when combined with the Program. + + "Program" means the Contributions Distributed in accordance with this + Agreement. + + "Recipient" means anyone who receives the Program under this Agreement + or any Secondary License (as applicable), including Contributors. + + "Derivative Works" shall mean any work, whether in Source Code or other + form, that is based on (or derived from) the Program and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. + + "Modified Works" shall mean any work in Source Code or other form that + results from an addition to, deletion from, or modification of the + contents of the Program, including, for purposes of clarity any new file + in Source Code form that contains any contents of the Program. Modified + Works shall not include works that contain only declarations, + interfaces, types, classes, structures, or files of the Program solely + in each case in order to link to, bind by name, or subclass the Program + or Modified Works thereof. + + "Distribute" means the acts of a) distributing or b) making available + in any manner that enables the transfer of a copy. + + "Source Code" means the form of a Program preferred for making + modifications, including but not limited to software source code, + documentation source, and configuration files. + + "Secondary License" means either the GNU General Public License, + Version 2.0, or any later versions of that license, including any + exceptions or additional permissions as identified by the initial + Contributor. + + 2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free copyright + license to reproduce, prepare Derivative Works of, publicly display, + publicly perform, Distribute and sublicense the Contribution of such + Contributor, if any, and such Derivative Works. + + b) Subject to the terms of this Agreement, each Contributor hereby + grants Recipient a non-exclusive, worldwide, royalty-free patent + license under Licensed Patents to make, use, sell, offer to sell, + import and otherwise transfer the Contribution of such Contributor, + if any, in Source Code or other form. This patent license shall + apply to the combination of the Contribution and the Program if, at + the time the Contribution is added by the Contributor, such addition + of the Contribution causes such combination to be covered by the + Licensed Patents. The patent license shall not apply to any other + combinations which include the Contribution. No hardware per se is + licensed hereunder. + + c) Recipient understands that although each Contributor grants the + licenses to its Contributions set forth herein, no assurances are + provided by any Contributor that the Program does not infringe the + patent or other intellectual property rights of any other entity. + Each Contributor disclaims any liability to Recipient for claims + brought by any other entity based on infringement of intellectual + property rights or otherwise. As a condition to exercising the + rights and licenses granted hereunder, each Recipient hereby + assumes sole responsibility to secure any other intellectual + property rights needed, if any. For example, if a third party + patent license is required to allow Recipient to Distribute the + Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + + d) Each Contributor represents that to its knowledge it has + sufficient copyright rights in its Contribution, if any, to grant + the copyright license set forth in this Agreement. + + e) Notwithstanding the terms of any Secondary License, no + Contributor makes additional grants to any Recipient (other than + those set forth in this Agreement) as a result of such Recipient's + receipt of the Program under the terms of a Secondary License + (if permitted under the terms of Section 3). + + 3. REQUIREMENTS + + 3.1 If a Contributor Distributes the Program in any form, then: + + a) the Program must also be made available as Source Code, in + accordance with section 3.2, and the Contributor must accompany + the Program with a statement that the Source Code for the Program + is available under this Agreement, and informs Recipients how to + obtain it in a reasonable manner on or through a medium customarily + used for software exchange; and + + b) the Contributor may Distribute the Program under a license + different than this Agreement, provided that such license: + i) effectively disclaims on behalf of all other Contributors all + warranties and conditions, express and implied, including + warranties or conditions of title and non-infringement, and + implied warranties or conditions of merchantability and fitness + for a particular purpose; + + ii) effectively excludes on behalf of all other Contributors all + liability for damages, including direct, indirect, special, + incidental and consequential damages, such as lost profits; + + iii) does not attempt to limit or alter the recipients' rights + in the Source Code under section 3.2; and + + iv) requires any subsequent distribution of the Program by any + party to be under a license that satisfies the requirements + of this section 3. + + 3.2 When the Program is Distributed as Source Code: + + a) it must be made available under this Agreement, or if the + Program (i) is combined with other material in a separate file or + files made available under a Secondary License, and (ii) the initial + Contributor attached to the Source Code the notice described in + Exhibit A of this Agreement, then the Program may be made available + under the terms of such Secondary Licenses, and + + b) a copy of this Agreement must be included with each copy of + the Program. + + 3.3 Contributors may not remove or alter any copyright, patent, + trademark, attribution notices, disclaimers of warranty, or limitations + of liability ("notices") contained within the Program from any copy of + the Program which they Distribute, provided that Contributors may add + their own appropriate notices. + + 4. COMMERCIAL DISTRIBUTION + + Commercial distributors of software may accept certain responsibilities + with respect to end users, business partners and the like. While this + license is intended to facilitate the commercial use of the Program, + the Contributor who includes the Program in a commercial product + offering should do so in a manner which does not create potential + liability for other Contributors. Therefore, if a Contributor includes + the Program in a commercial product offering, such Contributor + ("Commercial Contributor") hereby agrees to defend and indemnify every + other Contributor ("Indemnified Contributor") against any losses, + damages and costs (collectively "Losses") arising from claims, lawsuits + and other legal actions brought by a third party against the Indemnified + Contributor to the extent caused by the acts or omissions of such + Commercial Contributor in connection with its distribution of the Program + in a commercial product offering. The obligations in this section do not + apply to any claims or Losses relating to any actual or alleged + intellectual property infringement. In order to qualify, an Indemnified + Contributor must: a) promptly notify the Commercial Contributor in + writing of such claim, and b) allow the Commercial Contributor to control, + and cooperate with the Commercial Contributor in, the defense and any + related settlement negotiations. The Indemnified Contributor may + participate in any such claim at its own expense. + + For example, a Contributor might include the Program in a commercial + product offering, Product X. That Contributor is then a Commercial + Contributor. If that Commercial Contributor then makes performance + claims, or offers warranties related to Product X, those performance + claims and warranties are such Commercial Contributor's responsibility + alone. Under this section, the Commercial Contributor would have to + defend claims against the other Contributors related to those performance + claims and warranties, and if a court requires any other Contributor to + pay any damages as a result, the Commercial Contributor must pay + those damages. + + 5. NO WARRANTY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT + PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS" + BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR + IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF + TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR + PURPOSE. Each Recipient is solely responsible for determining the + appropriateness of using and distributing the Program and assumes all + risks associated with its exercise of rights under this Agreement, + including but not limited to the risks and costs of program errors, + compliance with applicable laws, damage to or loss of data, programs + or equipment, and unavailability or interruption of operations. + + 6. DISCLAIMER OF LIABILITY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT + PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS + SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST + PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE + EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGES. + + 7. GENERAL + + If any provision of this Agreement is invalid or unenforceable under + applicable law, it shall not affect the validity or enforceability of + the remainder of the terms of this Agreement, and without further + action by the parties hereto, such provision shall be reformed to the + minimum extent necessary to make such provision valid and enforceable. + + If Recipient institutes patent litigation against any entity + (including a cross-claim or counterclaim in a lawsuit) alleging that the + Program itself (excluding combinations of the Program with other software + or hardware) infringes such Recipient's patent(s), then such Recipient's + rights granted under Section 2(b) shall terminate as of the date such + litigation is filed. + + All Recipient's rights under this Agreement shall terminate if it + fails to comply with any of the material terms or conditions of this + Agreement and does not cure such failure in a reasonable period of + time after becoming aware of such noncompliance. If all Recipient's + rights under this Agreement terminate, Recipient agrees to cease use + and distribution of the Program as soon as reasonably practicable. + However, Recipient's obligations under this Agreement and any licenses + granted by Recipient relating to the Program shall continue and survive. + + Everyone is permitted to copy and distribute copies of this Agreement, + but in order to avoid inconsistency the Agreement is copyrighted and + may only be modified in the following manner. The Agreement Steward + reserves the right to publish new versions (including revisions) of + this Agreement from time to time. No one other than the Agreement + Steward has the right to modify this Agreement. The Eclipse Foundation + is the initial Agreement Steward. The Eclipse Foundation may assign the + responsibility to serve as the Agreement Steward to a suitable separate + entity. Each new version of the Agreement will be given a distinguishing + version number. The Program (including Contributions) may always be + Distributed subject to the version of the Agreement under which it was + received. In addition, after a new version of the Agreement is published, + Contributor may elect to Distribute the Program (including its + Contributions) under the new version. + + Except as expressly stated in Sections 2(a) and 2(b) above, Recipient + receives no rights or licenses to the intellectual property of any + Contributor under this Agreement, whether expressly, by implication, + estoppel or otherwise. All rights in the Program not expressly granted + under this Agreement are reserved. Nothing in this Agreement is intended + to be enforceable by any entity that is not a Contributor or Recipient. + No third-party beneficiary rights are created under this Agreement. + + Exhibit A - Form of Secondary Licenses Notice + + "This Source Code may also be made available under the following + Secondary Licenses when the conditions for such availability set forth + in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), + version(s), and exceptions or additional permissions here}." + + Simply including a copy of this Agreement, including this Exhibit A + is not sufficient to license the Source Code under Secondary Licenses. + + If it is not possible or desirable to put the notice in a particular + file, then You may include the notice in a location (such as a LICENSE + file in a relevant directory) where a recipient would be likely to + look for such a notice. + + You may add additional accurate notices of copyright ownership. + +==================================================================================================== +3.3 Eclipse Distribution License, Version 1.0 (BSD-3-Clause) +==================================================================================================== +Applies to Jakarta Activation and Eclipse Angus Activation. + + + Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of the Eclipse Foundation, Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +==================================================================================================== +3.4 BSD 3-Clause License (ASM) +==================================================================================================== +Applies to ASM. + +ASM: a very small and fast Java bytecode manipulation framework +Copyright (c) 2000-2011 INRIA, France Telecom +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +==================================================================================================== +3.5 MIT License +==================================================================================================== +Applies to the components below, each under its own copyright line: + + - Bouncy Castle (bcprov): Copyright (c) 2000-2023 The Legion of the Bouncy Castle Inc. + (https://www.bouncycastle.org) + - Brotli (native library in brotli4j): Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + - jsvg 2.1.0: Copyright (c) 2021-2024 Jannis Weis + - jsoup 1.18.3: Copyright (c) 2009-2024 Jonathan Hedley + - jul-to-slf4j 2.0.17: Copyright (c) 2004-2022 QOS.ch Sarl (Switzerland) + - slf4j-api 2.0.17: Copyright (c) 2004-2022 QOS.ch Sarl (Switzerland) + - ClassGraph (embedded in hazelcast): Copyright (c) 2019 Luke Hutchison + - FastDoubleParser (embedded in jackson-core and hazelcast): Copyright © 2024 Werner Randelshofer, + Switzerland. + - Alpine.js 3.15.12: Copyright the Alpine.js contributors (the shipped file carries no copyright + line) + - Chart.js 4.5.1: (c) 2025 Chart.js Contributors + - Tabler 1.4.0: Copyright 2018-2025 The Tabler Authors; Copyright 2018-2025 codecalm.net Paweł + Kuna + - Bootstrap (bundled inside tabler.min.js) 5.3.7: Copyright 2011-2025 The Bootstrap Authors + - Popper (bundled inside tabler.min.js) 2.x (exact version not stated in the file): Copyright the + Popper contributors (the bundle carries no copyright line for it) + - Font Awesome Free 7.3.0: Copyright 2026 Fonticons, Inc. (https://fontawesome.com, license + summary at https://fontawesome.com/license/free) + - CodeMirror bundle: @codemirror/autocomplete, @codemirror/commands, @codemirror/lang-css, + @codemirror/lang-html, @codemirror/lang-javascript, @codemirror/lang-xml, @codemirror/language, + @codemirror/lint, @codemirror/search, @codemirror/state, @codemirror/theme-one-dark, + @codemirror/view, codemirror: Copyright (C) 2018-2021 by Marijn Haverbeke + and others + - CodeMirror bundle: @lezer/common, @lezer/css, @lezer/highlight, @lezer/html, @lezer/javascript, + @lezer/lr, @lezer/xml, style-mod: Copyright (C) 2018 by Marijn Haverbeke + and others + - CodeMirror bundle: @marijn/find-cluster-break: Copyright (C) 2024 by Marijn Haverbeke + + - CodeMirror bundle: crelt: Copyright (C) 2020 by Marijn Haverbeke + - CodeMirror bundle: w3c-keyname: Copyright (C) 2016 by Marijn Haverbeke + and others + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +==================================================================================================== +3.6 Zero-Clause BSD License +==================================================================================================== +Applies to htmx. + +Zero-Clause BSD +============= + +Permission to use, copy, modify, and/or distribute this software for +any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE +FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY +DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +==================================================================================================== +3.7 Creative Commons CC0 1.0 Universal +==================================================================================================== +Applies to LatencyUtils and HdrHistogram. + +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. + +==================================================================================================== +3.8 HdrHistogram license statement (CC0-1.0 or BSD-2-Clause) +==================================================================================================== +As shipped in HdrHistogram's META-INF/LICENSE.txt. + +The code in this repository code was Written by Gil Tene, Michael Barker, +and Matt Warren, and released to the public domain, as explained at +http://creativecommons.org/publicdomain/zero/1.0/ + +For users of this code who wish to consume it under the "BSD" license +rather than under the public domain or CC0 contribution text mentioned +above, the code found under this directory is *also* provided under the +following license (commonly referred to as the BSD 2-Clause License). This +license does not detract from the above stated release of the code into +the public domain, and simply represents an additional license granted by +the Author. + +----------------------------------------------------------------------------- +** Beginning of "BSD 2-Clause License" text. ** + + Copyright (c) 2012, 2013, 2014, 2015, 2016 Gil Tene + Copyright (c) 2014 Michael Barker + Copyright (c) 2014 Matt Warren + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. + +==================================================================================================== +3.9 FastDoubleParser third-party licenses (fast_float MIT, fast_double_parser BSL-1.0, bigint BSD-2-Clause) +==================================================================================================== +As shipped in META-INF/thirdparty-LICENSE of jackson-core and hazelcast. + +------ +Third-party license for +fast_float, Copyright (c) 2021 The fast_float authors. MIT License. +https://github.com/fastfloat/fast_float +https://github.com/fastfloat/fast_float/blob/35d523195bf7d57aba0e735ad6eba1e6f71ba8d6/LICENSE-MIT + +MIT License + +Copyright (c) 2021 The fast_float authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------ +Third-party license for +bigint, Copyright 2020 Tim Buktu. 2-clause BSD License. +https://github.com/tbuktu/bigint/tree/floatfft +https://github.com/tbuktu/bigint/blob/617c8cd8a7c5e4fb4d919c6a4d11e2586107f029/LICENSE +https://github.com/wrandelshofer/FastDoubleParser/blob/39e123b15b71f29a38a087d16a0bc620fc879aa6/bigint-LICENSE +(We only use those portions of the bigint project that can be licensed under 2-clause BSD License.) + +2-clause BSD License + +Copyright 2022 Tim Buktu + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +==================================================================================================== +3.10 SIL Open Font License, Version 1.1 +==================================================================================================== +Applies to the Font Awesome Free fonts. + +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +==================================================================================================== +3.11 Creative Commons Attribution 4.0 International +==================================================================================================== +Applies to the Font Awesome Free icons. Also at https://creativecommons.org/licenses/by/4.0/legalcode + +Creative Commons Attribution 4.0 International Creative Commons Corporation +("Creative Commons") is not a law firm and does not provide legal services +or legal advice. Distribution of Creative Commons public licenses does not +create a lawyer-client or other relationship. Creative Commons makes its licenses +and related information available on an "as-is" basis. Creative Commons gives +no warranties regarding its licenses, any material licensed under their terms +and conditions, or any related information. Creative Commons disclaims all +liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions +that creators and other rights holders may use to share original works of +authorship and other material subject to copyright and certain other rights +specified in the public license below. The following considerations are for +informational purposes only, are not exhaustive, and do not form part of our +licenses. + +Considerations for licensors: Our public licenses are intended for use by +those authorized to give the public permission to use material in ways otherwise +restricted by copyright and certain other rights. Our licenses are irrevocable. +Licensors should read and understand the terms and conditions of the license +they choose before applying it. Licensors should also secure all rights necessary +before applying our licenses so that the public can reuse the material as +expected. Licensors should clearly mark any material not subject to the license. +This includes other CC-licensed material, or material used under an exception +or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors + +Considerations for the public: By using one of our public licenses, a licensor +grants the public permission to use the licensed material under specified +terms and conditions. If the licensor's permission is not necessary for any +reason–for example, because of any applicable exception or limitation to copyright–then +that use is not regulated by the license. Our licenses grant only permissions +under copyright and certain other rights that a licensor has authority to +grant. Use of the licensed material may still be restricted for other reasons, +including because others have copyright or other rights in the material. A +licensor may make special requests, such as asking that all changes be marked +or described. Although not required by our licenses, you are encouraged to +respect those requests where reasonable. More considerations for the public +: wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution +4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to +be bound by the terms and conditions of this Creative Commons Attribution +4.0 International Public License ("Public License"). To the extent this Public +License may be interpreted as a contract, You are granted the Licensed Rights +in consideration of Your acceptance of these terms and conditions, and the +Licensor grants You such rights in consideration of benefits the Licensor +receives from making the Licensed Material available under these terms and +conditions. + +Section 1 – Definitions. + +a. Adapted Material means material subject to Copyright and Similar Rights +that is derived from or based upon the Licensed Material and in which the +Licensed Material is translated, altered, arranged, transformed, or otherwise +modified in a manner requiring permission under the Copyright and Similar +Rights held by the Licensor. For purposes of this Public License, where the +Licensed Material is a musical work, performance, or sound recording, Adapted +Material is always produced where the Licensed Material is synched in timed +relation with a moving image. + +b. Adapter's License means the license You apply to Your Copyright and Similar +Rights in Your contributions to Adapted Material in accordance with the terms +and conditions of this Public License. + +c. Copyright and Similar Rights means copyright and/or similar rights closely +related to copyright including, without limitation, performance, broadcast, +sound recording, and Sui Generis Database Rights, without regard to how the +rights are labeled or categorized. For purposes of this Public License, the +rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +d. Effective Technological Measures means those measures that, in the absence +of proper authority, may not be circumvented under laws fulfilling obligations +under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, +and/or similar international agreements. + +e. Exceptions and Limitations means fair use, fair dealing, and/or any other +exception or limitation to Copyright and Similar Rights that applies to Your +use of the Licensed Material. + +f. Licensed Material means the artistic or literary work, database, or other +material to which the Licensor applied this Public License. + +g. Licensed Rights means the rights granted to You subject to the terms and +conditions of this Public License, which are limited to all Copyright and +Similar Rights that apply to Your use of the Licensed Material and that the +Licensor has authority to license. + +h. Licensor means the individual(s) or entity(ies) granting rights under this +Public License. + +i. Share means to provide material to the public by any means or process that +requires permission under the Licensed Rights, such as reproduction, public +display, public performance, distribution, dissemination, communication, or +importation, and to make material available to the public including in ways +that members of the public may access the material from a place and at a time +individually chosen by them. + +j. Sui Generis Database Rights means rights other than copyright resulting +from Directive 96/9/EC of the European Parliament and of the Council of 11 +March 1996 on the legal protection of databases, as amended and/or succeeded, +as well as other essentially equivalent rights anywhere in the world. + +k. You means the individual or entity exercising the Licensed Rights under +this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + +1. Subject to the terms and conditions of this Public License, the Licensor +hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, +irrevocable license to exercise the Licensed Rights in the Licensed Material +to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + +2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions +and Limitations apply to Your use, this Public License does not apply, and +You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + +4. Media and formats; technical modifications allowed. The Licensor authorizes +You to exercise the Licensed Rights in all media and formats whether now known +or hereafter created, and to make technical modifications necessary to do +so. The Licensor waives and/or agrees not to assert any right or authority +to forbid You from making technical modifications necessary to exercise the +Licensed Rights, including technical modifications necessary to circumvent +Effective Technological Measures. For purposes of this Public License, simply +making modifications authorized by this Section 2(a)(4) never produces Adapted +Material. + + 5. Downstream recipients. + +A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed +Material automatically receives an offer from the Licensor to exercise the +Licensed Rights under the terms and conditions of this Public License. + +B. No downstream restrictions. You may not offer or impose any additional +or different terms or conditions on, or apply any Effective Technological +Measures to, the Licensed Material if doing so restricts exercise of the Licensed +Rights by any recipient of the Licensed Material. + +6. No endorsement. Nothing in this Public License constitutes or may be construed +as permission to assert or imply that You are, or that Your use of the Licensed +Material is, connected with, or sponsored, endorsed, or granted official status +by, the Licensor or others designated to receive attribution as provided in +Section 3(a)(1)(A)(i). + + b. Other rights. + +1. Moral rights, such as the right of integrity, are not licensed under this +Public License, nor are publicity, privacy, and/or other similar personality +rights; however, to the extent possible, the Licensor waives and/or agrees +not to assert any such rights held by the Licensor to the limited extent necessary +to allow You to exercise the Licensed Rights, but not otherwise. + +2. Patent and trademark rights are not licensed under this Public License. + +3. To the extent possible, the Licensor waives any right to collect royalties +from You for the exercise of the Licensed Rights, whether directly or through +a collecting society under any voluntary or waivable statutory or compulsory +licensing scheme. In all other cases the Licensor expressly reserves any right +to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following +conditions. + + a. Attribution. + +1. If You Share the Licensed Material (including in modified form), You must: + +A. retain the following if it is supplied by the Licensor with the Licensed +Material: + +i. identification of the creator(s) of the Licensed Material and any others +designated to receive attribution, in any reasonable manner requested by the +Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + +v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + +B. indicate if You modified the Licensed Material and retain an indication +of any previous modifications; and + +C. indicate the Licensed Material is licensed under this Public License, and +include the text of, or the URI or hyperlink to, this Public License. + +2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner +based on the medium, means, and context in which You Share the Licensed Material. +For example, it may be reasonable to satisfy the conditions by providing a +URI or hyperlink to a resource that includes the required information. + +3. If requested by the Licensor, You must remove any of the information required +by Section 3(a)(1)(A) to the extent reasonably practicable. + +4. If You Share Adapted Material You produce, the Adapter's License You apply +must not prevent recipients of the Adapted Material from complying with this +Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to +Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, +reuse, reproduce, and Share all or a substantial portion of the contents of +the database; + +b. if You include all or a substantial portion of the database contents in +a database in which You have Sui Generis Database Rights, then the database +in which You have Sui Generis Database Rights (but not its individual contents) +is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share all or +a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace +Your obligations under this Public License where the Licensed Rights include +other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. Unless otherwise separately undertaken by the Licensor, to the extent possible, +the Licensor offers the Licensed Material as-is and as-available, and makes +no representations or warranties of any kind concerning the Licensed Material, +whether express, implied, statutory, or other. This includes, without limitation, +warranties of title, merchantability, fitness for a particular purpose, non-infringement, +absence of latent or other defects, accuracy, or the presence or absence of +errors, whether or not known or discoverable. Where disclaimers of warranties +are not allowed in full or in part, this disclaimer may not apply to You. + +b. To the extent possible, in no event will the Licensor be liable to You +on any legal theory (including, without limitation, negligence) or otherwise +for any direct, special, indirect, incidental, consequential, punitive, exemplary, +or other losses, costs, expenses, or damages arising out of this Public License +or use of the Licensed Material, even if the Licensor has been advised of +the possibility of such losses, costs, expenses, or damages. Where a limitation +of liability is not allowed in full or in part, this limitation may not apply +to You. + +c. The disclaimer of warranties and limitation of liability provided above +shall be interpreted in a manner that, to the extent possible, most closely +approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights +licensed here. However, if You fail to comply with this Public License, then +Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section +6(a), it reinstates: + +1. automatically as of the date the violation is cured, provided it is cured +within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + +c. For the avoidance of doubt, this Section 6(b) does not affect any right +the Licensor may have to seek remedies for Your violations of this Public +License. + +d. For the avoidance of doubt, the Licensor may also offer the Licensed Material +under separate terms or conditions or stop distributing the Licensed Material +at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or +conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed +Material not stated herein are separate from and independent of the terms +and conditions of this Public License. + +Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not +be interpreted to, reduce, limit, restrict, or impose conditions on any use +of the Licensed Material that could lawfully be made without permission under +this Public License. + +b. To the extent possible, if any provision of this Public License is deemed +unenforceable, it shall be automatically reformed to the minimum extent necessary +to make it enforceable. If the provision cannot be reformed, it shall be severed +from this Public License without affecting the enforceability of the remaining +terms and conditions. + +c. No term or condition of this Public License will be waived and no failure +to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation +upon, or waiver of, any privileges and immunities that apply to the Licensor +or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative +Commons may elect to apply one of its public licenses to material it publishes +and in those instances will be considered the "Licensor." The text of the +Creative Commons public licenses is dedicated to the public domain under the +CC0 Public Domain Dedication. Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as otherwise +permitted by the Creative Commons policies published at creativecommons.org/policies, +Creative Commons does not authorize the use of the trademark "Creative Commons" +or any other trademark or logo of Creative Commons without its prior written +consent including, without limitation, in connection with any unauthorized +modifications to any of its public licenses or any other arrangements, understandings, +or agreements concerning use of licensed material. For the avoidance of doubt, +this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. + + + +4. Notices of Apache-licensed components +---------------------------------------- + +Reproduced from the NOTICE files the components ship, as their licenses ask. Identical notices are +printed once. + +==================================================================================================== +NOTICE.txt of: attoparser 2.0.7.RELEASE +==================================================================================================== + Copyright (c) 2012-2022, The ATTOPARSER team (https://www.attoparser.org) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +==================================================================================================== +NOTICE.txt of: commons-logging 1.3.6 +==================================================================================================== +Apache Commons Logging +Copyright 2001-2026 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (https://www.apache.org/). + +==================================================================================================== +FastDoubleParser-NOTICE of: hazelcast 5.6.0, jackson-core 3.1.2 +==================================================================================================== +# FastDoubleParser + +This is a Java port of Daniel Lemire's fast_float project. +This project provides parsers for double, float, BigDecimal and BigInteger values. + +## Copyright + +Copyright © 2024 Werner Randelshofer, Switzerland. + +## Licensing + +This code is licensed under MIT License. +https://github.com/wrandelshofer/FastDoubleParser/blob/522be16e145f43308c43b23094e31d5efcaa580e/LICENSE +(The file 'LICENSE' is included in the sources and classes Jar files that are released by this project +- as is required by that license.) + +Some portions of the code have been derived from other projects. +All these projects require that we include a copyright notice, and some require that we also include some text of their +license file. + +fast_double_parser, Copyright (c) 2022 Daniel Lemire. BSL License. +https://github.com/lemire/fast_double_parser +https://github.com/lemire/fast_double_parser/blob/07d9189a8fb815fe800cb15ca022e7a07093236e/LICENSE.BSL +(The file 'thirdparty-LICENSE' is included in the sources and classes Jar files that are released by this project +- as is required by that license.) + +fast_float, Copyright (c) 2021 The fast_float authors. MIT License. +https://github.com/fastfloat/fast_float +https://github.com/fastfloat/fast_float/blob/cc1e01e9eee74128e48d51488a6b1df4a767a810/LICENSE-MIT +(The file 'thirdparty-LICENSE' is included in the sources and classes Jar files that are released by this project +- as is required by that license.) + +bigint, Copyright 2020 Tim Buktu. 2-clause BSD License. +https://github.com/tbuktu/bigint/tree/floatfft +https://github.com/tbuktu/bigint/blob/617c8cd8a7c5e4fb4d919c6a4d11e2586107f029/LICENSE +https://github.com/wrandelshofer/FastDoubleParser/blob/39e123b15b71f29a38a087d16a0bc620fc879aa6/bigint-LICENSE +(We only use those portions of the bigint project that can be licensed under 2-clause BSD License.) +(The file 'thirdparty-LICENSE' is included in the sources and classes Jar files that are released by this project +- as is required by that license.) + +==================================================================================================== +NOTICE of: hazelcast 5.6.0 +==================================================================================================== +// ------------------------------------------------------------------ +// NOTICE file corresponding to the section 4d of The Apache License, +// Version 2.0, in this case for +// ------------------------------------------------------------------ + +Objenesis +Copyright 2006-2024 Joe Walnes, Henri Tremblay, Leonardo Mesquita + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +The packages: + +com.hazelcast.internal.util.collection +com.hazelcast.internal.util.concurrent + +and the classes: + +com.hazelcast.internal.util.QuickMath +com.hazelcast.client.impl.protocol.util.UnsafeBuffer +com.hazelcast.client.impl.protocol.util.BufferBuilder + +contain code originating from the Agrona project +(https://github.com/real-logic/Agrona). + +The class com.hazelcast.internal.util.HashUtil contains code originating +from the Koloboke project (https://github.com/OpenHFT/Koloboke). + +The class classloading.ThreadLocalLeakTestUtils contains code originating +from the Tomcat project (https://github.com/apache/tomcat). + +com.hazelcast.internal.cluster.fd.PhiAccrualFailureDetector contains code originating +from the Akka project (https://github.com/akka/akka/). + +The package com.hazelcast.internal.json contains code originating +from minimal-json project (https://github.com/ralfstx/minimal-json). + +The class com.hazelcast.instance.impl.MobyNames contains code originating +from The Moby Project (https://github.com/moby/moby). + +The class com.hazelcast.internal.util.graph.BronKerboschCliqueFinder contains code +originating from The JGraphT Project (https://github.com/jgrapht/jgrapht). + +The packages: +com.hazelcast.sql +com.hazelcast.jet.sql + +contain code originating from the Apache Calcite (https://github.com/apache/calcite) + +The class com.hazelcast.jet.kafka.impl.ResumeTransactionUtil contains +code derived from the Apache Flink project. + +The class com.hazelcast.internal.util.ConcurrentReferenceHashMap contains code written by Doug Lea +and updated within the WildFly project (https://github.com/wildfly/wildfly). + +The classes: +com.hazelcast.cp.internal.raft.impl.state.FollowerState +com.hazelcast.cp.internal.raft.impl.state.FollowerStateTest +com.hazelcast.cp.internal.raft.impl.SlowFollowerBackoffTest + +contain code originating from the MicroRaft project (https://github.com/MicroRaft/MicroRaft) + +# Jackson JSON processor + +Jackson is a high-performance, Free/Open Source JSON processing library. +It was originally written by Tatu Saloranta (tatu.saloranta@iki.fi), and has +been in development since 2007. +It is currently developed by a community of developers. + +## Copyright + +Copyright 2007-, Tatu Saloranta (tatu.saloranta@iki.fi) + +## Licensing + +Jackson 2.x core and extension components are licensed under Apache License 2.0 +To find the details that apply to this artifact see the accompanying LICENSE file. + +## Credits + +A list of contributors may be found from CREDITS(-2.x) file, which is included +in some artifacts (usually source distributions); but is always available +from the source code management (SCM) system project uses. + +## FastDoubleParser + +jackson-core bundles a shaded copy of FastDoubleParser . +That code is available under an MIT license +under the following copyright. + +Copyright © 2023 Werner Randelshofer, Switzerland. MIT License. + +See FastDoubleParser-NOTICE for details of other source code included in FastDoubleParser +and the licenses and copyrights that apply to that code. + +Jackson components are licensed under Apache (Software) License, version 2.0, +as per accompanying LICENSE file. + +A list of contributors may be found from CREDITS file, which is included +in some artifacts (usually source distributions); but is always available +from the source code management (SCM) system project uses. + +==================================================================================================== +NOTICE of: jackson-annotations 2.21 +==================================================================================================== +# Jackson JSON processor + +Jackson is a high-performance, Free/Open Source JSON processing library. +It was originally written by Tatu Saloranta (tatu.saloranta@iki.fi), and has +been in development since 2007. +It is currently developed by a community of developers. + +## Copyright + +Copyright 2007-, Tatu Saloranta (tatu.saloranta@iki.fi) + +## Licensing + +Jackson 2.x core and extension components are licensed under Apache License 2.0 +To find the details that apply to this artifact see the accompanying LICENSE file. + +## Credits + +A list of contributors may be found from CREDITS(-2.x) file, which is included +in some artifacts (usually source distributions); but is always available +from the source code management (SCM) system project uses. + +==================================================================================================== +NOTICE of: jackson-core 3.1.2 +==================================================================================================== +# Jackson JSON processor + +Jackson is a high-performance, Free/Open Source JSON processing library. +It was originally written by Tatu Saloranta (tatu.saloranta@iki.fi), and has +been in development since 2007. +It is currently developed by a community of developers. + +## Copyright + +Copyright 2007-, Tatu Saloranta (tatu.saloranta@iki.fi) + +## Licensing + +Jackson 3.x core and extension components are licensed under Apache License 2.0 +To find the details that apply to this artifact see the accompanying LICENSE file. + +## Credits + +A list of contributors may be found from CREDITS file, which is included +in some artifacts (usually source distributions); but is always available +from the source code management (SCM) system project uses. + +## FastDoubleParser + +jackson-core bundles a shaded copy of FastDoubleParser . +That code is available under an MIT license +under the following copyright. + +Copyright © 2023 Werner Randelshofer, Switzerland. MIT License. + +See FastDoubleParser-NOTICE for details of other source code included in FastDoubleParser +and the licenses and copyrights that apply to that code. + +==================================================================================================== +NOTICE of: jackson-databind 3.1.2 +==================================================================================================== +# Jackson JSON processor + +Jackson is a high-performance, Free/Open Source JSON processing library. +It was originally written by Tatu Saloranta (tatu.saloranta@iki.fi), and has +been in development since 2007. +It is currently developed by a community of developers. + +## Copyright + +Copyright 2007-, Tatu Saloranta (tatu.saloranta@iki.fi) + +## Licensing + +Jackson 3.x core and extension components are licensed under Apache License 2.0 +To find the details that apply to this artifact see the accompanying LICENSE file. + +## Credits + +A list of contributors may be found from CREDITS file, which is included +in some artifacts (usually source distributions); but is always available +from the source code management (SCM) system project uses. + +==================================================================================================== +NOTICE of: jackson-dataformat-yaml 3.1.2 +==================================================================================================== +# Jackson JSON processor + +Jackson is a high-performance, Free/Open Source JSON processing library. +It was originally written by Tatu Saloranta (tatu.saloranta@iki.fi), and has +been in development since 2007. +It is currently developed by a community of developers. + +## Copyright + +Copyright 2007-, Tatu Saloranta (tatu.saloranta@iki.fi) + +## Licensing + +Jackson components are licensed under Apache (Software) License, version 2.0, +as per accompanying LICENSE file. + +## Credits + +A list of contributors may be found from CREDITS file, which is included +in some artifacts (usually source distributions); but is always available +from the source code management (SCM) system project uses. + +==================================================================================================== +NOTICE.md of: jakarta.enterprise.cdi-api 4.1.0, jakarta.enterprise.lang-model 4.1.0 +==================================================================================================== +# Notices for Jakarta Contexts and Dependency Injection + +This content is produced and maintained by the Jakarta Contexts and Dependency Injection +project. + +* Project home: https://projects.eclipse.org/projects/ee4j.cdi + +## Trademarks + +Jakarta Contexts and Dependency Injection is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Apache License v. 2.0 which is available at +http://www.apache.org/licenses/LICENSE-2.0 + +SPDX-License-Identifier: Apache-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/jakartaee/cdi +* https://github.com/jakartaee/cdi-tck +* https://github.com/jakartaee/inject +* https://github.com/jakartaee/inject-spec +* https://github.com/jakartaee/inject-tck + +The project also maintains the following legacy CPL licensed source code repositories: + +* https://github.com/eclipse-ee4j/cdi-cpl +* https://github.com/eclipse-ee4j/cdi-tck-cpl + +## Third-party Content + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.inject-api 2.0.1 +==================================================================================================== +# Notices for Eclipse Jakarta Dependency Injection + +This content is produced and maintained by the Eclipse Jakarta Dependency Injection project. + +* Project home: https://projects.eclipse.org/projects/cdi.batch + +## Trademarks + +Jakarta Dependency Injection is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Apache License, Version 2.0 which is available at +https://www.apache.org/licenses/LICENSE-2.0. + +SPDX-License-Identifier: Apache-2.0 + +## Source Code + +The project maintains the following source code repositories: + +https://github.com/eclipse-ee4j/injection-api +https://github.com/eclipse-ee4j/injection-spec +https://github.com/eclipse-ee4j/injection-tck + +## Third-party Content + +This project leverages the following third party content. + +None + +## Cryptography + +None + +==================================================================================================== +NOTICE of: log4j-api 2.25.4 +==================================================================================================== +Apache Log4j API +Copyright 1999-2026 The Apache Software Foundation + + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +==================================================================================================== +NOTICE of: log4j-to-slf4j 2.25.4 +==================================================================================================== +Log4j API to SLF4J Adapter +Copyright 1999-2026 The Apache Software Foundation + + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +==================================================================================================== +NOTICE of: micrometer-commons 1.16.5, micrometer-core 1.16.5, micrometer-jakarta9 1.16.5, +micrometer-observation 1.16.5, micrometer-registry-prometheus 1.16.5 +==================================================================================================== +Micrometer + +Copyright (c) 2017-Present VMware, Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------------------- + +This product contains a modified portion of 'io.netty.util.internal.logging', +in the Netty/Common library distributed by The Netty Project: + + * Copyright 2013 The Netty Project + * License: Apache License v2.0 + * Homepage: https://netty.io + +This product contains a modified portion of 'StringUtils.isBlank()', +in the Commons Lang library distributed by The Apache Software Foundation: + + * Copyright 2001-2019 The Apache Software Foundation + * License: Apache License v2.0 + * Homepage: https://commons.apache.org/proper/commons-lang/ + +This product contains a modified portion of 'JsonUtf8Writer', +in the Moshi library distributed by Square, Inc: + + * Copyright 2010 Google Inc. + * License: Apache License v2.0 + * Homepage: https://github.com/square/moshi + +This product contains a modified portion of the 'org.springframework.lang' +package in the Spring Framework library, distributed by VMware, Inc: + + * Copyright 2002-2019 the original author or authors. + * License: Apache License v2.0 + * Homepage: https://spring.io/projects/spring-framework + +==================================================================================================== +notice.txt of: spring-aop 7.0.7, spring-beans 7.0.7, spring-context 7.0.7, spring-core 7.0.7, +spring-expression 7.0.7, spring-web 7.0.7, spring-webmvc 7.0.7 +==================================================================================================== +Spring Framework 7.0.7 +Copyright (c) 2002-2026 Pivotal, Inc. + +This product is licensed to you under the Apache License, Version 2.0 +(the "License"). You may not use this product except in compliance with +the License. + +This product may include a number of subcomponents with separate +copyright notices and license terms. Your use of the source code for +these subcomponents is subject to the terms and conditions of the +subcomponent's license, as noted in the license.txt file. + +==================================================================================================== +NOTICE.txt of: spring-boot 4.0.6, spring-boot-actuator 4.0.6, spring-boot-actuator-autoconfigure +4.0.6, spring-boot-autoconfigure 4.0.6, spring-boot-health 4.0.6, spring-boot-http-converter 4.0.6, +spring-boot-jackson 4.0.6, spring-boot-jarmode-tools 4.0.6, spring-boot-jetty 4.0.6, +spring-boot-micrometer-metrics 4.0.6, spring-boot-micrometer-observation 4.0.6, spring-boot-security +4.0.6, spring-boot-servlet 4.0.6, spring-boot-thymeleaf 4.0.6, spring-boot-web-server 4.0.6, +spring-boot-webmvc 4.0.6 +==================================================================================================== +Spring Boot 4.0.6 +Copyright (c) 2012-2026 VMware, Inc. + +This product is licensed to you under the Apache License, Version 2.0 +(the "License"). You may not use this product except in compliance with +the License. + +==================================================================================================== +NOTICE.txt of: thymeleaf-spring6 3.1.5.RELEASE +==================================================================================================== + Copyright (c) 2011-2026 Thymeleaf (http://www.thymeleaf.org) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +==================================================================================================== +NOTICE of: tomcat-embed-el 11.0.21 +==================================================================================================== +Apache Tomcat +Copyright 1999-2026 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +==================================================================================================== +NOTICE.txt of: unbescape 1.1.6.RELEASE +==================================================================================================== + Copyright (c) 2014-2017, The UNBESCAPE team (http://www.unbescape.org) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +5. Notices of Eclipse-licensed components +----------------------------------------- + +Reproduced from the NOTICE files the components ship, as their licenses ask. Identical notices are +printed once. + +==================================================================================================== +NOTICE.md of: angus-activation 2.0.3 +==================================================================================================== +# Notices for Eclipse Angus + +This content is produced and maintained by the Eclipse Angus project. + +* Project home: https://projects.eclipse.org/projects/ee4j.angus + +## Trademarks + +Eclipse Angus is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Distribution License v1.0 which is available at +https://www.eclipse.org/org/documents/edl-v10.php. + +SPDX-License-Identifier: BSD-3-Clause + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/eclipse-ee4j/angus-activation +* https://github.com/eclipse-ee4j/angus-mail + +## Third-party Content + +This project leverages the following third party content. + +None + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: angus-mail 2.0.5 +==================================================================================================== +# Notices for Jakarta Mail + +This content is produced and maintained by the Jakarta Mail project. + +* Project home: https://projects.eclipse.org/projects/ee4j.mail + +## Trademarks + +Jakarta Mail is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +http://www.eclipse.org/legal/epl-2.0. This Source Code may also be made +available under the following Secondary Licenses when the conditions for such +availability set forth in the Eclipse Public License v. 2.0 are satisfied: GNU +General Public License, version 2 with the GNU Classpath Exception which is +available at https://www.gnu.org/software/classpath/license.html. + +SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/eclipse-ee4j/mail + +## Third-party Content + +This project leverages the following third party content. + +None + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.activation-api 2.1.4 +==================================================================================================== +# Notices for Jakarta Activation + +This content is produced and maintained by the Jakarta Activation project. + +* Project home: https://projects.eclipse.org/projects/ee4j.jaf + +## Trademarks + +Jakarta Activation is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +https://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License v1.0 +which is available at https://www.eclipse.org/org/documents/edl-v10.php. This +Source Code may also be made available under the following Secondary Licenses +when the conditions for such availability set forth in the Eclipse Public +License v. 2.0 are satisfied: (secondary) GPL-2.0 with Classpath-exception-2.0 +which is available at https://openjdk.java.net/legal/gplv2+ce.html. + +SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause OR GPL-2.0-only with +Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/jakartaee/jaf-api +* https://github.com/jakartaee/jaf-tck + +## Third-party Content + +This project leverages the following third party content. + +Apache Ant (1.9.6) + +* License: Apache License, 2.0, W3C License, Public Domain + +Apache Ant (1.9.6) + +* License: Apache License, 2.0, W3C License, Public Domain + +Apache commons-lang (3.5) + +* License: Apache-2.0 + +font-awesome (4.7.0) + +* License: OFL-1.1 AND MIT + +jsoup (1.10.2) + +* License: MIT + +JTHarness (5.0) + +* License: (GPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0) +* Project: https://wiki.openjdk.java.net/display/CodeTools/JT+Harness +* Source: http://hg.openjdk.java.net/code-tools/jtharness/ + +JUnit (4.12) + +* License: Eclipse Public License + +normalize.css (3.0.2) + +* License: MIT +* Project: http://necolas.github.io/normalize.css/ +* Source: http://necolas.github.io/normalize.css/ + +SigTest (4.0) + +* License: GPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 +* Project: https://wiki.openjdk.java.net/display/CodeTools/sigtest +* Source: http://hg.openjdk.java.net/code-tools/sigtest/file/c57f97e2ac2f + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.annotation-api 3.0.0 +==================================================================================================== +# Notices for Jakarta Annotations + +This content is produced and maintained by the Jakarta Annotations project. + +* Project home: https://projects.eclipse.org/projects/ee4j.ca + +## Trademarks + +Jakarta Annotations™ is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +https://www.eclipse.org/legal/epl-2.0. This Source Code may also be made +available under the following Secondary Licenses when the conditions for such +availability set forth in the Eclipse Public License v. 2.0 are satisfied: +GPL-2.0 with Classpath-exception-2.0 which is available at +https://openjdk.java.net/legal/gplv2+ce.html. + +SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only with Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/jakartaee/common-annotations-api + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.interceptor-api 2.2.0 +==================================================================================================== +# Notices for Eclipse Project for Interceptors + +This content is produced and maintained by the Eclipse Project for Interceptors +project. + +* Project home: https://projects.eclipse.org/projects/ee4j.interceptors + +## Trademarks + +Eclipse Project for Interceptors is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +http://www.eclipse.org/legal/epl-2.0. This Source Code may also be made +available under the following Secondary Licenses when the conditions for such +availability set forth in the Eclipse Public License v. 2.0 are satisfied: GNU +General Public License, version 2 with the GNU Classpath Exception which is +available at https://www.gnu.org/software/classpath/license.html. + +SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/eclipse-ee4j/interceptor-api + +## Third-party Content + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.mail-api 2.1.5 +==================================================================================================== +# Notices for Jakarta Mail + +This content is produced and maintained by the Jakarta Mail project. + +* Project home: [https://projects.eclipse.org/projects/ee4j.mail](https://projects.eclipse.org/projects/ee4j.mail) + +## Trademarks + +Jakarta Mail is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +[https://www.eclipse.org/legal/epl-2.0](https://www.eclipse.org/legal/epl-2.0). This Source Code may also be made +available under the following Secondary Licenses when the conditions for such +availability set forth in the Eclipse Public License v. 2.0 are satisfied: +(secondary) GPL-2.0 with Classpath-exception-2.0 which is available at +[https://openjdk.java.net/legal/gplv2+ce.html](https://openjdk.java.net/legal/gplv2+ce.html). + +SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only with Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* [https://github.com/jakartaee/mail-api](https://github.com/jakartaee/mail-api) +* [https://github.com/jakartaee/mail-tck](https://github.com/jakartaee/mail-tck) +* [https://github.com/jakartaee/mail-spec](https://github.com/jakartaee/mail-spec) + +## Third-party Content + +This project leverages the following third party content. + +Apache Ant (1.9.6) + +* License: Apache License, 2.0, W3C License, Public Domain + +commons-lang3 (3.5) + +* License: Apache-2.0 + +font-awesome (4.7.0) + +* License: OFL-1.1 AND MIT + +jsoup (1.10.2) + +* License: MIT + +JTHarness (5.0) + +* License: GPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + +normalize.css (3.0.2) + +* License: MIT + +SigTest (4.0) + +* License: (GPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0) +* Project: [https://wiki.openjdk.java.net/display/CodeTools/sigtest](https://wiki.openjdk.java.net/display/CodeTools/sigtest) +* Source: [http://hg.openjdk.java.net/code-tools/sigtest/file/c57f97e2ac2f](http://hg.openjdk.java.net/code-tools/sigtest/file/c57f97e2ac2f) + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.servlet-api 6.1.0 +==================================================================================================== +# Notices for Eclipse Project for Servlet + +This content is produced and maintained by the Eclipse Project for Servlet +project. + +* Project home: https://projects.eclipse.org/projects/ee4j.servlet + +## Trademarks + +Eclipse Project for Servlet is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +http://www.eclipse.org/legal/epl-2.0. This Source Code may also be made +available under the following Secondary Licenses when the conditions for such +availability set forth in the Eclipse Public License v. 2.0 are satisfied: GNU +General Public License, version 2 with the GNU Classpath Exception which is +available at https://www.gnu.org/software/classpath/license.html. Portions of +this program and the accompanying materials are made available under the terms +of the Apache License, version 2.0 which is available at +https://www.apache.org/licenses/LICENSE-2.0. + +SPDX-License-Identifier: (EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0) AND Apache-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/eclipse-ee4j/servlet-api + +## Third-party Content + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.transaction-api 2.0.1 +==================================================================================================== +# Notices for Jakarta Transactions + +This content is produced and maintained by the Jakarta Transactions project. + +* Project home: https://projects.eclipse.org/projects/ee4j.jta + +## Trademarks + +Jakarta Transactions is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +http://www.eclipse.org/legal/epl-2.0. This Source Code may also be made +available under the following Secondary Licenses when the conditions for such +availability set forth in the Eclipse Public License v. 2.0 are satisfied: GNU +General Public License, version 2 with the GNU Classpath Exception which is +available at https://www.gnu.org/software/classpath/license.html. + +SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/eclipse-ee4j/jta-api + +## Third-party Content + +This project leverages the following third party content. + +None + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. + +==================================================================================================== +NOTICE.md of: jakarta.websocket-api 2.2.0, jakarta.websocket-client-api 2.2.0 +==================================================================================================== +# Notices for Jakarta WebSocket + +This content is produced and maintained by the Jakarta WebSocket project. + +* Project home: https://projects.eclipse.org/projects/ee4j.websocket + +## Trademarks + +Jakarta WebSocket is a trademark of the Eclipse Foundation. + +## Copyright + +All content is the property of the respective authors or their employers. For +more information regarding authorship of content, please consult the listed +source code repository logs. + +## Declared Project Licenses + +This program and the accompanying materials are made available under the terms +of the Eclipse Public License v. 2.0 which is available at +http://www.eclipse.org/legal/epl-2.0. This Source Code may also be made +available under the following Secondary Licenses when the conditions for such +availability set forth in the Eclipse Public License v. 2.0 are satisfied: GNU +General Public License, version 2 with the GNU Classpath Exception which is +available at https://www.gnu.org/software/classpath/license.html. + +SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + +## Source Code + +The project maintains the following source code repositories: + +* https://github.com/eclipse-ee4j/websocket-api + +## Third-party Content + +This project leverages the following third party content. + +None + +## Cryptography + +Content may contain encryption software. The country in which you are currently +may have restrictions on the import, possession, and use, and/or re-export to +another country, of encryption software. BEFORE using any encryption software, +please check the country's laws, regulations and policies concerning the import, +possession, or use, and re-export of encryption software, to see if this is +permitted. diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md new file mode 100644 index 0000000..3151f0b --- /dev/null +++ b/docs/ADMINISTRATION.md @@ -0,0 +1,2786 @@ +# Runway — Administration Manual + +> **Audience:** **application administrators** — the operators who install and run the Runway +> platform itself (not the people who manage an individual site). +> **What this is:** everything needed to install, configure, run, and maintain a Runway server, +> including managing plugins, sites, and application users. + +> **Doc status.** Every section covering a built feature is written, including **§14 Monitoring & metrics**. +> Each change ships with its documentation. This document is self-contained. + +--- + +## 1. Overview & audience + +Runway is a **multi-site web platform**: one running server hosts many independent **sites** +(tenancies), each with its own content, presentation, users, and configuration, resolved by the +request's `Host` header. This manual is for the **application administrator** — the operator who +installs, configures, runs, and maintains that server. + +**What you control.** As an application administrator you run the *platform*: its configuration, +the **plugins** it loads, the **sites** it hosts (create, suspend, resume, delete), the +**application-level user accounts** (fellow operators), and the platform-wide settings. You do all +of this from the **operator console** at `/__app`, after signing in at `/app/login`. The console answers on +the default site's host names and on host names that serve no site (the server's IP address, `localhost`), but +not on a host name that serves another site, or only on the names you list in `runway.console.hosts` (**§8.6**). + +The console's top bar is organized into **dropdown groups**: **Dashboard** (top-level), **Sites** +(Manage sites, Backups, Templates, Site master users), **Access** (App users, Permissions), +**Activity** (Bandwidth, Logs), the top-level **Plugins**, and **Settings** (Platform settings, About +Runway). Items you cannot open are hidden — each entry is shown exactly when its screen would let you in +(the same check the screen makes: a grantable permission such as **Logs** → `VIEW_AUDIT`, **Bandwidth** → +`VIEW_BANDWIDTH`, **Templates** → `MANAGE_STYLES`, **Manage sites** → `VIEW_TENANCIES` or `MANAGE_SITE_HOSTS`, +or the superadmin/wildcard-admin gate of **Backups**, **Permissions** and **Platform settings**) — and a group left with nothing in it is hidden too, so the menu +never offers a link that answers "forbidden". Hiding is only presentation: every screen still checks on its +own. Section references below name the +destination screen; the parenthetical path is the direct URL. A **language switcher** (the globe/language +icon next to your username) sets the console's display language — English or Spanish by default (see +`runway.operator.ui-languages` in **§8**); the choice is remembered per operator and does not affect any +site's own language. + +**What you do NOT do.** You never operate *inside* a site as if you were a site user — you cannot +edit a site's pages, its content, or its per-site data. That is the site manager's job, done in a +separate realm and a separate console. This is a deliberate, foundational boundary: + +- **Two user realms that never cross.** The **application realm** (operators; login `/app/login`, + console `/__app`) and the **tenant realm** (site users; login `/login`, console `/__admin`) have + separate login URLs and separate user stores. Authenticating in one never grants the other — even + in the same browser, an application session and a site session coexist without crossing. A + compromised or buggy action in one site is contained to that one site; the operator and the other + sites are never exposed. +- **The application superadmin runs the platform but cannot enter a site;** every **site + superadmin** fully manages its site but can never reach the application realm. You provision a + site's first superadmin when you create the site, and you can reset its password from the console, + but you cannot use it to act inside the site. + +The companion document for operating an individual site is the *Site Manager & Designer Guide* +([SITE-MANAGER-GUIDE.md](SITE-MANAGER-GUIDE.md)); its §2 also describes keyboard and screen-reader use, which +is the same in the platform console (skip link, Esc then Tab out of a code editor, Down arrow or Shift+F10 for +a listing table's column menu). Day-to-day operational troubleshooting lives in +[OPERATIONS.md](OPERATIONS.md). + +## 2. System requirements + +| Requirement | Detail | +|---|---| +| **OS** | Linux with **systemd** (the installer and unit target it; tested on RHEL-family — Rocky/Fedora/Alma — and Debian-family). macOS/Windows are not covered by the installer. | +| **Java** | A **JDK or JRE 25+** on the host. A JRE is sufficient — Runway does **not** compile at runtime. The installer auto-detects a 25+ runtime (Zulu, Temurin, generic OpenJDK) or you point it with `--java-home`. | +| **Database** | **None.** The kernel is filesystem/YAML-backed on purpose; there is no SQL server to install or configure, and the first-run wizard never asks for one. A deployment that genuinely needs a database adds it as a plugin. | +| **CPU / RAM** | Modest. The service runs in one JVM; the shipped heap is `-Xms256m -Xmx1g` (`JAVA_OPTS` in the unit), which suits a small VM. Note the sizing interlock: each Argon2id password verification costs 19–32 MiB, and the hash pool is bounded (`runway.security.max-concurrent-hashes`, default 8) precisely so a login flood cannot exhaust heap — keep `-Xmx` comfortably above `max-concurrent-hashes × memory-cost`. | +| **Disk** | The code footprint is small (a single fat jar). Plan capacity for **editable state**: `external/` (config + all site folders), `logs/`, and `backups/` (site backup archives can be large — see **§13**). | +| **Network / ports** | One HTTP listener. By default Runway serves **plain HTTP on port 8080** and expects a reverse proxy (HAProxy/nginx/Caddy) in front to terminate TLS (**§7**). Change the port with `--server.port=` (`RUNWAY_OPTS`). Binding a privileged port (80/443) directly needs `CAP_NET_BIND_SERVICE` — see the unit (**§6**). | + +Clustering is **opt-in and off by default** (`runway.cluster.enabled`, set in the external +`application.yml`). Left off — the default, and what the sizing figures below assume — no Hazelcast member +starts, no session repository is wired, and the container's own `HttpSession` is used: one instance, scaled +vertically on a bigger host. Turned on, several instances run behind a load balancer — HTTP sessions live in +a Hazelcast `IMap` shared by every node (so a session survives losing the node that created it, with no +sticky-session requirement), and a Hazelcast topic relays cache-invalidation events (site, page, content and +per-site plugin-config changes) so every node evicts in step. Each node is a Hazelcast member itself by +default (`runway.cluster.topology: EMBEDDED`, `tcp-ip` discovery with an explicit member list), or a client +of a separately-run grid (`CLIENT_SERVER`). + +**The clustering keys.** All of them live in the external `application.yml` (or the environment) of **every** +node, with the same values on each, and are read once at startup: a change needs a restart of every node. None is +on a console screen, because one node's console cannot change the others. While `enabled` is `false` none of the +other keys is read, so a mistake in them shows only when you switch clustering on. Nor are they read in WIZARD mode: +clustering starts only once first-run setup is done. + +| Key | Default | What it does | +|---|---|---| +| `runway.cluster.enabled` | `false` | The master switch. Off, the node runs alone with the servlet container's own sessions. | +| `runway.cluster.cluster-name` | `runway` | The Hazelcast cluster name. Members and clients join only peers with the same name, so two estates on one network stay apart. With `CLIENT_SERVER` it must equal the name of the grid you connect to. | +| `runway.cluster.topology` | `embedded` | `embedded`: every node is a Hazelcast member and reads only the `embedded.*` keys. `client-server` (or `CLIENT_SERVER`): every node is a client of a grid you run separately and reads only the `client.*` keys. Any other value stops startup. | +| `runway.cluster.session-ttl` | `30m` | How long an idle signed-in session lives while clustering is on. **Keep it equal to `server.servlet.session.timeout`** (§8): with clustering on, this value decides the timeout, and with it off that one does, so equal values mean switching clustering never changes when people are signed out. Write the unit (`30m`, `2h`): a bare number is read as **milliseconds** here, unlike `server.servlet.session.timeout`, where it means seconds. On an embedded member the grid also drops idle session entries itself after this time, but never sooner than 60 seconds. | +| `runway.cluster.sessions-map-name` | `runway.sessions` | The name of the distributed map that holds the sessions. Change it only when two separate Runway estates share one external grid (`CLIENT_SERVER`): with the same name they would share sessions. | +| `runway.cluster.events-topic-name` | `runway.events` | The name of the distributed topic that carries "this changed, drop your cached copy" messages between nodes (site, page, content and per-site plugin-setting changes). Same rule as the map name: different estates on one grid need different names. | +| `runway.cluster.embedded.discovery` | `tcp-ip` | How embedded members find each other: `tcp-ip` (the `members` list below; use it in production) or `multicast` (members find each other on the local network; convenient for a test cluster, and `members` is then ignored). Written exactly so, in lower case; any other value stops startup with a message naming it. | +| `runway.cluster.embedded.members` | empty | With `tcp-ip`: the members' addresses as `host:port`, for example `["10.0.0.1:5701", "10.0.0.2:5701"]`. | +| `runway.cluster.embedded.port` | `5701` | The port this node's member listens on for the other members. Open it between the nodes in the host firewall, and nowhere else: it is the cluster's internal traffic, sessions included. | +| `runway.cluster.embedded.port-auto-increment` | `true` | When the port is taken, try the next ones, so several members can run on one host. Turn it off to make a taken port fail instead of moving to a port your firewall does not open. | +| `runway.cluster.client.addresses` | empty | With `client-server`: the grid members to connect to, e.g. `["hz1.internal:5701"]`. **Required**: an empty list stops startup with *"runway.cluster.topology=CLIENT_SERVER requires runway.cluster.client.addresses to be non-empty"*. | +| `runway.cluster.client.smart-routing` | `true` | The client talks to every grid member and sends each operation to the member that owns the data (the fastest). Turn it off only when a firewall lets the client reach just one member: everything then goes through that one. | + +With `client-server`, Runway does not configure the grid's session map for you: declare the map named in +`sessions-map-name` on the grid with `max-idle-seconds` equal to the session TTL. Without it an idle session is +removed only when someone presents its id again, so abandoned sessions stay in the grid's memory. + +Two limits remain, and they shape the topology you can actually run: there is **no read-only edge/replica +mode** yet (every node is a full read-write instance), and the filesystem stores serialize writes **per site +within one JVM only** — two nodes writing the same site's files are last-writer-wins at file granularity (a +distributed lock is the follow-up). Keep authoring traffic on one node until that lands. + +### Capacity, sizing & resilience + +Runway is **CPU-bound**, not memory-bound, for dynamic traffic — so **size the CPU for your peak request rate and +let memory follow the §15 rule.** Reference numbers from a load test on a **2 vCPU** box (Jetty/JDK 25, behind +HAProxy; SSR-heavy mix including a full-JSON-LD page): + +- **~750 req/s sustained** for server-rendered pages, at **~99 % CPU** — the **SSR render is the cost**; the box + saturated CPU well before anything else. **Median latency ~27 ms** when not overloaded. +- **Static / cached content goes far higher** (a CSS/JS asset is cheap) — the dynamic render is what consumes a + core, so read the 750 figure as a *dynamic-page* ceiling, not a total. +- **Memory was comfortable throughout: zero full GCs**, heap peaked ~0.7 GB of a 2 GB `-Xmx`, and the `MemoryMax` + cgroup cap was never approached. Add cores for throughput; give memory the §15 headroom and it is not the limit. +- **Rule of thumb:** throughput scales with cores for SSR traffic — roughly **~350–400 dynamic req/s per core** on + this class of hardware. Extrapolate cautiously (these are 2-core measurements; real pages and CPU differ). + +**Concurrency ceiling — the Jetty thread pool.** In-flight request concurrency is bounded by the embedded Jetty +thread pool (**default max 200**, min 8). On ≤ 2 cores CPU saturates long before 200 threads matter, so the default +is fine; on a **larger multi-core host** the pool becomes the binding ceiling. Raise it on **Settings → Server +settings → Capacity** ("Most request threads", "Fewest request threads"), or with the standard Spring Boot property +in the external `application.yml` (or as a `RUNWAY_OPTS`/JVM arg). Either way it applies after a restart. The +minimum may not be above the maximum (the console refuses it, because the server would not start). The same threads +serve the public sites **and** the consoles, so a maximum set too low leaves the console waiting behind public +traffic under load: + +```yaml +server: + jetty: + threads: + max: 400 # default 200 — raise on a box with many cores serving high SSR concurrency + min: 8 +``` + +**Resilience past capacity.** Beyond its capacity Runway **degrades gracefully — it sheds excess with `503`s, +never crashes, and recovers instantly** when load drops (in the test, CPU fell 99 %→8 % and busy threads 200→3 the +moment the spike ended). Combined with the DoS floor (**§12**), an overload or a flood is shed, not fatal. + +## 3. Installation + +Runway ships as a **single-file, self-extracting installer** — `runway-.bin` — a plain +shell script with a compressed bundle appended after a marker. It needs only stock tools +(`bash`, `tar`, `gzip`, `awk`, `tail`); there is no `makeself` or other dependency. The **same +file installs and upgrades** — re-run it to upgrade in place (**§15**). + +**Download & verify.** Get the installer (and the plain `runway--dist.zip` bundle) from the +releases page, . Every release also ships **stable-named +aliases** and an auto-computed **`SHA256SUMS`** manifest, so these links always fetch the newest build +without looking up a version number: + +``` +https://g.quest.mx/quest/runway/releases/download/latest/runway-latest.bin +https://g.quest.mx/quest/runway/releases/download/latest/runway-latest-dist.zip +https://g.quest.mx/quest/runway/releases/download/latest/SHA256SUMS +``` + +The browser page `…/releases/latest` always opens the newest release. + +> **`latest` serves the newest release.** `…/releases/latest` and every `…/download/latest/…` link serve the +> newest release from the moment it is cut. The release title and its versioned file (`runway-.bin`, beside the +> alias) say which version you got; the CHANGELOG says what each one is. **For production, download an explicit version** from the +> releases page rather than the `latest` link, so a re-run of your install script cannot pick up a newer build +> you have not read the upgrade notes for (§15). + +Verify before running — `SHA256SUMS` lists both +the versioned and the alias names (the aliases are byte-identical copies of that release's artifacts), and the +plugin author's `runway-spi*` files, which an operator does not download (`--ignore-missing` skips them): + +```bash +curl -fL -O \ + https://g.quest.mx/quest/runway/releases/download/latest/runway-latest.bin +curl -fL -O \ + https://g.quest.mx/quest/runway/releases/download/latest/SHA256SUMS +sha256sum -c SHA256SUMS --ignore-missing # must print: runway-latest.bin: OK +sudo ./runway-latest.bin +``` + +> **The `sha256sum -c` step is not optional, and it is the only thing standing between you and a silent +> failure.** Where the releases page requires signing in, a Gitea server given no valid token does not return an +> error — it returns **HTTP 200 with +> `Content-Type: text/html`**, the sign-in page, under the asset's own URL. `curl -f` does **not** catch that +> (`-f` only fails on status ≥ 400), so you end up with a ~12 KB HTML file named `runway-latest.bin`, and any +> check that looks at the exit code or the status code reports success. +> +> The checksum comparison is what fails loudly there, so never skip it — and if you script the download, assert +> **`Content-Type` and size**, not the status code. The same reasoning applies to any automated freshness or +> availability probe against these URLs. + +Before you point an audit, prober or load test at the new install, exempt its address — §12.4, *Exempting +your own high-volume clients*. + +**Install (interactive).** Copy the `.bin` to the target host and run it as root: + +```bash +sudo ./runway-.bin +``` + +On a terminal it walks you through the deployment choices it can't infer — **install location**, +**service user**, the **listen port**, whether to **terminate TLS in Runway itself** (and if so the +PKCS12 keystore + password, and an optional HTTP→HTTPS redirect), and whether to **open the host +firewall** — with any flags you passed pre-filled as the defaults. Anything you supply as a flag is not +re-asked. Watch for the closing lines — it prints the install path, the `systemctl status` / +`journalctl` commands, and the reminder to finish setup in the browser. TLS choices are written to the +external `application.yml` and the first-run web wizard **preserves** them (it merges only its +superadmin pin — see §4). + +**Install (unattended).** Accept all defaults with `-y`, or drive every choice by flag: + +```bash +sudo ./runway-.bin -y # plain HTTP behind a reverse proxy (the default) +sudo ./runway-.bin --port 8080 --open-firewall # set + open the listen port +# terminate TLS locally with an existing PKCS12 keystore (see §7.1 to make one from PEM): +sudo ./runway-.bin -y --tls-keystore /opt/runway-data/external/tls/runway.p12 \ + --tls-password 's3cr3t' --tls-redirect --open-firewall +``` + +**Installer options** (pass any straight through the `.bin`): + +| Flag | Effect | +|---|---| +| `--prefix DIR` | Install root (default `/opt`). | +| `--user NAME` | Service user to create/use (default `runway`). | +| `--port N` | The app's listen port. Written to `application.yml` when non-default (443 with local TLS, else 8080), and opened in the firewall if requested. A port below 1024 also switches on `CAP_NET_BIND_SERVICE` in the unit; later upgrades keep it (§6). **First install only** (see below). | +| `--tls-keystore PATH` | Terminate TLS in Runway itself with this **PKCS12** (`.p12`) keystore — implies local TLS; the file is copied to `external/tls/` and `runway.tls.*` is written (§7.1). **First install only** (see below). | +| `--tls-password PASS` | Keystore password (else prompted; unattended installs must pass it). It is written **in plain text** as `runway.tls.keystore-password` in `external/application.yml`, which is why that file is mode `600` and owned by the service user. Typed on the command line it also lands in your shell history; leave it off on a terminal and answer the prompt instead. | +| `--tls-redirect` | Also add an HTTP→HTTPS 301 redirect + ACME webroot on port 80. Port 80 is privileged, so it also switches on `CAP_NET_BIND_SERVICE` in the unit (kept on upgrade, as with `--port`; see §6), and `--open-firewall` then opens 80 as well. | +| `--no-tls` | Skip the TLS prompt — stay plain HTTP behind a proxy. | +| `--secret-key KEY` | The master key for encrypting stored secrets (SMTP / CAPTCHA / plugin passwords). Persisted as a **root-only systemd drop-in** (`/etc/systemd/system/runway.service.d/30-secret-key.conf`, env var `RUNWAY_SECURITY_SECRET_KEY`). **Leave it off to auto-generate one on first install** (so secret storage never silently fails — even with `-y`). An existing key is **kept** on upgrade (never rotated). Pass an explicit value only to reuse a known key (e.g. migrating a deployment). **Back it up** — losing or changing it makes existing `ENC(...)` values undecryptable. | +| `--java-home DIR` | The JDK/JRE 25+ to run under (else auto-detected). The installer takes the first of these whose `bin/java` reports version 25 or later: this flag, then `$JAVA_HOME`, then `/usr/lib/jvm/` folders matching `*zulu*25*`, `*temurin*25*`, `*-25-*`, `java-25-*`, `jdk-25*`, `jre-25*`. A `--java-home` older than 25 is passed over without an error, so check the `java home` line it prints. With none found it warns and writes `/usr/lib/jvm/java-25-openjdk` into the unit; fix the unit's `JAVA_HOME` then. | +| `--open-firewall` | Best-effort: open the listen port (and 80 with `--tls-redirect`) in **firewalld** or an already-active **ufw** (**§16**). | +| `--firewall-ports LIST` | Comma-separated TCP ports to open (implies `--open-firewall`). | +| `--no-firewall` | Never touch the firewall — **wins over** `--open-firewall` and skips the prompt. | +| `-y`, `--yes`, `--non-interactive` | Non-interactive: accept all defaults. Without it the installer asks only when its input is a terminal, so a run from a pipe, a script or cron is already non-interactive. | +| `--update-essential-plugins` | Accepted and ignored (it logs that it has nothing to do). **Every upgrade** refreshes the bundled essential plugin (`protection`) from the new release; see §15 *Essential plugins on upgrade*. | +| `--heap SIZE` | Set the JVM heap `-Xmx` (e.g. `2g`, `1536m`) via an **upgrade-surviving drop-in** (`runway.service.d/20-heap.conf`) instead of the installer-rewritten main unit. `SIZE` is a whole number with an optional `k`, `m` or `g` (either case); a value with any other character (`2GB`, `1.5g`) is refused before the install starts. The drop-in sets `JAVA_OPTS=-Xms256m -Xmx` and is rewritten whole each time you pass `--heap`. See **Memory tuning** in **§15**. | +| `--memory-max SIZE` | Set a systemd `MemoryMax` cgroup backstop (e.g. `3g`, `1945M`) via drop-in `10-memory.conf`. Keep it ≥ heap + headroom. See **§15**. | +| `--dry-run` | Print every privileged action instead of doing it (change nothing). | +| `-h`, `--help` | Show help. | +| `--extract DIR` | (On the `.bin` itself) unpack the bundle into `DIR` without installing. | + +**Where the `.bin` unpacks.** Before it installs, the `.bin` unpacks itself into a new folder under `$TMPDIR` (or +`/tmp` when `TMPDIR` is unset) and deletes that folder when it ends. On a host whose `/tmp` is small, point it +elsewhere: `sudo env TMPDIR=/var/tmp ./runway-.bin`. Or unpack it yourself with `--extract DIR` and run +`DIR/runway-/scripts/install.sh` with the same options. + +**`--port` and `--tls-keystore` are for the first install only.** They write `external/application.yml` whole, +and on an existing install that file also holds the setup wizard's superadmin pin and anything you added to it; +replacing it would put the platform back into wizard mode with `/setup` open. So when the file already exists the +installer **refuses** them, before changing anything, and names the keys to edit instead — `server.port`, +`runway.tls.*` (§7.1) — then restart. An upgrade needs neither (**§15**); `--port 8080` (the default, never +written) and the firewall flags are still accepted. On an existing install the interactive run does not ask +about TLS or the port either. + +**What it lays down.** The installer is **idempotent** and separates *code* from *state* so an +upgrade never clobbers your configuration or data (see **§5** for the layout, **§15** for +upgrades). With the defaults it: + +1. Creates the **service user** `runway` (a system account, `nologin` shell). +2. Creates the version-independent **data dir** `/opt/runway-data/` with `external/`, `logs/`, + and `backups/`. +3. Unpacks the release to a **versioned dir** `/opt/runway-/` — `bin/` (the jar and the + launcher), `scripts/` (the installer), and `seed/plugins/` (the bundled protection plugin as it ships, the copy + you repair from — **§12**) — and symlinks `external/`, `logs/`, `backups/` from there into the data dir. +4. Flips the **`/opt/runway` "current" symlink** to the new release (this path is `RUNWAY_HOME`). +5. Sets ownership to the service user and, on SELinux-enforcing hosts, **relabels contexts** + (`restorecon`) — this is required, not optional (**§16**). +6. Installs/updates the **systemd unit** `/etc/systemd/system/runway.service` with the detected + `JAVA_HOME`, enables it, and **starts the service**. + +**Verify the install.** After it finishes: + +```bash +systemctl status runway # should be "active (running)" +journalctl -u runway -e # startup log — look for the listen port and "WIZARD" mode +ls -l /opt/runway # -> runway- (the current symlink) +ls /opt/runway-data # external logs backups +``` + +Then open the server in a browser and complete the first-run setup (**§4**) — a fresh install +boots in **WIZARD** mode and every request funnels to the setup page. + +## 4. First-run setup + +A brand-new install has no accounts and no sites, so Runway boots in **WIZARD mode** and serves a +single open setup page — every other path is funneled to it. The mode is **derived**, not a knob: +the platform is in WIZARD mode precisely while the application-superadmin **pin** +(`runway.security.app-master-id`) is unset in `external/application.yml`. Once the wizard writes +it, the next launch comes up in **ACTIVE mode** and the whole wizard layer is gone. Config can +never contradict reality because there is no separate `mode` setting to drift. + +Writing the pin is a **merge, not a rewrite**: any settings already in `external/application.yml` — +self-managed TLS (§7.1), proxy CIDRs, a custom `server.port`, whatever the installer or you put there — +are **preserved** through first-run setup (the wizard only sets the pin). If that file exists but is not +valid YAML, setup stops with a clear message rather than overwriting it, so a hand-edit is never lost. + +**Security note.** Because there are no accounts yet, the setup page is **unauthenticated**. Reach +it only over localhost or from behind your reverse proxy until setup completes — do not expose +`/setup` to the internet. + +**Run the wizard.** Open the server (e.g. `http://:8080/setup`, or just any URL — it +redirects to setup). You provision **two administrators, one per realm** in a single step: + +- **Application superadmin** — runs the *platform* (sites, plugins, application users). You give a + username, an optional display name and recovery email, and a password (min 8 chars). There is + exactly one, and it is **pinned** — it can never be deleted, disabled, demoted, or renamed from + within the realm (**§9**). +- **Default site administrator** — the **superadmin of the first site** the wizard seeds. This is a + separate **tenant-realm** identity (username, password and an optional recovery email); the two realms + never cross, so this is a distinct account from the application superadmin. Give it the recovery email + here, or later on **Site masters** (**§10**), so it can use *Forgot your password?*. + +Submit **"Create administrators & restart"**. The wizard: + +1. Seeds a first site from the **starter template** and marks it the **default (catch-all)** site + (**§10**) — so the deployment answers any hostname out of the box. The starter is a real, styled + **two-page site** (a home page and an about page) sharing one master template, not a blank placeholder: + it is meant to be edited, not replaced. There is no other choice to make here. +2. Provisions that site's superadmin (the tenant admin you entered). If this step fails, it rolls + back to a clean slate so you can simply retry. +3. Creates the pinned application superadmin, writes `external/application.yml` with the pin + (mode `600` — it holds a secret), and triggers a supervised relaunch. + +**Confirm it worked.** The success page says setup is complete and the server is restarting. Under +systemd the JVM exits with the relaunch code and systemd restarts it into ACTIVE mode (**§6**). +Within a few seconds: + +```bash +journalctl -u runway -f # you should see a fresh startup, now WITHOUT WIZARD mode +ls -l /opt/runway-data/external/application.yml # exists, mode -rw------- (600) +``` + +Then sign in to the **operator console** at `/app/login` with the application-superadmin +credentials — you land on the console home at `/__app`. The site administrator signs in +separately at the site's `/login`. Use the server's address, or a host name of the first site (it is the +default site): once you give other sites their own host names, the console does not answer on those (**§8.6**). + +## 5. Deployment layout + +Runway keeps all editable state in an **external folder** (no database). The kernel resolves +these paths from `runway.storage.*`; only `external` is normally set, the rest default relative +to it: + +| Key | Default | Holds | +|---|---|---| +| `runway.storage.external` | `./external` | The operator-editable root: `application.yml`, shared templates/static/i18n, app-level stores, `sites/` | +| `runway.storage.sites` | `/sites` | One self-contained folder per site (its data, presentation, users, config) | +| `runway.storage.backups` | `./backups` | Per-site backup archives | +| `runway.plugins.root` | `/plugins` | Installed plugins, one folder each (**§11**). Normally left unset; when set, both the loader and the console's install/uninstall/enable/disable use it | + +`runway.storage.stats` and `runway.storage.logs` are not settings (bandwidth is metered per site, in +`sites//stats/`; the launcher's `runway.out` lives in the deployment's `logs/`, outside Runway's control). +A configuration that sets either starts normally and logs one `WARN` naming the key — delete the line. + +**The layout marker.** On its first start with a data folder, Runway writes `external/layout.yml` +(`version: 1`). It records which version of this folder's layout the data is in, and it is checked before +anything else touches the folder: a release older than the layout refuses to start rather than write into it +(see **§15**, *Rolling back*). Do not edit or delete it. + +**Every file, and who owns it.** The full `external/` and `sites//` inventory — each file, the class +that reads and writes it, and what an upgrade may change about it — is in +[CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md) §2. + +## 6. Running the service + +The installer registers Runway as a **systemd service**, which is the normal way to run it. The +service is driven by the launcher script `bin/runway.sh`, which you can also run by hand. + +**Under systemd (recommended):** + +```bash +sudo systemctl start runway # start +sudo systemctl stop runway # stop +sudo systemctl restart runway # restart +sudo systemctl status runway # is it running? +sudo journalctl -u runway -f # follow the log +``` + +The unit uses `Type=simple` and runs the launcher in **foreground** mode +(`ExecStart=/opt/runway/bin/runway.sh -f`) so systemd gets the real JVM PID and `SIGTERM` reaches +Java directly. Two exit codes matter and are handled by the unit: + +- **42** is Runway's *supervised-relaunch* request (used by the first-run wizard and by plugin + install/enable/disable). `RestartForceExitStatus=42` makes systemd restart even though 42 is a + clean exit, and `SuccessExitStatus=143 42` keeps both a normal `SIGTERM` shutdown (143) and the + relaunch (42) from being logged as failures. This is why installing a plugin (**§11**) simply + needs a restart action, not a manual `systemctl` dance. + +The unit also sandboxes the process (`NoNewPrivileges`, `ProtectHome`, `ProtectSystem=strict`, +`PrivateTmp`) and grants write access only to the data dir: the installer writes +`ReadWritePaths=/opt/runway-data` (the template in `scripts/runway.service` names the three data folders under +`/opt/runway`; the installer replaces that line). Anything Runway must write — a log file you configure (Operations +§3), an off-host backup folder (§13) — therefore has to be under `/opt/runway-data`, or added to `ReadWritePaths` in a +drop-in. + +**The installer rewrites the main unit on every run.** Put lasting changes in drop-ins under +`/etc/systemd/system/runway.service.d/`. The installer leaves your own files there alone; it writes only its own +`10-memory.conf` and `20-heap.conf` (when you pass `--memory-max` or `--heap`) and `30-secret-key.conf` (on the first +install). **Binding a privileged port** (80/443 without a proxy) needs `CAP_NET_BIND_SERVICE`. The installer switches +it on in the main unit when you install with `--port` below 1024 or `--tls-redirect`, and an upgrade keeps it when the +unit it replaces had it switched on. It cannot read your port from `application.yml`, though: if you move to a +privileged port later by editing that file, give the service the capability yourself, in a drop-in: + +```bash +sudo mkdir -p /etc/systemd/system/runway.service.d +printf '[Service]\nAmbientCapabilities=CAP_NET_BIND_SERVICE\nCapabilityBoundingSet=CAP_NET_BIND_SERVICE\n' \ + | sudo tee /etc/systemd/system/runway.service.d/40-net-bind.conf +sudo systemctl daemon-reload && sudo systemctl restart runway +``` + +**The launcher directly** (e.g. on a host without systemd, or for a quick manual run). It resolves +`RUNWAY_HOME`, the executable jar, and `JAVA_HOME`, then: + +```bash +bin/runway.sh # detached: a supervisor backgrounds the JVM, writes runway.pid, + # logs to logs/runway.out, and relaunches on exit 42 +bin/runway.sh -f # foreground: exec the JVM (what systemd uses); also --foreground +bin/runway.sh stop # stop the supervisor (which SIGTERMs the JVM); also --stop +bin/runway.sh -h # the launcher's help; also --help +``` + +Detached mode refuses to start a second instance while one is running. It keeps two PID files in `RUNWAY_HOME`: +`runway.pid` (the supervisor) and `runway.jvm.pid` (the JVM it is running now); `stop` uses both and removes them. +Any other argument is passed to Spring as it is, and everything after `--` is passed even if it looks like a launcher +option: `bin/runway.sh -f --server.port=9090`. + +Environment overrides (honored by both the launcher and the unit's `Environment=`): `RUNWAY_HOME`, +`RUNWAY_JAR`, `RUNWAY_OPTS` (extra Spring args, e.g. `--server.port=`), `JAVA_HOME`, `JAVA_OPTS` (heap/GC — +default `-Xms256m -Xmx1g`). The launcher always adds `--enable-native-access=ALL-UNNAMED` after your `JAVA_OPTS`: +the Brotli compression library and Hazelcast (clustering) use native code, which Java 25 restricts without it. Do not +remove it from a hand-written start command. + +**Verify:** `systemctl status runway` shows `active (running)`; `journalctl -u runway -e` shows the +banner with the bound port; hitting the site in a browser returns a page (the default site, if no +host is bound). + +## 7. TLS & reverse-proxy setup + +**Trusting forwarded headers (implemented).** Runway honors `X-Forwarded-*`/`Forwarded` headers (client IP, +host, scheme) **only** from proxy peers you list in `runway.proxy.trusted-cidrs`; from any other peer the +headers are ignored and the raw connection is used, so a directly-reachable instance cannot spoof them. The +container's own forwarded-header handling is off (`server.forward-headers-strategy: none`) — Runway's gated +filter is the sole handler. Defaults: forwarding is on (`runway.proxy.forwarded-headers: true`) and the +shipped config trusts loopback only (`127.0.0.1/32`, `::1/128`) for a same-host proxy. **Behind an off-host +proxy, add its exact IP** (prefer a single address over a broad range); an **empty** `trusted-cidrs` trusts +nothing (every request attributed to its direct peer, logged at startup). A catch-all (`0.0.0.0/0`, `::/0`, +or ranges that add up to one, such as `0.0.0.0/1` with `128.0.0.0/1`) trusts every client to fake its address: +Server settings refuses it, and one set in `application.yml` is warned about at startup. Never put a tenant-editable value here — it is an isolation/abuse boundary. + +**The host name behind a proxy.** Runway decides which site a request is for, and whether the operator console +answers (**§8.6**), from the host name it sees: the request's own `Host`, or the forwarded host from a trusted proxy. +So the proxy must pass the visitor's host name on (`proxy_set_header Host $host;` in nginx, the default in HAProxy +and Caddy). To give the console a host name of its own, point that name at Runway like any other and list it in +`runway.console.hosts`. + +### 7.1 Self-managed TLS (optional) + +By default Runway serves **plain HTTP behind a TLS-terminating reverse proxy** — that stays the +recommended topology. When no proxy is wanted, Runway can **terminate TLS itself**: put the certificate + +key in a **PKCS12 keystore** and enable it in the external `application.yml`: + +```yaml +runway: + tls: + enabled: true + keystore: /opt/runway-data/external/tls/runway.p12 + keystore-password: "…" # a secret — this file is chmod 600 + key-alias: runway # the keystore entry holding the server key +``` + +Set TLS **only** through `runway.tls.*`. Spring Boot's own `server.ssl.*` keys are filled from them by the shipped +`application.yml`; setting `server.ssl.*` yourself would bypass Runway's startup checks (keystore readable, password +set, alias present, each failing with a message that says what to fix), and the startup log line would still say +that TLS does not terminate here. + +**Convert a PEM certificate to the PKCS12 keystore.** ACME clients (certbot, acme.sh) and most CAs issue +**PEM** files — a certificate (usually with its intermediate chain) plus a private key — while Runway wants a +**PKCS12** keystore. Convert them with `openssl`. For the typical Let's Encrypt layout under +`/etc/letsencrypt/live//`, where `fullchain.pem` is the leaf certificate **plus** the intermediate +chain and `privkey.pem` is the private key: + +```bash +openssl pkcs12 -export \ + -inkey privkey.pem \ + -in fullchain.pem \ + -name runway \ + -out runway.p12 \ + -passout pass:'CHANGE-ME' +``` + +- **`-name runway`** is the keystore **alias** — it MUST equal `runway.tls.key-alias` (default `runway`), or + startup fails to find the key. +- **`-passout pass:'CHANGE-ME'`** sets the keystore **password** — it MUST equal + `runway.tls.keystore-password` in the external `application.yml`. +- **`-in fullchain.pem`** must be the leaf certificate **followed by** its intermediate chain (that is exactly + Let's Encrypt's `fullchain.pem`). If your cert and chain are in **separate** files, use + `-in cert.pem -certfile chain.pem` instead. +- Add **`-passin pass:''`** if the private key is itself password-protected. +- The output is already PKCS12 — `runway.tls.keystore-type: PKCS12` is the default, so no extra flag is needed. + `keystore-type` takes any keystore type the Java runtime knows (for example `JKS` for an older Java keystore); a + type it does not know, like a file that is not of the stated type, stops startup with a message naming the + keystore and the type. + +Then lock it down (it holds the private key) and place it where `runway.tls.keystore` points: + +```bash +install -o runway -g runway -m 600 runway.p12 /opt/runway-data/external/tls/runway.p12 +``` + +**Verify** it before enabling TLS — both the alias and the password must match your config: + +```bash +# lists the entries; must show one `runway` alias (prompts for the keystore password): +keytool -list -keystore runway.p12 -storetype PKCS12 +# or inspect the certificate's subject / issuer / validity dates directly: +openssl pkcs12 -in runway.p12 -nodes -passin pass:'CHANGE-ME' | openssl x509 -noout -subject -issuer -dates +``` + +> **On renewal, just re-run the `openssl pkcs12 -export` above** (same `-out`, `-name` and password). With +> `watch-keystore` on (the default), Runway reloads the new certificate **live** — no restart. Wire that +> one-liner into your ACME client's `--deploy-hook` / renew hook. + +Startup **fails fast** — with a precise message — if TLS is enabled with a missing/unreadable keystore or a +blank password, and one log line always states where TLS terminates (`TLS terminates HERE: HTTPS on port …` +vs `TLS does NOT terminate here: plain HTTP …`), so the topology is never ambiguous. + +**Hot certificate reload (no restart).** With `watch-keystore: true` (the default when TLS is on), Runway +watches the keystore file and **reloads the certificate live when it changes** — so a renewal that rewrites +the keystore is picked up without a restart (only new TLS connections use the new cert; existing ones drain +naturally). Point your ACME client's deploy/renew hook at rewriting the PKCS12 keystore and you are done; a +half-written or invalid keystore is logged and the **previous** certificate keeps serving (degrade, don't +crash). Set `watch-keystore: false` to opt out and reload by restart instead. + +**HTTP→HTTPS redirect + Let's Encrypt.** With TLS on, an optional **plain-HTTP listener** (default port 80) +301-redirects every request to the HTTPS listener — **except** `/.well-known/acme-challenge/`, which is +served as plain files from `acme-challenges-dir`, so **ACME HTTP-01** issuance/renewal keeps working with +the redirect on (point `certbot`/`acme.sh` `--webroot` at that directory, then convert the issued PEMs into +the PKCS12 keystore as shown above — the hot reload picks up the new certificate, no restart needed): + +```yaml +runway: + tls: + redirect-http: + enabled: true + port: 80 # binding <1024 needs CAP_NET_BIND_SERVICE — see §6 / §16 + acme-challenges-dir: /opt/runway-data/external/acme-challenges +``` + +The redirect answers at the **connector level** — nothing on the plain port ever reaches the application — +with hardened handling (ACME tokens are shape-checked and confined to the webroot; symlinks and over-sized +files are refused; malformed `Host`/path values are rejected `400`). `status` is the redirect's HTTP status: +`301` (the default, permanent), `308` (permanent, and the client keeps the request method), `302` or `307` +(temporary). Any other value stops startup with a message naming it. + +> **The webroot's permissions are yours to guard:** everything in `acme-challenges-dir` is served to +> anyone on the plain port. Only the ACME client should be able to write there — never the application or +> an untrusted user (e.g. `chown` it to the user running certbot and keep it `700`/`750`). + +**Privileged ports & firewall.** Binding 443 and/or 80 directly needs `CAP_NET_BIND_SERVICE`. An install with +`--tls-keystore` on 443 or with `--tls-redirect` already has it, and upgrades keep it. If you switched to these ports +afterwards by editing `application.yml`, give it with the drop-in shown in **§6**. Open both ports in the host firewall (e.g. re-run the installer with +`--firewall-ports 80,443 --open-firewall`, or your firewall tooling directly). + +> **Verify:** `curl -sI https:/// | head -1` answers over TLS; `curl -sI http:///x` returns +> `301` with a `Location: https://…`; and with a file `t` in the webroot, +> `curl -s http:///.well-known/acme-challenge/t` returns its content instead of a redirect. + +Set `runway.tls.sni-host-check: false` only for a **re-encrypting proxy** that connects by the backend's IP +while forwarding the real Host (Jetty's SNI/Host consistency check would otherwise reject those requests); +leave it on everywhere else. + +## 8. Configuration reference + +Runway is configured through **`application.yml`**, following the house convention: a reference +copy of every default ships inside the jar (on the classpath), and your **external override** at +`external/application.yml` (i.e. `/opt/runway-data/external/application.yml`) is loaded **above** it +and wins key-by-key. Only set in the external file the keys you actually change. The first-run +wizard creates this file and writes the application-superadmin pin into it; add your own keys +alongside. Because it holds a secret (the pin, and any `runway.security.secret-key`), keep it mode +`600`, owned by the service user (**§16**). + +Changes take effect on the **next restart** (`systemctl restart runway`), except where noted. +Runtime-editable resources — messages/i18n, templates, static assets — live under `external/` and +reload without a restart. + +**Most settings are set in the console, not here.** Every setting that can be changed safely +while the server runs has a page in the application console: **Settings → Server settings** +(`/__app/config/server`), and the **Settings** button on Backups, Bandwidth, Activity → Logs and Plugins +(§8.5). Those pages save to `settings:` in `external/platform.yml`. What stays in `external/application.yml` +is what the server needs before it can start or what is only safe to change on the host: the port, TLS, the +secret key, the storage paths, clustering, the audit switch `runway.app-activity.enabled`, and the console's host +names `runway.console.hosts` (a wrong value would lock you out of the console, so the file is where you fix it, +**§8.6**). [SETTINGS-REFERENCE.md](SETTINGS-REFERENCE.md) lists every host-only key with its reason. + +**One home per setting; the host wins.** The console's values are loaded *below* `external/application.yml`, +environment variables and command-line arguments. A key you set there by hand wins, and the console shows +that field disabled with the note *"Set on the server in external/application.yml, which wins over this +page."*, followed by what removing the line would do: the console holds the same value, or the value is the +default (removing it changes nothing); the console holds a different value (that one takes effect); or the console +holds none and the default takes effect. A list counts in either form: a comma string +(`trusted-cidrs: "10.0.0.5/32,::1/128"`) or a YAML list (`trusted-cidrs: [10.0.0.5/32, ::1/128]`). + +**Moving a key from `application.yml` to the console: one restart, with "Use the file's value".** While a key's +line is in the file, its field is locked, so the console cannot be given a value first. Moving it the plain way — +delete the line, restart, set the value on the page, restart again — costs **two restarts, and between them the +server runs on the default**. For a key whose default differs from your value (your proxy's address in trusted +proxy addresses, a monitoring token, the CSP mode) that is a window with the wrong value. A +locked row whose removal would change something offers **Use the file's value** (**Use the server's value** when an +environment variable or a command-line argument sets it). It copies the value the server runs with now into the +console's store. Then: + +1. On the locked row, click **Use the file's value** and confirm. The field stays locked (the file still wins), and + the row now says *"The console holds the same value, so removing it there changes nothing."* +2. Delete the key's line from `external/application.yml`. +3. Restart once (`sudo systemctl restart runway`). Nothing changes: the console's copy is what the server reads now. + +The value goes through the same checks as a save, and nothing is stored when one fails: a value the console +refuses (a catch-all trusted proxy, a value containing `${`, a number outside the console's range) stays on the host +until you correct it there. A token needs `runway.security.secret-key`: it is stored encrypted, like a token typed +on the page, and never shown. A token the host sets to `""` removes the console's stored token, since no token is +what runs. A blank value the console cannot hold is refused, because a blank field on the console means the default +(an empty `runway.compression.mime-types`, say, which compresses nothing): keep that one on the host. The copy is +recorded in the activity log, with the key and never the value. Values copied this way are listed with the +other changes saved since the start, but they change nothing until the line is removed and the server restarts. + +Two keys do not follow this rule. **Password strength** (`runway.security.password-strength`): the value chosen +on Settings → Platform settings wins over `application.yml`, environment variables and command-line arguments, +and that field is never locked (§8.1). **The protection plugin's settings**: what its settings screen saves in +`external/plugin-settings/protection.yml` wins over `external/application.yml`, and the form shows no lock; an +environment variable or a command-line argument still wins over both. + +**Keys.** The tables below list the most-used keys; anything not listed is left at its default. The +complete `runway.*` inventory, with types and defaults, is in +[CONFIGURATION-AND-DATA-STABILITY.md](CONFIGURATION-AND-DATA-STABILITY.md) §1, and your IDE completes every key +from the configuration metadata shipped in the jar. + +**`runway.*` — the platform's own keys:** + +| Key | Default | Meaning | +|---|---|---| +| `runway.storage.external` | `./external` | Root of the operator-editable folder (see **§5**). | +| `runway.storage.sites` | `/sites` | Where per-site folders live. | +| `runway.storage.backups` | `./backups` (deployment root) | Where per-site backup archives are written (**§13**). | +| `runway.plugins.root` | `/plugins` | Where plugins are installed and discovered (read from the environment before startup). The console's install/uninstall/enable/disable work in the same folder. | +| `runway.operator.ui-languages` | `[en, es]` | Languages the operator console's topbar switcher offers (BCP-47 codes, in display order). English and Spanish ship; any other language needs your own translation in `external/i18n/` (*Translating the console*, below). | +| `runway.operator.default-language` | `en` | Fallback console language when the browser requests none offered. | +| `runway.console.hosts` | _(empty)_ | The host names the operator console answers on (case and port ignored); every other host gets a `404` for the console's paths. Empty: the default site's host names and host names that serve no site. Host only, applies after a restart. **§8.6**. | +| `runway.compression.enabled` | `true` | Master switch for the single Brotli+gzip response-compression filter. Set `false` when a fronting proxy already compresses. Jetty's own gzip (`server.compression`) stays off either way. | +| `runway.compression.max-buffer-bytes` | `4194304` (4 MiB) | Largest response buffered to compress; anything larger streams through uncompressed. The buffer is held in memory **per response being sent**, so the worst case is this size times the busy request threads. `0` or a negative value (possible only in `application.yml`; the console takes 64 KiB to 256 MiB) sends every response uncompressed. | +| `runway.compression.mime-types` | `text/html`, `text/xml`, `text/plain`, `text/css`, `text/javascript`, `application/javascript`, `application/json`, `application/xml`, `image/svg+xml` | The content types that are compressed, matched on the type without its `charset`. **A list you set replaces this one**, so repeat the defaults you want to keep. An empty list in `application.yml` compresses nothing; a blank field on the console restores this default. Leave out formats that are already compressed (images, fonts, zip). | +| `runway.compression.gzip.enabled` / `.min-size` | `true` / `1024` | Offer gzip; skip bodies below the minimum. | +| `runway.compression.brotli.enabled` / `.quality` / `.min-size` | `true` / `5` / `1024` | Offer Brotli (needs the brotli4j native lib; falls back to gzip if absent). Quality `0..11`: lower is faster and compresses less, higher is smaller and costs more CPU on every response; 4 to 6 suit compressing as pages are sent. In `application.yml`, a value above 11 or below -1 stops startup (the library refuses it; -1 asks for the library's own default). | +| `runway.security.app-master-id` | _(blank)_ | The pinned application-superadmin principal id. **Written by the wizard** — its presence flips WIZARD → ACTIVE. Do not edit by hand. | +| `runway.security.password-strength` | `STANDARD` | Argon2id memory-cost profile for **new** passwords: `STANDARD` (19 MiB) or `HIGH` (32 MiB). The Settings screen can override this (**§8.1**). | +| `runway.security.max-concurrent-hashes` | `8` | Most password hashes computed at once before requests fail "busy" — bounds heap under a login flood. Read once at startup (Settings → Server settings → Capacity, or here); at least `1` — `0` or a negative value stops startup. | +| `runway.security.acquire-timeout-millis` | `2000` | How long a request waits for a hashing slot before failing "busy". | +| `runway.security.secret-key` | _(installer-set)_ | Master key for AES-256-GCM encryption of every stored secret (platform SMTP password, per-site CAPTCHA secrets, `secret`-typed plugin settings). The installer generates one on first install and stores it in a root-only systemd drop-in as `RUNWAY_SECURITY_SECRET_KEY` (see `--secret-key`, §3); Spring's relaxed binding maps that env var to this property. **While blank the secret cipher is unavailable and no secret can be saved** — the app console shows a persistent warning on every page until it is set. Holds a real secret — never in the classpath default. | +| `runway.proxy.forwarded-headers` | `true` | Whether to honor `X-Forwarded-*` / `Forwarded` at all (still only from trusted peers) — see **§7**. | +| `runway.proxy.trusted-cidrs` | `127.0.0.1/32`, `::1/128` | Proxy peers whose forwarded headers are trusted. The **bound default is empty** (trust nothing); the shipped file seeds loopback. **§7**. | +| `runway.i18n.cache-seconds` | `5` | How often a message lookup **outside** a public page (an error page, a plugin's background text) and the operator console's own bundle re-check their files on disk (`0` = on every lookup). Public pages re-check on every request, so a bundle edited on disk shows on the next page view, under a new ETag. | +| `runway.csp.mode` | `report` | Content-Security-Policy delivery: `report` (report-only — violations are logged, nothing is blocked), `enforce`, or `off`. Upper or lower case; blank means `report`. Any other value (`enforced`, say) stops startup with a message naming it. See **§8.4**. | +| `runway.csp.strict-dynamic` | `true` | `'strict-dynamic'` on the nonced pages. `false` rolls the whole estate (console **and** public pages) back to the host allowlist. **§8.4**. | +| `runway.csp.public-strict-dynamic` | `true` | Public tenant pages get a nonce derived from the page version + `'strict-dynamic'`, stamped at the edge on the scripts the allowlist policy would have run (same-origin or allowlisted `src`; never inline). `false` keeps public pages on the host allowlist. Needs `strict-dynamic: true`. **§8.4**. | +| `runway.csp.extra-hosts` | `[]` | Extra hosts an operator allowlists for the fetch directives and `frame-src` (a CDN, an analytics host), on **every site's** pages (the console calls it *Extra allowed hosts (all sites)*). A host only one site needs belongs on **Settings → Embed hosts**. **§8.4**. | +| `runway.http-cache.public-pages` | `public, max-age=300, stale-while-revalidate=60` | The `Cache-Control` header of a public page: browsers and shared caches may keep it 5 minutes, then serve it one more minute while they check for a newer version. A page also carries an ETag that changes with its content, so a cache that asks again gets the new page at once. (A page whose content widget reads the request's query, such as a search results page asked with a query, is sent `private, no-cache` and no ETag instead.) `no-cache` makes every visit ask. A page's own **Cache-Control** field in the page editor wins over this value. Blank means this default. | +| `runway.http-cache.assets` | `public, max-age=86400` | The header of a site's files under `/static/` (one day), and always of its documents under `/static/doc/`, which can be replaced in place. Blank means this default. | +| `runway.http-cache.plugin-assets` | `public, max-age=3600` | The header of the files plugins serve under `/__plugin//static/` (their styles and scripts): browsers keep them an hour, then ask again and get a `304` while the file is unchanged (each file carries an ETag of its content). An hour rather than a day because a plugin file keeps its name across upgrades. Accepts `public`, `private`, `max-age`, `s-maxage`, `stale-while-revalidate`, `stale-if-error`, `must-revalidate`, `proxy-revalidate`, `no-transform`, `immutable`, and `no-cache` or `no-store` alone; another value logs a warning and uses the default. Blank means this default. | +| `runway.http-cache.immutable-extensions` | `woff2, woff, ttf, otf, eot` | Files under `/static/` with these extensions (any case, with or without the dot) get the immutable header below instead. Add `css` or `js` only if the site's file names change with their content (`app.3f9c2.js`): a browser never asks again for an immutable file, so an edited `site.css` under the same name would stay old for a year. An empty list makes no file immutable. | +| `runway.http-cache.immutable-assets` | `public, max-age=31536000, immutable` | The header for those files: kept a year and never re-checked, not even on reload. Blank means this default. | + +**`server.*` / `spring.*` — framework keys Runway pins (change with care):** + +| Key | Shipped value | Why | +|---|---|---| +| `server.port` | `8080` (Boot default; unset) | The HTTP listen port. Override with `RUNWAY_OPTS=--server.port=N`. | +| `server.forward-headers-strategy` | `none` | The container's own forwarded-header handling is **off** — Runway's gated filter is the sole handler, so a direct client cannot spoof `X-Forwarded-*` (**§7**). Do not turn this on. | +| `server.error.whitelabel.enabled` | `false` | Runway serves its own error pages; the Spring whitelabel page is disabled. | +| `spring.config.import` | `optional:file:external/application.yml` | Loads your external override above the classpath defaults. | +| `spring.web.resources.add-mappings` | `false` | The page controller owns the catch-all `/**`; Boot's default static `/**` mapping is off so it can never shadow a page. | +| `spring.servlet.multipart.max-file-size` / `max-request-size` | `256MB` | The largest upload the platform accepts is a site backup zip (restore-from-upload); the 1 MB Boot default would reject any real backup. | +| `spring.security.filter.order` | `100` | Runs Spring Security's chain **after** the multi-tenancy filters, so a chain can read the bound site — required for tenant isolation. Do not lower it. | +| `spring.task.scheduling.pool.size` | `4` | Threads in the **one** scheduler pool every periodic task runs on: automatic backups (when enabled, §13) and plugins' scheduled work. Scheduling is always on. Four, so a long nightly backup cannot hold up short plugin jobs; threads start only as tasks are scheduled, so an idle pool costs nothing. Raise it only if a thread dump shows every `runway-scheduler-*` thread busy. | +| `spring.task.scheduling.thread-name-prefix` | `runway-scheduler-` | Names those threads, so they are recognisable in a thread dump (`jcmd Thread.print`). | +| `spring.thymeleaf.servlet.produce-partial-output-while-processing` | `false` | A page is rendered whole before its first byte is sent. Streamed instead (Boot's default), an error halfway through a render would leave the visitor a blank or cut-off page instead of the error page. Do not turn it on. | +| `server.servlet.session.timeout` | `30m` | How long a signed-in session (the operator console and every site console) may sit idle before it signs out. A duration such as `30m`, `2h` or `1d`; a bare number means seconds. Set on **Settings → Server settings → Sessions**; applies after a restart. With clustering on, `runway.cluster.session-ttl` decides instead — keep the two equal (§2). | +| `server.jetty.threads.max` / `.min` | `200` / `8` | The request thread pool (§2, *Capacity*). Set on **Settings → Server settings → Capacity**; applies after a restart; the minimum may not exceed the maximum. | +| `server.ssl.*` | from `runway.tls.*` | Filled from `runway.tls.*` (§7.1). Never set these yourself: they would bypass Runway's TLS startup checks. | +| `management.endpoints.web.exposure.include` | `health, prometheus` | The only actuator endpoints served. Do not add others: everything under `/actuator/` is open to the superadmin and System admins without the console's CSRF protection, and an endpoint such as `heapdump` would hand out what the server holds in memory, secrets included. | +| `management.endpoint.health.probes.enabled` | `true` | Adds `/actuator/health/liveness` and `/actuator/health/readiness` for a supervisor or load balancer. | +| `management.endpoint.health.show-details` | `when-authorized` | The public health answer is only `UP`/`DOWN`; a signed-in operator also sees each check (e.g. the data folder's path). | +| `logging.level.` | Boot's (`INFO`) | Raise one logger for diagnosis, e.g. `logging.level.mx.quest.runway.head: DEBUG`. Runway's own loggers are `runway.access` (one line per public request), `runway.protect` (edge rejections) and the `mx.quest.runway.*` packages. Set here, it applies after a restart (or set it for one run with `RUNWAY_OPTS=--logging.level.mx.quest.runway=DEBUG`). Easier: **Activity → Logs → Log levels** (`/__app/logs/levels`) changes a level at once and keeps it across restarts (in `platform.yml`); a level set here wins and shows locked there. **Default** on that screen puts a logger back to the level set here, or else its parent's; `ROOT` goes back to `logging.level.root`, or else `INFO`. Turn it back down afterwards: `DEBUG` on a busy server writes a lot. | +| `logging.file.name` / `logging.file.path` | _(unset)_ | Unset, everything goes to the console stream (journald under systemd). Setting either also writes a log file, rotated by Spring Boot; see Operations §3. | + +Plugin settings are **not** placed in `application.yml`: app-level plugin settings live in their own +file per plugin under `external/plugin-settings/.yml` and are edited from the console (**§11**). + +**Translating the console.** The console's text ships in the jar as `i18n/operator-messages.properties` (English, +also the fallback for any language without its own file) and `operator-messages_es.properties` (Spanish). To +correct a wording or add a language, put a file of the same name in `external/i18n/`: for example +`external/i18n/operator-messages_fr.properties` for French. It needs only the keys you change; any key it lacks +comes from the shipped files. Copy the keys from the shipped file (`unzip -p +'BOOT-INF/classes/i18n/operator-messages.properties'`) and write the file in **UTF-8**. A new language also needs +its code added to `runway.operator.ui-languages` (Settings → Server settings → Console languages; applies after a +restart) and a name for the switcher, the key `op.lang.` (`op.lang.fr=Français`); without it the switcher +shows the key itself. Edits to these files are picked up while the server runs, within +`runway.i18n.cache-seconds` (5 seconds by default). Mind one trap: a key in the unsuffixed +`external/i18n/operator-messages.properties` wins over the **shipped Spanish** text too, because your folder is read +before the shipped files; put a Spanish correction in `operator-messages_es.properties`. + +The console's **Settings** menu is a dropdown with two entries: **Platform settings** (§8.1, the +editable settings below) and **About Runway** (§8.2, a read-only view of the running platform). + +### 8.1 Platform settings + +A small set of platform-wide settings is edited from the operator console at **Settings → Platform +settings** (`/__app/settings`, restricted to the application superadmin or a wildcard admin) and +stored in `external/platform.yml` — application-realm state kept **outside every tenant folder**, so +it never travels in a per-site backup: + +- **Default site** — the catch-all that answers requests whose `Host` isn't bound to any other site + (see **§10**). Changing it takes effect immediately. +- **Password strength** — the Argon2id memory-cost profile (`STANDARD` = 19 MiB, `HIGH` = 32 MiB) used + for **new** passwords. It overrides the `runway.security.password-strength` value from + `application.yml` and applies on the next restart; existing passwords are unaffected (Argon2id hashes + are self-describing, so verification never breaks when the profile changes). +- **Node name** and **Response compression** — a display name for this node (shown on About) and the + master + per-encoding (Brotli / gzip) compression switches. Both apply immediately. The name shown is this field + when it is set, else `runway.node.name` from the server's configuration, else the server's host name. So in a + cluster, leave the field blank and give each node its own `runway.node.name` (an environment variable such as + `RUNWAY_NODE_NAME=web-1` suits that); a value saved in the field wins over it. The name is only displayed; nothing + else uses it. +- **Platform mail (SMTP)** — the application's own mail account: host, port, From address, and optional + authentication (username + password) with STARTTLS or implicit TLS. With STARTTLS chosen, a relay that does + not offer it fails the send rather than receiving the password in the clear, and with either TLS mode the + relay's certificate must name its host. A relay that does not accept the connection within 10 seconds, or + stalls for 30 seconds while sending, fails the send. It is used to send + **password-recovery** links and any future operator notifications, for **both** the application and + site consoles — and is **never** used for mail a site sends itself (a site keeps its own SMTP + relay). The password is stored **encrypted** (leave the field blank on a later save to keep the stored + one), and a **Send test email** button verifies the account. See **§8.3**. The fields in detail: + - Mail counts as configured — the *Forgot your password?* links appear and the test button works — only when + **both** the host and the From address are set. + - **Port** — blank means `587`; otherwise a number from 1 to 65535. + - **STARTTLS** (a plain connection upgraded to TLS, usually port `587`) or **SSL** (TLS from the first byte, + usually port `465`). If both are ticked, SSL is used and STARTTLS is ignored. With neither, the connection is + not encrypted, and neither is the password when authentication is on. + - **Authentication** — off by default; while it is off the username and password are not sent. + - **The password cannot be removed from this form:** a blank field always keeps the stored one, even when you + empty every other field. To remove it, delete the `smtp:` block (or its `password:` line) from + `external/platform.yml` and restart (see *Editing platform.yml by hand* below). + +Leaving a field blank restores its default (no catch-all site; the `application.yml` password +strength; the node name from `runway.node.name` or the host name; no platform mail). The three compression +switches are the exception: a tick box has no "default" state, so **the first save of this page stores all three**, +and from then on they, not the shipped defaults, decide. A switch set in the server's `external/application.yml` +still wins over the saved one, and the page then shows it locked with where it is set. To hand a switch back to +the configuration, set it in `application.yml`, or delete it from `platform.yml` by hand. + +**What `external/platform.yml` holds.** The fields of this page are top-level keys: + +```yaml +defaultSiteId: acme # the catch-all site's id +passwordStrength: HIGH # STANDARD | HIGH +nodeName: web-1 +compressionEnabled: true +brotliEnabled: true +gzipEnabled: true +smtp: + host: smtp.example.com + port: 587 + auth: true + username: runway@example.com + password: ENC(...) # encrypted with runway.security.secret-key + from: runway@example.com + starttls: true + ssl: false +``` + +The same file also keeps `settings:` (Server settings and the policy cards, §8.5), `siteQuotas:` (each site's +bandwidth cap, §12), `siteStorageCeilings:` (each site's storage limit, §10), `embedHosts:` (§8.4) and `logLevels:` +(the levels set on Activity → Logs → Log levels). + +**Editing platform.yml by hand.** The running server reads this file once and keeps it in memory, so a hand edit +applies only **after a restart** — and a save of any console page that writes this file before that restart writes +the old values back over your edit. Stop the service, edit, start it. An unknown `passwordStrength` is logged and +ignored (the `application.yml` profile is used). + +**Clear template cache.** Below the settings form, **Clear template cache** empties the cache of parsed +page and chrome templates on **the node that answers you**. You normally never need it: Runway keeps the +cache on for speed, evicts exactly the right entries whenever a page or fragment is changed +**through the console** or a site is deleted or restored, and re-reads a template whose file changed +**outside** the console (edited on the server, copied in by a deployment script) on its next use — a +cached parse counts only while its files are unchanged on disk (Operations §5.2). It stays as a +backstop, e.g. for a file system whose timestamps cannot be trusted. (For **one** site, the site reload +of §12.2 does the same for that site's templates only, and leaves every other site's cache warm.) It is harmless — each page re-reads its template on its next request, which costs a few +milliseconds once — and is recorded in the activity log (`platform.template-cache-cleared`). In a +cluster it clears only the node that served the click: open the console on each node and run it there. +Restricted to the application superadmin or a wildcard admin. + +### 8.2 About Runway + +**Settings → About Runway** (`/__app/about`) is a **read-only** view of the running platform — useful +when diagnosing an install or filing a report. Unlike Platform settings it changes nothing and exposes +no secret, so it is visible to **any** signed-in operator. It has three parts: + +- **Version & build** — the running version and, when the build carries it, the build timestamp. +- **Effective configuration** — a curated table of the non-secret settings in force: whether TLS + terminates here or upstream, the HTTP port, reverse-proxy trust, the password-hashing profile, + whether secret encryption is configured, the data and backups directories, the backup + schedule/retention/off-host mirror, and the message-reload interval. These come from + `external/application.yml`; **a restart is needed to change them**. No secret value is ever shown — + secret-adjacent state (e.g. the master secret key) appears only as *configured / not configured*. +- **Runtime environment** — the node serving the request: active profiles, Java/JVM/OS, processors, + heap, data-disk free/total, uptime, start time, PID, host name, time zone and locale — plus the + versions of the bundled components (Spring Boot, Jetty, Thymeleaf, Jackson, and more). In a + multi-node deployment these describe **whichever node answered you**. + +### 8.3 Password recovery + +Both sign-in pages — the application login (`/app/login`) and each site's login (`/login`) — offer a +**"Forgot your password?"** link that lets a user reset their own password by email, without an operator. +The link appears **only when platform mail is configured** (§8.1); until then, recovery is done manually +(reset an application user from **§9**, a tenant-superadmin from **§10**, or a site sub-user from the +site console). + +How it works: + +1. The user clicks **Forgot your password?** and enters the **email address** of their account. Every + account type can recover — application users, tenant-superadmins, and site sub-users — **provided it + has a recovery email set** (captured when the account is created, and editable afterwards by an + administrator or by the user on their own **Account** page — `/__app/account` or `/__admin/account`, where + changing it asks for the current password; make sure operators and site managers set one). Five wrong + current passwords in a row on the Account page, for the email or the password, sign that session out, even + when they are sent all at once; each wrong one is journaled as `account.password-check-failed` with the + client's IP (`ip=203.0.113.9`) and counts toward the network's sign-in lockout. +2. The platform emails a **single-use link that expires in one hour**. For security the page always + shows the same *"if an account with that email exists…"* confirmation, whether or not any account + matched (no account enumeration). +3. Opening the link lets the user choose a new password. Reset links are stored only as **hashes** + (`external/recovery-tokens.yml`, an ephemeral file that is **not** part of any backup), are used + once, and requesting a new link invalidates the previous one. + +**Isolation.** A link is scoped to its realm and site: an application link can never reset a tenant +account, and a site's link works **only on that site's own host**. A tenant-superadmin who manages +several sites has one password; recovering it from any of their sites resets that single account. + +There is nothing to configure beyond the platform mail account — recovery is on automatically once mail +works. Verify it with **Send test email** (§8.1), then exercise a full round-trip from a login page. + +### 8.4 Content-Security-Policy and the public-page nonce secret + +Every HTML response carries a Content-Security-Policy header (`runway.csp.*`, **§8**). Out of the box it +is **report-only**: violations are logged by the in-kernel collector (`/__csp-report`, WARN level) and +nothing is blocked. Review the log, then set `runway.csp.mode: enforce` in the external +`application.yml` and restart. + +**The directives.** The policy is built once at startup from `runway.csp.*` (Settings → Server settings → +Content-Security-Policy, or `application.yml`; every field applies after a restart, and SETTINGS-REFERENCE.md lists +each default). Each directive key — `default-src`, `script-src`, `style-src`, `img-src`, `font-src`, `connect-src`, +`base-uri`, `form-action`, `frame-ancestors` — is the source list written after the directive's name, **exactly as +you type it** and not checked, so quote keywords the CSP way (`'self'`, `'none'`). Runway then adds to it: + +- `extra-hosts` (*Extra allowed hosts (all sites)* on Server settings: every site gets them) and the hosts plugins + declare (reCAPTCHA's, for instance) — `extra-hosts` to `default-src`, + `script-src`, `style-src`, `img-src`, `font-src`, `connect-src` and an added `frame-src`; plugin hosts to + `script-src`, `connect-src` and `frame-src` only; +- the response's nonce (and `'strict-dynamic'` where it applies) to `script-src`, which is therefore always sent; +- on a site's public pages, the embed hosts that site switched on (below), each to its own directive. + +A **blank value in `external/application.yml`** (`runway.csp.default-src: ""`) leaves that directive out. For +`style-src`, `img-src`, `font-src` and `connect-src` the browser then uses `default-src`; with `default-src` blank +too, those are unrestricted. `base-uri`, `form-action` and `frame-ancestors` do **not** fall back to +`default-src`: blank removes that protection (`frame-ancestors` is what stops other sites from framing yours). +On the Server settings screen a blank field restores the default instead (a form field cannot say "nothing"); to +omit a directive, set its key to `""` in `application.yml`, and the console then shows the field locked. +`object-src 'none'` is always sent and has no key. + +- `runway.csp.report-uri` — where browsers send violation reports: Runway's own collector at `/__csp-report` by + default, which writes them to the log at `WARN`. Any URL is used as given, so a report collector of your own + works too. A blank value in `application.yml` (`runway.csp.report-uri: ""`) sends no reporting directive at all + (no `report-uri`, `report-to` or `Reporting-Endpoints`), so `report` mode then only shows violations in each + visitor's browser console. On the Server settings screen a blank field restores `/__csp-report`. +- `runway.csp.upgrade-insecure-requests` — `true` adds `upgrade-insecure-requests`: the browser fetches every + `http://` image, script or style of a page over `https://` instead. Turn it on only once every host your pages + load from serves `https`, or those resources stop loading. + +**What `script-src` looks like.** The console and login/recovery pages get a fresh nonce per request +plus `'strict-dynamic'`. **Public site pages** get `'nonce-' 'strict-dynamic'` +too, where the nonce is **derived from the page version** (its ETag): every visitor and every cache +sees the same value until the page changes, so shared caching (`public, max-age=…`) and `304` +revalidation keep working exactly as before. The response edge adds that nonce to **the scripts the +allowlist policy would have run** — a `` is never stamped, and a script on any other +host is never stamped either, so both stay blocked in `enforce` mode exactly as they were before this +release; a `nonce` attribute already written in the markup is overridden, so a copied nonce cannot unlock a +script either. One exception: if you wrote `'unsafe-inline'` into `runway.csp.script-src` yourself (and no +`'nonce-…'`, `'sha…-…'` or `'strict-dynamic'` token next to it), the old policy ran inline scripts, so +inline scripts are stamped too and keep running. The stamp never runs a script the old policy blocked: a +script on a host outside the policy stays unstamped either way. Add any of those three tokens and the +exception ends: inline scripts are no longer stamped. `'self'` and the host allowlist +stay in the header as the fallback for browsers that predate `'strict-dynamic'`. *Why the stamp follows the +allowlist:* under `'strict-dynamic'` the browser runs a script only if it carries the nonce, so stamping +everything would have turned scripts the allowlist blocked — markup injected into a page included — into +scripts that run. *Why `'strict-dynamic'` at all:* a script the allowlist trusts may now load further +scripts itself (`document.createElement('script')`) on any host — reCAPTCHA's loader fetching its own +chunks is the case it exists for — while a modern browser no longer lets the allowlist alone authorize a +parser-inserted script. So add a host to `extra-hosts` only if you also trust what its scripts load. + +Responses with no page version — error pages, plugin endpoints, the maintenance page — keep the plain +`'self'` + host-allowlist policy. A page larger than the 8 MiB rewrite buffer is sent unrewritten with +the allowlist policy and `Cache-Control: no-store`. So is a page whose rendered markup **already contains +its own nonce** (in any spelling): markup copied the public value in — for example into an +`" + + ""; + } + + private ResponseEntity renderPreview(Site site, Page page, String localeParam, HttpServletRequest request) { + Locale locale = previewLocale(localeParam, page, site.defaultLocale()); + String body; + try { + // Force noindex on the in-page head-injection (read post-response at the edge); an empty baseUrl + // keeps a preview's canonical links off the live host. + request.setAttribute(HeadInjectionFilter.HEAD_CONTEXT_ATTRIBUTE, + modelBuilder.headContext(SiteViews.toView(site), page, locale, "", true)); + // Render the page, then anchor its relative URLs to the page's REAL public path. The preview is + // served at a deeper URL (/__admin/pages//preview) than the published page (/), so a + // relative asset URL in the content (e.g. "../static/img/x.jpg") would resolve against that deep + // path and 404 — even though it resolves fine live. A pinned to the public path makes + // the browser resolve every relative URL exactly as it will once published, so the preview is + // faithful. Injected at the response layer, never in tenant templates (isolation law). + body = withBaseHref(draftRenderer.render(site, page, locale, ""), + publicPath(page, locale, site.defaultLocale())); + } catch (RuntimeException ex) { + // A broken master/logic is the author's to fix — show the reason in the frame, not a 500 stack. + log.warn("preview render failed for {}/{}", site.id(), page.slug(), ex); + body = previewError(ex); + } + return ResponseEntity.ok() + .cacheControl(CacheControl.noStore()) + .header("X-Robots-Tag", "noindex, nofollow") + // The preview is author-controlled HTML rendered at the tenant-console origin. Sandbox it so a + // page's own scripts run in an OPAQUE origin (no allow-same-origin) — they can render, but can + // never reach the parent editor DOM, its CSRF token, cookies, or same-origin authenticated + // endpoints. A lower-privileged EDIT_PAGES author therefore cannot plant a script that escalates + // when a tenant superadmin opens the editor. The response CSP `sandbox` applies even on direct + // navigation; the editor iframe carries a matching sandbox attribute (defense in depth). + .header("Content-Security-Policy", "sandbox allow-scripts") + .header("X-Content-Type-Options", "nosniff") + .contentType(new MediaType(MediaType.TEXT_HTML, StandardCharsets.UTF_8)) + .body(body); + } + + private Site boundTenancy() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")); + } + + /** Matches the opening {@code } tag (case-insensitive) so a {@code } can be inserted first. */ + private static final Pattern HEAD_OPEN = Pattern.compile("]*>", Pattern.CASE_INSENSITIVE); + + /** + * The root-relative public URL path this page is served at in {@code locale} — the value a preview's + * {@code } is pinned to. Uses the page's real routing path (honoring per-locale slug overrides via + * {@link LocaleUrls}), not its {@code canonical} override (which may legitimately point off-site); a + * page with no path yet (a brand-new draft) resolves against the site root. + */ + private static String publicPath(Page page, Locale locale, Locale siteDefault) { + String path = page.pathFor(locale); + return (path == null || path.isBlank()) ? "/" : LocaleUrls.urlFor(path, locale, siteDefault); + } + + /** + * Inserts {@code } as the first child of {@code } so every relative URL in the previewed + * document resolves against the page's public path instead of the deeper preview endpoint URL. The href is + * attribute-escaped. If the document has no {@code } (a bare/standalone page) the tag is prepended — a + * stray {@code } is still hoisted into the head by the parser, so relative URLs are corrected either way. + */ + private static String withBaseHref(String html, String baseHref) { + if (html == null || baseHref == null || baseHref.isBlank()) { + return html; + } + String tag = ""; + Matcher m = HEAD_OPEN.matcher(html); + if (m.find()) { + return html.substring(0, m.end()) + tag + html.substring(m.end()); + } + return tag + html; + } + + private static Locale previewLocale(String param, Page page, Locale siteDefault) { + if (param != null && !param.isBlank()) { + Locale requested = Locale.forLanguageTag(param); + if (page.hasLocale(requested, siteDefault)) { + return requested; + } + } + return page.primaryLocale(siteDefault); + } + + /** A minimal draft stand-in for previewing a page that has not been saved yet. */ + private static Page minimalDraft(String slug) { + return new Page(slug, null, Map.of(), List.of(), Map.of(), Map.of(), "", "_master", true, false, null, null); + } + + private static String previewError(RuntimeException ex) { + String message = ex.getMessage() == null ? ex.getClass().getSimpleName() : ex.getMessage(); + return "Preview error" + + "" + + "

Preview could not be rendered

" + HtmlUtils.htmlEscape(message)
+                + "
"; + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantPagesController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantPagesController.java new file mode 100644 index 0000000..c231865 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantPagesController.java @@ -0,0 +1,74 @@ +package mx.quest.runway.console; + +import java.util.List; +import mx.quest.runway.authz.AuthzExpressions; +import mx.quest.runway.content.PathOwnership; +import mx.quest.runway.editorial.EditorialService; +import mx.quest.runway.page.Page; +import mx.quest.runway.page.PageStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteViews; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.server.ResponseStatusException; + +/** + * The tenant console's Pages listing ({@code /__admin/pages}): the grid of the bound tenancy's pages + * (slug, path, locales, editorial status) over {@link PageStore}, and the entry point to the editor (its Edit / + * New / disable-enable actions). + * + *

Gated by the grantable page permissions — {@code EDIT_PAGES} or {@code DISABLE_PAGES} — + * not the tenant master/wildcard gate: this is the editor's home and the destination the disable/enable + * actions redirect back to, so any user actually granted a page permission (not only a superadmin) must be + * able to reach and return to it. The mutating routes each re-enforce their own fine permission. + * + *

The status column shows where each page stands in the editorial workflow ({@link EditorialService#statuses}): + * draft, in review, returned, published, or published with a pending revision. The Enable (publish) button is + * offered only to a user who may publish at the site's level — on a reviewed site that takes {@code + * APPROVE_PAGES}; everyone else submits from the editor. + */ +@Controller +public class TenantPagesController { + + private final PageStore pages; + private final SiteResolver siteResolver; + private final PathOwnership pathOwnership; + private final EditorialService editorial; + private final AuthzExpressions authz; + + public TenantPagesController(PageStore pages, SiteResolver siteResolver, PathOwnership pathOwnership, + EditorialService editorial, AuthzExpressions authz) { + this.pages = pages; + this.siteResolver = siteResolver; + this.pathOwnership = pathOwnership; + this.editorial = editorial; + this.authz = authz; + } + + @GetMapping("/__admin/pages") + @PreAuthorize("@authz.may('EDIT_PAGES') or @authz.may('DISABLE_PAGES')") + public String list(Model model) { + Site site = tenancy(); + List all = pages.findAll(site.id()); + model.addAttribute("pages", all); + model.addAttribute("statuses", editorial.statuses(site.id(), all)); + model.addAttribute("canPublish", editorial.mayPublish(site, authz.may("APPROVE_PAGES"))); + model.addAttribute("editorialLevel", site.editorial().key()); + // The conflicts panel (the visibility triple's site-wide leg): every URL contested between a page and + // plugin content (page wins — the content is shadowed) or between two plugins (a loud 500 until an + // operator resolves it). Empty on almost every site; the template shows the panel only when non-empty. + model.addAttribute("conflicts", pathOwnership.conflicts(SiteViews.toView(site))); + model.addAttribute("contentTemplate", "operator/admin/pages"); + model.addAttribute("pageTitleKey", "op.pages.title"); + return "operator/op-layout"; + } + + private Site tenancy() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantPermissionsController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantPermissionsController.java new file mode 100644 index 0000000..0e7b9c9 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantPermissionsController.java @@ -0,0 +1,73 @@ +package mx.quest.runway.console; + +import mx.quest.runway.authz.AuthorizationAdminService; +import mx.quest.runway.authz.PermissionCatalog; +import mx.quest.runway.log.SiteLogService; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.spi.model.Realm; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.server.ResponseStatusException; + +/** + * The tenant-realm permissions matrix ({@code /__admin/permissions}): a TENANT principal (a tenant + * superadmin/admin) edits its bound tenancy's users and roles. The tenancy is the request's resolved + * site ({@link SiteResolver#current()}), never a path argument — so a tenant manager can only ever shape the + * tenancy they are signed into, and the application realm is unreachable from here (this route is on the tenant + * security chain only). Every successful change is recorded to the bound site's audit log. + */ +@Controller +@RequestMapping("/__admin/permissions") +public class TenantPermissionsController extends AbstractPermissionsController { + + private final SiteResolver siteResolver; + private final TenantAuthority tenantAuthority; + private final SiteLogService siteLog; + + public TenantPermissionsController(PermissionsMatrixService matrix, AuthorizationAdminService admin, + PermissionCatalog catalog, SiteResolver siteResolver, + TenantAuthority tenantAuthority, SiteLogService siteLog) { + super(matrix, admin, catalog); + this.siteResolver = siteResolver; + this.tenantAuthority = tenantAuthority; + this.siteLog = siteLog; + } + + @Override + protected void audit(String actor, String action, String detail) { + siteLog.audit(tenancyId(), actor, action, detail); + } + + @Override + protected void requireAdmin(org.springframework.security.core.Authentication authentication) { + tenantAuthority.require(authentication, tenancyId()); // master / wildcard of the bound tenancy + } + + @Override + protected Realm realm() { + return Realm.TENANT; + } + + @Override + protected String tenancyId() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")) + .id(); + } + + @Override + protected String basePath() { + return "/__admin/permissions"; + } + + @Override + protected String contentTemplate() { + return "operator/permissions"; + } + + @Override + protected String titleKey() { + return "op.permissions.title"; + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantPluginSettingsController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantPluginSettingsController.java new file mode 100644 index 0000000..887988f --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantPluginSettingsController.java @@ -0,0 +1,159 @@ +package mx.quest.runway.console; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import mx.quest.runway.authz.AuthorizationService; +import mx.quest.runway.authz.Permission; +import mx.quest.runway.authz.PermissionCatalog; +import mx.quest.runway.log.SiteLogService; +import mx.quest.runway.plugin.PluginAdminService; +import mx.quest.runway.plugin.PluginDescriptor; +import mx.quest.runway.plugin.PluginSettingDef; +import mx.quest.runway.plugin.SettingValidationException; +import mx.quest.runway.plugin.SitePluginConfigService; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.PathSafety; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +/** + * The per-tenant plugin settings form ({@code /__admin/plugins/{id}/settings}, tenant realm) — the kernel + * renders the plugin's declared {@code siteSettings:} schema generically over the bound tenancy's + * {@code sites//plugins/.yml} (via {@link SitePluginConfigService}); changes apply immediately + * (cache evicted + change event). Gated by the plugin's {@code |settings} permission when it declares one, + * else to the tenancy's administrators ({@link TenantAuthority}) — see {@code requireSettingsAccess}; the tenancy + * is the request's resolved site, never a path argument, so a tenant manager only ever configures the tenancy + * they are signed into. Reuses the same shared form template as the app-level settings. + */ +@Controller +public class TenantPluginSettingsController { + + private final SettingRefusals refusals; + private final PluginAdminService plugins; + private final SitePluginConfigService config; + private final TenantAuthority tenantAuthority; + private final SiteResolver siteResolver; + private final Environment environment; + private final SiteLogService siteLog; + private final PermissionCatalog catalog; + private final AuthorizationService authorization; + + public TenantPluginSettingsController(PluginAdminService plugins, SitePluginConfigService config, + TenantAuthority tenantAuthority, SiteResolver siteResolver, + Environment environment, SiteLogService siteLog, + PermissionCatalog catalog, AuthorizationService authorization, SettingRefusals refusals) { + this.refusals = refusals; + this.siteLog = siteLog; + this.plugins = plugins; + this.config = config; + this.tenantAuthority = tenantAuthority; + this.siteResolver = siteResolver; + this.environment = environment; + this.catalog = catalog; + this.authorization = authorization; + } + + /** + * The gate for one plugin's settings in the bound tenancy. When the plugin declares the reserved tenant-realm + * {@code settings} permission point ({@code |settings}), that permission is what opens the form — the same + * rule the console's Settings menu already used to show the link, so a user granted it no longer meets a 403 + * behind a visible entry. The tenancy's master and wildcard admins hold every permission, so they keep access. + * A plugin that declares no such point keeps the historical gate: the tenancy's administrators only. + */ + private void requireSettingsAccess(Authentication authentication, String tenancyId, String pluginId) { + if (!PathSafety.isSafeId(pluginId)) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such plugin"); + } + Permission declared = catalog.find(PathSafety.compoundKey(pluginId, "settings")) + .filter(permission -> permission.realm() == Realm.TENANT) + .orElse(null); + if (declared == null) { + tenantAuthority.require(authentication, tenancyId); + return; + } + boolean allowed = authentication != null + && authentication.getPrincipal() instanceof RunwayUserDetails principal + && principal.realm() == Realm.TENANT + && authorization.mayAccess(principal, declared, tenancyId); + if (!allowed) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, + "this operation needs the '" + declared.key() + "' permission in this site"); + } + } + + @GetMapping("/__admin/plugins/{id}/settings") + public String form(@PathVariable String id, Authentication authentication, Model model) { + String tenancyId = tenancy(); + requireSettingsAccess(authentication, tenancyId, id); + PluginDescriptor descriptor = descriptorOrThrow(id); + List schema = descriptor.siteSettings(); + + model.addAttribute("pluginName", descriptor.name() != null ? descriptor.name() : id); + var rendered = config.render(tenancyId, id, schema); + model.addAttribute("fields", rendered.stream().map(SettingField::of).toList()); + // Sections apply the descriptor's presentation keys; "inherit" and platform switches read the plugin's + // RUNNING app-level values, because that is what this tenant's site is actually getting. + model.addAttribute("sections", SettingsForm.build(rendered, descriptor, + SettingsForm.appValues(descriptor, environment))); + model.addAttribute("pendingKeys", List.of()); // per-tenant config applies immediately — no restart drift + model.addAttribute("strayKeys", List.of()); // unknown keys are preserved, not flagged + model.addAttribute("settingsAction", "/__admin/plugins/" + id + "/settings"); + // No standalone Site-settings landing any more — plugin settings hang off the console's Settings dropdown; + // Back/Cancel returns to the tenant dashboard. + model.addAttribute("settingsBack", "/__admin"); + model.addAttribute("settingsScope", "tenant"); + // A plugin's optional status/actions panel, rendered below the form from its own namespace. + if (plugins.hasAdminFragment(id)) { + model.addAttribute("adminFragment", "__plugin__/" + id + "/admin"); + } + model.addAttribute("contentTemplate", "operator/plugin-settings"); + model.addAttribute("pageTitleKey", "op.settings.title"); + return "operator/op-layout"; + } + + @PostMapping("/__admin/plugins/{id}/settings") + public String save(@PathVariable String id, HttpServletRequest request, Authentication authentication, + RedirectAttributes redirect) { + String tenancyId = tenancy(); + requireSettingsAccess(authentication, tenancyId, id); + List schema = descriptorOrThrow(id).siteSettings(); + try { + List dropped = config.save(tenancyId, id, schema, + PluginSettingsController.submittedValues(request, schema)); + // Only WHICH plugin changed is recorded — never the values (a setting may be a secret). A secret the + // save removed (a setting it is bound to changed) is named by key, which reveals nothing. + siteLog.audit(tenancyId, authentication.getName(), "plugin.settings-changed", + dropped.isEmpty() ? id : id + " (cleared " + String.join(", ", dropped) + ")"); + redirect.addFlashAttribute("flash", "Settings saved for '" + id + "' — applied immediately."); + if (!dropped.isEmpty()) { + redirect.addFlashAttribute("secretsDropped", String.join(", ", dropped)); + } + } catch (SettingValidationException invalid) { + redirect.addFlashAttribute("error", refusals.describe(invalid)); + } catch (RuntimeException e) { + redirect.addFlashAttribute("error", e.getMessage()); + } + return "redirect:/__admin/plugins/" + id + "/settings"; + } + + private String tenancy() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")) + .id(); + } + + private PluginDescriptor descriptorOrThrow(String id) { + return plugins.descriptor(id) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "no such plugin: " + id)); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantRecoveryController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantRecoveryController.java new file mode 100644 index 0000000..806ded2 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantRecoveryController.java @@ -0,0 +1,115 @@ +package mx.quest.runway.console; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import java.util.function.Function; +import mx.quest.runway.recovery.PasswordRecoveryService; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteResolver; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +/** + * The tenant-realm password-recovery flow — {@code /forgot-password} and {@code /reset}, served on a + * site's own host (the tenant counterpart to {@code /login}). The bound site is resolved from the host by the + * {@code SiteContextFilter} before this runs, so recovery is automatically scoped to that tenancy: it can only + * find/reset that site's own sub-users and the tenant-superadmins assigned to it, and a reset link is honoured + * only on the host it was issued for (the grant's site must equal the resolved site). + * + *

Like the login page, the routes are public; the flow is non-enumerating (a POST always shows the same + * neutral confirmation). All logic lives in {@link PasswordRecoveryService}. + */ +@Controller +public class TenantRecoveryController { + + private static final int MIN_PASSWORD_LENGTH = 8; + + private final PasswordRecoveryService recovery; + private final SiteResolver siteResolver; + + public TenantRecoveryController(PasswordRecoveryService recovery, SiteResolver siteResolver) { + this.recovery = recovery; + this.siteResolver = siteResolver; + } + + @GetMapping("/forgot-password") + public String forgot(@RequestParam(required = false) String sent, Model model) { + chrome(model, "/forgot-password"); + model.addAttribute("sent", sent != null); + return "operator/recovery-forgot"; + } + + @PostMapping("/forgot-password") + public String requestLink(@RequestParam(required = false) String email, Locale locale) { + String siteId = siteResolver.current().map(Site::id).orElse(null); + String base = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString(); + Function linkFor = + token -> base + "/reset?token=" + URLEncoder.encode(token, StandardCharsets.UTF_8); + recovery.requestTenant(siteId, email, brand(), linkFor, locale); + return "redirect:/forgot-password?sent"; + } + + @GetMapping("/reset") + public String resetForm(@RequestParam(required = false) String token, Model model) { + chrome(model, "/reset"); + String siteId = siteResolver.current().map(Site::id).orElse(null); + recovery.validateTenant(token, siteId).ifPresentOrElse( + grant -> { + model.addAttribute("valid", true); + model.addAttribute("token", token); + model.addAttribute("username", grant.username()); + }, + () -> model.addAttribute("valid", false)); + return "operator/recovery-reset"; + } + + @PostMapping("/reset") + public String doReset(@RequestParam(required = false) String token, + @RequestParam(required = false) String password, + @RequestParam(required = false) String confirm, Model model) { + String error = passwordError(password, confirm); + if (error != null) { + chrome(model, "/reset"); + model.addAttribute("valid", true); + model.addAttribute("token", token); + model.addAttribute("error", error); + return "operator/recovery-reset"; + } + String siteId = siteResolver.current().map(Site::id).orElse(null); + if (recovery.resetTenant(token, siteId, password) == PasswordRecoveryService.ResetOutcome.OK) { + return "redirect:/login?reset"; + } + chrome(model, "/reset"); + model.addAttribute("valid", false); + return "operator/recovery-reset"; + } + + /** The bound site's display name, or the platform brand when no site is bound (an unmatched host). */ + private String brand() { + return siteResolver.current().map(Site::name).orElse("Runway"); + } + + /** The realm-specific chrome the shared recovery templates bind (green accent, tenant URLs). */ + private void chrome(Model model, String postUrl) { + model.addAttribute("brand", brand()); + model.addAttribute("accentBorder", "border-success"); + model.addAttribute("accentBtn", "btn-success"); + model.addAttribute("loginUrl", "/login"); + model.addAttribute("postUrl", postUrl); + } + + private static String passwordError(String password, String confirm) { + if (password == null || password.length() < MIN_PASSWORD_LENGTH) { + return "weak"; + } + if (!password.equals(confirm)) { + return "mismatch"; + } + return null; + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantReviewController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantReviewController.java new file mode 100644 index 0000000..828ae95 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantReviewController.java @@ -0,0 +1,288 @@ +package mx.quest.runway.console; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import mx.quest.runway.editorial.EditorialException; +import mx.quest.runway.editorial.EditorialService; +import mx.quest.runway.editorial.LineDiff; +import mx.quest.runway.page.Page; +import mx.quest.runway.page.PageAuthoringException; +import mx.quest.runway.page.PageStore; +import mx.quest.runway.page.PageWriteService; +import mx.quest.runway.page.PendingRevisionStore; +import mx.quest.runway.quality.QualityGate; +import mx.quest.runway.quality.QualityReport; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.spi.model.Finding; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +/** + * The tenant console's editorial review surface, for sites at the {@code reviewed} level (it also works on + * whatever is still waiting after a site leaves that level): + * + *

    + *
  • {@code GET /__admin/review} — the queue: drafts submitted for their first publication and pending + * revisions of published pages, oldest first ({@code APPROVE_PAGES});
  • + *
  • {@code GET /__admin/review/{slug}} — one item: what changes (metadata table and a line diff of the body and + * logic against the live page), the live and proposed renders side by side, the quality findings of the + * proposed content, and the Approve / Send back actions ({@code APPROVE_PAGES});
  • + *
  • {@code POST /__admin/review/{slug}/approve} and {@code …/return} — the approver's two answers + * ({@code APPROVE_PAGES});
  • + *
  • {@code POST /__admin/pages/{slug}/submit} and {@code …/withdraw} — the editor's side: submit a draft (or + * a returned revision) for review, or take it back out ({@code EDIT_PAGES}).
  • + *
+ * + *

Every route is method-gated and acts on the bound tenancy only ({@link SiteResolver#current()}), never a + * path or parameter id, so one site's approver can never see or act on another site's queue. The rules + * themselves live in {@link EditorialService}; this controller only maps them to screens and messages. + */ +@Controller +public class TenantReviewController { + + private final SiteResolver siteResolver; + private final PageStore pages; + private final PageWriteService writer; + private final EditorialService editorial; + private final QualityGate gate; + private final MessageSource messages; + + public TenantReviewController(SiteResolver siteResolver, PageStore pages, PageWriteService writer, + EditorialService editorial, QualityGate gate, + @Qualifier("operatorAwareMessageSource") MessageSource messages) { + this.siteResolver = siteResolver; + this.pages = pages; + this.writer = writer; + this.editorial = editorial; + this.gate = gate; + this.messages = messages; + } + + /** One metadata field of the comparison: its label key, the live and proposed values, whether it changed. */ + public record MetaRow(String label, String locale, String before, String after, boolean changed) { + } + + /** One queue row for the screen: the page, whether it is a revision, who submitted it and when (formatted). */ + public record QueueRow(String slug, String path, boolean revision, String submittedBy, String submittedAt) { + } + + /** A localized finding (severity lower-cased for the badge class). */ + public record FindingRow(String severity, String code, String message) { + } + + @GetMapping("/__admin/review") + @PreAuthorize("@authz.may('APPROVE_PAGES')") + public String queue(Model model) { + Site site = boundTenancy(); + model.addAttribute("items", editorial.queue(site).stream() + .map(i -> new QueueRow(i.page().slug(), i.page().path(), i.revision(), i.review().submittedBy(), + TenantPageEditorController.when(i.review().submittedAt()))) + .toList()); + model.addAttribute("editorialLevel", site.editorial().key()); + model.addAttribute("pageTitleKey", "op.review.title"); + model.addAttribute("contentTemplate", "operator/admin/review"); + return "operator/op-layout"; + } + + @GetMapping("/__admin/review/{slug}") + @PreAuthorize("@authz.may('APPROVE_PAGES')") + public String item(@PathVariable String slug, Model model, RedirectAttributes redirect) { + Site site = boundTenancy(); + Optional found = editorial.queue(site).stream() + .filter(i -> i.page().slug().equals(slug)).findFirst(); + if (found.isEmpty()) { + redirect.addFlashAttribute("error", message("op.review.error.not-in-review", "Nothing is waiting.")); + return "redirect:/__admin/review"; + } + EditorialService.QueueItem item = found.get(); + Page live = item.page(); + String liveHtml = writer.readBody(site.id(), slug).orElse(""); + String liveLogic = writer.readLogic(site.id(), slug).orElse(""); + Page proposed = live; + String html = liveHtml; + String logic = liveLogic; + if (item.revision()) { + Optional rev = writer.pending().revision(site.id(), slug); + if (rev.isPresent()) { + proposed = rev.get().page().withDraft(live.draft()); + html = rev.get().html(); + logic = rev.get().thxml() == null ? "" : rev.get().thxml(); + } + } + model.addAttribute("item", item); + model.addAttribute("submittedAt", TenantPageEditorController.when(item.review().submittedAt())); + model.addAttribute("live", live); + model.addAttribute("proposed", proposed); + List meta = item.revision() ? metaRows(live, proposed, site) : List.of(); + model.addAttribute("metaRows", meta); + model.addAttribute("metaChanged", meta.stream().anyMatch(MetaRow::changed)); + LineDiff.Result body = LineDiff.diff(liveHtml, html); + LineDiff.Result logicDiff = LineDiff.diff(liveLogic, logic); + model.addAttribute("bodyDiff", body); + model.addAttribute("logicDiff", logicDiff); + model.addAttribute("liveUrl", "/__admin/pages/" + slug + "/preview"); + model.addAttribute("proposedUrl", "/__admin/pages/" + slug + "/preview" + (item.revision() ? "?revision=1" : "")); + QualityReport report = gate.inspect(site, proposed, html, logic, + proposed.primaryLocale(site.defaultLocale())); + model.addAttribute("findings", localize(report.findings())); + model.addAttribute("enforced", site.editorial().enforcesChecks()); + model.addAttribute("hasErrors", report.errors() > 0); + model.addAttribute("editorialLevel", site.editorial().key()); + model.addAttribute("pageTitleKey", "op.review.item.title"); + model.addAttribute("contentTemplate", "operator/admin/review-item"); + return "operator/op-layout"; + } + + @PostMapping("/__admin/review/{slug}/approve") + @PreAuthorize("@authz.may('APPROVE_PAGES')") + public String approve(@PathVariable String slug, @RequestParam(required = false) String fingerprint, + RedirectAttributes redirect) { + Site site = boundTenancy(); + try { + List blocking = editorial.approve(site, slug, fingerprint); + if (!blocking.isEmpty()) { + redirect.addFlashAttribute("error", message("op.review.blocked.approve", + "Not approved: the page has quality errors.") + " " + reasons(blocking)); + return "redirect:/__admin/review/" + slug; + } + redirect.addFlashAttribute("flash", message("op.review.approved", "Approved and published.")); + } catch (EditorialException ex) { + redirect.addFlashAttribute("error", message("op.review.error." + ex.code(), ex.getMessage())); + return "changed".equals(ex.code()) ? "redirect:/__admin/review/" + slug : "redirect:/__admin/review"; + } catch (PageAuthoringException ex) { + redirect.addFlashAttribute("error", message("op.pages.error." + ex.code(), ex.getMessage())); + return "redirect:/__admin/review/" + slug; + } + return "redirect:/__admin/review"; + } + + @PostMapping("/__admin/review/{slug}/return") + @PreAuthorize("@authz.may('APPROVE_PAGES')") + public String sendBack(@PathVariable String slug, @RequestParam(required = false) String note, + RedirectAttributes redirect) { + Site site = boundTenancy(); + try { + editorial.sendBack(site, slug, note); + redirect.addFlashAttribute("flash", message("op.review.returned", "Sent back to the editor.")); + } catch (EditorialException ex) { + redirect.addFlashAttribute("error", message("op.review.error." + ex.code(), ex.getMessage())); + return "note-required".equals(ex.code()) ? "redirect:/__admin/review/" + slug : "redirect:/__admin/review"; + } + return "redirect:/__admin/review"; + } + + @PostMapping("/__admin/pages/{slug}/submit") + @PreAuthorize("@authz.may('EDIT_PAGES')") + public String submit(@PathVariable String slug, RedirectAttributes redirect) { + Site site = boundTenancy(); + try { + editorial.submit(site, slug); + redirect.addFlashAttribute("flash", message("op.review.submitted", "Submitted for review.")); + } catch (EditorialException ex) { + redirect.addFlashAttribute("error", message("op.review.error." + ex.code(), ex.getMessage())); + } + return "redirect:/__admin/pages/" + slug + "/edit"; + } + + @PostMapping("/__admin/pages/{slug}/withdraw") + @PreAuthorize("@authz.may('EDIT_PAGES')") + public String withdraw(@PathVariable String slug, RedirectAttributes redirect) { + Site site = boundTenancy(); + if (pages.find(site.id(), slug).isEmpty()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such page"); + } + editorial.withdraw(site, slug); + redirect.addFlashAttribute("flash", message("op.review.withdrawn", "Taken out of review.")); + return "redirect:/__admin/pages/" + slug + "/edit"; + } + + /** + * The metadata comparison rows between the live page and its revision — every field the editor can change, + * per locale where it is per-locale. Only changed rows are flagged; unchanged ones are still listed so the + * approver sees the whole picture. + */ + static List metaRows(Page live, Page proposed, Site site) { + List rows = new ArrayList<>(); + rows.add(row("path", "", live.path(), proposed.path())); + Set langs = new LinkedHashSet<>(); + site.locales().forEach(l -> langs.add(l.getLanguage())); + langs.addAll(live.title().keySet()); + langs.addAll(proposed.title().keySet()); + langs.addAll(live.description().keySet()); + langs.addAll(proposed.description().keySet()); + langs.addAll(live.localizedPaths().keySet()); + langs.addAll(proposed.localizedPaths().keySet()); + for (String lang : langs) { + rows.add(row("title", lang, live.title().get(lang), proposed.title().get(lang))); + rows.add(row("description", lang, live.description().get(lang), proposed.description().get(lang))); + rows.add(row("localizedPath", lang, live.localizedPaths().get(lang), proposed.localizedPaths().get(lang))); + } + rows.add(row("locales", "", join(live.locales()), join(proposed.locales()))); + rows.add(row("template", "", live.template(), proposed.template())); + rows.add(row("activeNav", "", live.activeNav(), proposed.activeNav())); + rows.add(row("author", "", live.author(), proposed.author())); + rows.add(row("publishedAt", "", str(live.publishedAt()), str(proposed.publishedAt()))); + rows.add(row("canonical", "", live.canonical(), proposed.canonical())); + rows.add(row("cacheControl", "", live.cacheControl(), proposed.cacheControl())); + rows.add(row("noindex", "", Boolean.toString(live.noindex()), Boolean.toString(proposed.noindex()))); + rows.add(row("nosnippet", "", Boolean.toString(live.nosnippet()), Boolean.toString(proposed.nosnippet()))); + rows.add(row("gone", "", Boolean.toString(live.gone()), Boolean.toString(proposed.gone()))); + rows.add(row("params", "", live.params().toString(), proposed.params().toString())); + return rows; + } + + private static MetaRow row(String label, String locale, String before, String after) { + String b = before == null ? "" : before; + String a = after == null ? "" : after; + return new MetaRow(label, locale, b, a, !Objects.equals(b, a)); + } + + private static String join(List locales) { + return locales.stream().map(Locale::getLanguage).collect(Collectors.joining(", ")); + } + + private static String str(Object value) { + return value == null ? "" : value.toString(); + } + + private List localize(List findings) { + Locale ui = LocaleContextHolder.getLocale(); + List rows = new ArrayList<>(findings.size()); + for (Finding f : findings) { + rows.add(new FindingRow(f.severity().name().toLowerCase(Locale.ROOT), f.code(), + messages.getMessage("quality." + f.code(), null, f.message(), ui))); + } + return rows; + } + + private String reasons(List blocking) { + return localize(blocking).stream().map(FindingRow::message).collect(Collectors.joining(" · ")); + } + + private String message(String code, String fallback) { + return messages.getMessage(code, null, fallback, LocaleContextHolder.getLocale()); + } + + private Site boundTenancy() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantSiteConfigController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantSiteConfigController.java new file mode 100644 index 0000000..f0ce421 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantSiteConfigController.java @@ -0,0 +1,310 @@ +package mx.quest.runway.console; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.authz.AuthzExpressions; +import mx.quest.runway.log.SiteLogService; +import mx.quest.runway.page.Page; +import mx.quest.runway.page.PageStore; +import mx.quest.runway.site.EditorialLevel; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteContact; +import mx.quest.runway.site.SiteContactService; +import mx.quest.runway.site.SiteLifecycleService; +import mx.quest.runway.site.SiteParamsService; +import mx.quest.runway.site.SiteResolver; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +/** + * The tenant console's Site config screen ({@code /__admin/config}): a site manager edits the site's + * settings in Runway's kernel field set — + * + *

    + *
  • display name — the site's human-facing name;
  • + *
  • languages — the available locales and which one is the default (the default must be among the + * available; validated server-side);
  • + *
  • contact — the site's public contact information ({@link SiteContact}: email, phone, address);
  • + *
  • template parameters — the site-level {@code params.yml} key/value editor deferred here from the + * page editor, reusing the page editor's exact parallel-array param rows, scoped to the site + * (a page's own params overlay these at render time);
  • + *
  • editorial level — {@link EditorialLevel advisory, enforced or reviewed}: how strictly publishing + * is governed. Changing it additionally requires {@code APPROVE_PAGES}: the level is what stands between an + * editor and the live site, so a user who could otherwise only configure the site must not be able to + * switch review off and publish. Without that permission the choice is shown read-only and a posted value + * is ignored. A missing value keeps the current level (an older form cannot reset it to advisory).
  • + *
+ * + *

What stays app-controlled, and why. A tenant may not edit its {@code hosts} (host→site + * routing is a platform concern — a tenant could otherwise hijack another site's host or the app realm) nor the + * site {@code id} (its folder name and stable identity), nor its lifecycle ({@code status}/maintenance are + * operator/tenant-maintenance surfaces of their own). Those fields are simply absent from this form and + * preserved by {@link Site#withConfig}, so a crafted POST cannot change them. + * + *

Isolation. The edited tenancy is always the bound one ({@link SiteResolver#current()}), + * never a path/param id — so this screen can only ever read and write the current site's own files, and a + * second site is provably untouched. + * + *

Immediate apply. A name/locale change is persisted via {@link SiteLifecycleService#updateConfig} + * which publishes a {@code SiteChangedEvent(UPDATED)}; every per-site cache (resolver index, params, SEO, i18n, + * manifest…) drops the site's entry, so the change is live on the next request. Contact and params evict their + * own caches on save. + * + *

Audit. A save that changed anything is recorded in the site's audit log as + * {@code site-config.changed}, naming which parts changed ({@code name}, {@code languages}, {@code contact}, + * {@code params}, and {@code editorial=}) — never the other values, since a template parameter may hold + * something a site manager would not want copied into a journal; the editorial level is not sensitive and the + * journal is where a reviewer looks to see when review was switched on or off. + * + *

Gated by the grantable {@code CONFIGURE_SITE} permission — the same gate as SEO/Icons. + */ +@Controller +public class TenantSiteConfigController { + + private final SiteResolver siteResolver; + private final SiteLifecycleService lifecycle; + private final SiteContactService contacts; + private final SiteParamsService siteParams; + private final PageStore pages; + private final MessageSource messages; + private final SiteLogService siteLog; + private final AuthzExpressions authz; + + private final mx.quest.runway.platform.EmbedHostService embedHosts; + private final mx.quest.runway.site.SiteCspService siteCsp; + + public TenantSiteConfigController(SiteResolver siteResolver, SiteLifecycleService lifecycle, + SiteContactService contacts, SiteParamsService siteParams, PageStore pages, + @Qualifier("operatorAwareMessageSource") MessageSource messages, + SiteLogService siteLog, AuthzExpressions authz, + mx.quest.runway.platform.EmbedHostService embedHosts, + mx.quest.runway.site.SiteCspService siteCsp) { + this.embedHosts = embedHosts; + this.siteCsp = siteCsp; + this.siteLog = siteLog; + this.authz = authz; + this.siteResolver = siteResolver; + this.lifecycle = lifecycle; + this.contacts = contacts; + this.siteParams = siteParams; + this.pages = pages; + this.messages = messages; + } + + @GetMapping("/__admin/config") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String form(Model model) { + Site site = boundTenancy(); + model.addAttribute("site", site); + model.addAttribute("effectiveBaseUrl", mx.quest.runway.site.SiteViews.toView(site).baseUrl()); + model.addAttribute("embedHosts", embedHosts.list()); + model.addAttribute("embedChosen", siteCsp.chosen(site.id())); + model.addAttribute("siteName", site.name()); + model.addAttribute("defaultLocale", site.defaultLocale().toLanguageTag()); + model.addAttribute("locales", site.locales()); + model.addAttribute("contact", contacts.get(site.id())); + // Site-level template parameters as an ordered entry list, exactly like the page editor's paramEntries + // (the .th.xml iterates a row per entry, plus a trailing blank row to add one). + model.addAttribute("paramEntries", List.copyOf(siteParams.get(site.id()).entrySet())); + model.addAttribute("editorialLevel", site.editorial().key()); + model.addAttribute("editorialLevels", java.util.Arrays.stream(EditorialLevel.values()) + .map(EditorialLevel::key).toList()); + model.addAttribute("mayChangeEditorial", authz.may("APPROVE_PAGES")); + model.addAttribute("pageTitleKey", "op.config.title"); + model.addAttribute("contentTemplate", "operator/admin/site-config"); + return "operator/op-layout"; + } + + /** + * Switches the operator's approved embed hosts on or off for this site's public pages. Only approved ids are kept + * ({@link mx.quest.runway.site.SiteCspService#save}); the change applies on the next page. + */ + @PostMapping("/__admin/config/embeds") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String saveEmbeds(@RequestParam(name = "hosts", required = false) List hosts, + org.springframework.security.core.Authentication authentication, + RedirectAttributes redirect) { + Site site = boundTenancy(); + siteCsp.save(site.id(), hosts); + siteLog.audit(site.id(), authentication == null ? "unknown" : authentication.getName(), + "site.embeds-changed", String.join(",", siteCsp.chosen(site.id()))); + redirect.addFlashAttribute("flash", messages.getMessage("op.config.embeds.saved", null, + "Embedded content saved.", LocaleContextHolder.getLocale())); + return "redirect:/__admin/config"; + } + + @PostMapping("/__admin/config") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String save(@RequestParam(required = false) String name, + @RequestParam(required = false) String defaultLocale, + @RequestParam(name = "locale", required = false) List localeTags, + @RequestParam(required = false) String contactEmail, + @RequestParam(required = false) String contactPhone, + @RequestParam(required = false) String contactAddress, + @RequestParam(name = "paramKey", required = false) List paramKeys, + @RequestParam(name = "paramValue", required = false) List paramValues, + @RequestParam(required = false) String editorial, + Authentication authentication, RedirectAttributes redirect) { + Site site = boundTenancy(); + String actor = authentication == null ? "" : authentication.getName(); + + // --- Validate the name + language set BEFORE writing anything (an invalid submit changes nothing). The + // rules are shared with the operator's Sites screen (SiteConfigInput), so the two can never disagree. + // The default is NOT force-added to the available set — a default outside it is an error to fix. --- + SiteConfigInput.Valid valid; + try { + valid = SiteConfigInput.validate(name, defaultLocale, localeTags); + } catch (SiteConfigInput.Invalid invalid) { + return reject(redirect, invalid.messageKey(), invalid.getMessage()); + } + Locale defaultLoc = valid.defaultLocale(); + List available = valid.locales(); // default first, the rest in submitted order + // The editorial level: only an APPROVE_PAGES holder may change it; a missing value keeps the current one; + // an unknown value is rejected before anything is written. + EditorialLevel level = site.editorial(); + if (editorial != null && !editorial.isBlank() && !editorial.equals(site.editorial().key())) { + EditorialLevel requested = EditorialLevel.parseStrict(editorial).orElse(null); + if (requested == null) { + return reject(redirect, "op.config.error.editorial", "Choose a valid editorial level."); + } + if (!authz.may("APPROVE_PAGES")) { + return reject(redirect, "op.config.error.editorialPermission", + "Changing the editorial level requires the Approve pages permission."); + } + level = requested; + } + + // --- Persist name + languages (publishes UPDATED → caches evict → live next request). --- + lifecycle.updateConfig(site.id(), valid.name(), defaultLoc, available); + List changed = new ArrayList<>(); + if (!valid.name().equals(site.name())) { + changed.add("name"); + } + if (!available.equals(site.locales()) || !defaultLoc.equals(site.defaultLocale())) { + changed.add("languages"); + } + if (level != site.editorial()) { + lifecycle.updateEditorial(site.id(), level); + changed.add("editorial=" + level.key()); + } + + // --- Persist contact + site params (each evicts its own cache). --- + SiteContact contactBefore = contacts.get(site.id()); + Map paramsBefore = siteParams.get(site.id()); + try { + SiteContact contactAfter = new SiteContact(blankToNull(contactEmail), blankToNull(contactPhone), + blankToNull(contactAddress)); + contacts.save(site.id(), contactAfter); + if (!contactAfter.equals(contactBefore)) { + changed.add("contact"); + } + siteParams.save(site.id(), zipParams(paramKeys, paramValues)); + if (!siteParams.get(site.id()).equals(paramsBefore)) { + changed.add("params"); + } + } catch (IOException | RuntimeException e) { + // A params key with a nested value throws IllegalArgumentException from the service; surface it and + // keep the (already-saved) name/languages. The form re-renders with the flash error. + auditChanges(site.id(), actor, changed); + redirect.addFlashAttribute("error", message("op.config.error.save", "Could not save site settings.")); + return "redirect:/__admin/config"; + } + auditChanges(site.id(), actor, changed); + + // --- Advisory warnings (routing/URLs degrade gracefully, never break). `site` is the pre-save snapshot, + // so site.defaultLocale() is the OLD default. --- + boolean defaultChanged = !defaultLoc.equals(site.defaultLocale()); + List orphaned = pagesLosingLocale(site, available); + String flash = orphaned.isEmpty() + ? message("op.config.saved", "Site settings saved.") + : message("op.config.saved.langWarn", "Saved. Some pages still declare a language you removed: ") + + String.join(", ", orphaned); + if (defaultChanged) { + // Existing pages keep their URL paths (authored for the previous default), so a slug may no longer + // match its content language — nudge the operator to review page paths (we never rewrite them). + flash += " " + message("op.config.saved.defaultLocaleWarn", + "You changed the default language — existing pages keep their URL paths, so a page's URL may " + + "no longer match its content language. Review each page's Path in the page editor."); + } + redirect.addFlashAttribute("flash", flash); + return "redirect:/__admin/config"; + } + + /** + * Pages that declare a locale no longer in the site's available set. Such a page is not broken — it falls + * back to its {@linkplain Page#primaryLocale(Locale) primary locale} — but the operator should know the + * removed language will no longer route, so we warn (never silently drop, never hard-block). Read-only. + */ + private List pagesLosingLocale(Site site, List available) { + List orphaned = new ArrayList<>(); + for (Page page : pages.findAll(site.id())) { + boolean loses = page.locales().stream().anyMatch(loc -> !available.contains(loc)); + if (loses) { + orphaned.add(page.slug()); + } + } + return orphaned; + } + + /** + * Pairs the {@code paramKey[]}/{@code paramValue[]} arrays positionally into an ordered map, mirroring the + * page editor's {@code PageForm.zipParams}: a blank/null key is dropped, a missing value becomes empty, and + * the last value wins on a duplicate key. {@link SiteParamsService#save} re-sanitizes (trims keys, rejects + * nested values), so this stays deliberately thin. + */ + private static Map zipParams(List keys, List values) { + Map params = new LinkedHashMap<>(); + if (keys == null) { + return params; + } + for (int i = 0; i < keys.size(); i++) { + String key = keys.get(i); + if (key == null || key.isBlank()) { + continue; + } + String value = (values != null && i < values.size() && values.get(i) != null) ? values.get(i) : ""; + params.put(key.trim(), value); + } + return params; + } + + /** Records which parts of the site config a save changed (nothing when it changed nothing). */ + private void auditChanges(String siteId, String actor, List changed) { + if (!changed.isEmpty()) { + siteLog.audit(siteId, actor, "site-config.changed", String.join(",", changed)); + } + } + + private String reject(RedirectAttributes redirect, String key, String fallback) { + redirect.addFlashAttribute("error", message(key, fallback)); + return "redirect:/__admin/config"; + } + + private Site boundTenancy() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")); + } + + private String message(String key, String fallback) { + return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale()); + } + + private static String blankToNull(String value) { + return (value == null || value.isBlank()) ? null : value.strip(); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantStaticFilesController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantStaticFilesController.java new file mode 100644 index 0000000..8d86128 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantStaticFilesController.java @@ -0,0 +1,249 @@ +package mx.quest.runway.console; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import mx.quest.runway.bandwidth.Bytes; +import mx.quest.runway.log.SiteLogService; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStorageCeilings; +import mx.quest.runway.site.StaticFilesService; +import mx.quest.runway.site.StaticFilesService.Refused; +import mx.quest.runway.storage.SiteFileStore; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; +import org.springframework.web.util.UriUtils; + +/** + * The site console's Static files screen ({@code /__admin/static}): browse the site's {@code static/} folder, + * upload files (several at once, optionally replacing ones of the same name), create folders, and delete files and + * empty folders, over {@link StaticFilesService} and its rules (web asset types only, a size cap, {@code doc/} left + * to Documents, the site's storage ceiling). The screen shows what the site's files use against that ceiling. + * + *

Gated by {@code CONFIGURE_SITE}, like Fragments: stylesheets and scripts shape every page as much as the + * master does. Always the bound site; every change is recorded in the site's audit log. + */ +@Controller +public class TenantStaticFilesController { + + private static final String SCREEN = "/__admin/static"; + + private final SiteResolver siteResolver; + private final StaticFilesService staticFiles; + private final MessageSource messages; + private final SiteLogService siteLog; + private final SiteStorageCeilings ceilings; + + public TenantStaticFilesController(SiteResolver siteResolver, StaticFilesService staticFiles, + @Qualifier("operatorAwareMessageSource") MessageSource messages, + SiteLogService siteLog, SiteStorageCeilings ceilings) { + this.siteResolver = siteResolver; + this.staticFiles = staticFiles; + this.messages = messages; + this.siteLog = siteLog; + this.ceilings = ceilings; + } + + /** One row of the listing, with what the screen needs to show and link it. */ + public record Row(String name, boolean directory, String size, long sizeBytes, long modified, String path, + String publicUrl, boolean documents) { + } + + /** One step of the folder breadcrumb. */ + public record Crumb(String name, String path) { + } + + @GetMapping(SCREEN) + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String list(@RequestParam(required = false) String dir, Model model) throws IOException { + String siteId = currentSiteId(); + String folder; + try { + folder = StaticFilesService.existingPath(dir); + } catch (Refused bad) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such folder"); + } + if (!staticFiles.folderExists(siteId, folder)) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no such folder"); + } + List rows = new ArrayList<>(); + for (SiteFileStore.Entry entry : staticFiles.list(siteId, folder)) { + String path = folder.isEmpty() ? entry.name() : folder + "/" + entry.name(); + rows.add(new Row(entry.name(), entry.directory(), + entry.directory() ? "" : Bytes.human(entry.size()), entry.size(), entry.modified(), path, + "/static/" + UriUtils.encodePath(path, StandardCharsets.UTF_8), + StaticFilesService.isDocuments(path))); + } + List crumbs = new ArrayList<>(); + StringBuilder walked = new StringBuilder(); + if (!folder.isEmpty()) { + for (String part : folder.split("/")) { + walked.append(walked.length() == 0 ? "" : "/").append(part); + crumbs.add(new Crumb(part, walked.toString())); + } + } + model.addAttribute("folder", folder); + model.addAttribute("crumbs", crumbs); + model.addAttribute("rows", rows); + model.addAttribute("inDocuments", StaticFilesService.isDocuments(folder)); + model.addAttribute("maxMiB", StaticFilesService.MAX_FILE_BYTES >> 20); + // What the site's files use and the ceiling the operator set (read-only here). + SiteStorageCeilings.Ceiling ceiling = ceilings.of(siteId); + long used = ceilings.usedBytes(siteId); + model.addAttribute("storageUsed", Bytes.human(used)); + model.addAttribute("storageLimited", ceiling.limited()); + model.addAttribute("storageCeiling", Bytes.human(ceiling.bytes())); + model.addAttribute("storageOver", ceiling.limited() && used > ceiling.bytes()); + model.addAttribute("allowedTypes", String.join(", ", + StaticFilesService.ALLOWED_EXTENSIONS.stream().sorted().toList())); + model.addAttribute("contentTemplate", "operator/admin/static-files"); + model.addAttribute("pageTitleKey", "op.static.title"); + return "operator/op-layout"; + } + + /** + * Uploads one or more files into {@code dir}. Each file is checked on its own: the ones that pass are stored, + * the others are named in the error with the reason, so one bad file does not lose the rest. + */ + @PostMapping(SCREEN + "/upload") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String upload(@RequestParam(required = false) String dir, + @RequestParam(name = "files", required = false) List uploads, + @RequestParam(defaultValue = "false") boolean replace, Authentication authentication, + RedirectAttributes redirect) { + String siteId = currentSiteId(); + String folder = safeFolder(dir); + List stored = new ArrayList<>(); + List refused = new ArrayList<>(); + if (uploads != null) { + for (MultipartFile upload : uploads) { + if (upload == null || upload.isEmpty()) { + continue; + } + String original = upload.getOriginalFilename(); + try { + if (upload.getSize() > StaticFilesService.MAX_FILE_BYTES) { + throw new Refused("tooLarge", "too large"); + } + String name = staticFiles.upload(siteId, folder, original, upload.getBytes(), replace); + stored.add(name); + siteLog.audit(siteId, actor(authentication), "static.uploaded", join(folder, name)); + } catch (Refused why) { + refused.add(original + ": " + message("op.static.refused." + why.code(), why.getMessage())); + } catch (IOException | IllegalArgumentException failed) { + refused.add(original + ": " + message("op.static.failed", "could not be saved")); + } + } + } + if (stored.isEmpty() && refused.isEmpty()) { + redirect.addFlashAttribute("error", message("op.static.noFile", "Choose at least one file.")); + } + if (!stored.isEmpty()) { + redirect.addFlashAttribute("flash", messages.getMessage("op.static.uploaded", + new Object[] {stored.size(), String.join(", ", stored)}, "Uploaded.", + LocaleContextHolder.getLocale())); + } + if (!refused.isEmpty()) { + redirect.addFlashAttribute("error", message("op.static.notUploaded", "Not uploaded:") + " " + + String.join(" · ", refused)); + } + return back(folder); + } + + /** Creates a folder inside {@code dir}. */ + @PostMapping(SCREEN + "/folder") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String folder(@RequestParam(required = false) String dir, @RequestParam(required = false) String name, + Authentication authentication, RedirectAttributes redirect) { + String siteId = currentSiteId(); + String folder = safeFolder(dir); + try { + staticFiles.createFolder(siteId, folder, name); + siteLog.audit(siteId, actor(authentication), "static.folder-created", join(folder, name.strip())); + redirect.addFlashAttribute("flash", message("op.static.folderCreated", "Folder created.")); + } catch (Refused why) { + redirect.addFlashAttribute("error", message("op.static.refused." + why.code(), why.getMessage())); + } catch (IOException failed) { + redirect.addFlashAttribute("error", message("op.static.failed", "could not be saved")); + } + return back(folder); + } + + /** Deletes a file, or a folder when it is empty, then returns to the folder that held it. */ + @PostMapping(SCREEN + "/delete") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String delete(@RequestParam(required = false) String path, Authentication authentication, + RedirectAttributes redirect) { + String siteId = currentSiteId(); + // Not stripped: a name with a leading or trailing space (" logo.css") is a real, listed name, and deleting + // it must name it exactly. A blank path is the static folder itself, which the service refuses. + String target = path == null || path.isBlank() ? "" : path; + String parent = target.contains("/") ? target.substring(0, target.lastIndexOf('/')) : ""; + try { + if (staticFiles.delete(siteId, target)) { + ceilings.changed(siteId); + siteLog.audit(siteId, actor(authentication), "static.deleted", target); + redirect.addFlashAttribute("flash", message("op.static.deleted", "Deleted.")); + } else { + redirect.addFlashAttribute("error", message("op.static.notDeleted", + "Nothing was deleted: the file is gone, or the folder is not empty.")); + } + } catch (Refused why) { + redirect.addFlashAttribute("error", message("op.static.refused." + why.code(), why.getMessage())); + } catch (IOException failed) { + redirect.addFlashAttribute("error", message("op.static.failed", "could not be saved")); + } + return back(safeFolderOrRoot(parent)); + } + + private static String safeFolder(String dir) { + try { + return StaticFilesService.existingPath(dir); + } catch (Refused bad) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "not a folder"); + } + } + + private static String safeFolderOrRoot(String dir) { + try { + return StaticFilesService.existingPath(dir); + } catch (Refused bad) { + return ""; + } + } + + private static String back(String folder) { + return "redirect:" + SCREEN + (folder.isEmpty() ? "" + : "?dir=" + UriUtils.encodeQueryParam(folder, StandardCharsets.UTF_8)); + } + + private static String join(String folder, String name) { + return folder.isEmpty() ? name : folder + "/" + name; + } + + private static String actor(Authentication authentication) { + return authentication == null ? "unknown" : authentication.getName(); + } + + private String currentSiteId() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")).id(); + } + + private String message(String key, String fallback) { + return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale()); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/TenantUsersController.java b/runway-app/src/main/java/mx/quest/runway/console/TenantUsersController.java new file mode 100644 index 0000000..686fe97 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/TenantUsersController.java @@ -0,0 +1,328 @@ +package mx.quest.runway.console; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import mx.quest.runway.authz.AuthorizationAdminService; +import mx.quest.runway.authz.Role; +import mx.quest.runway.authz.RoleStore; +import mx.quest.runway.log.SiteLogService; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.SiteUserStore; +import mx.quest.runway.security.User; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.spi.model.Realm; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +/** + * The tenant console's Users screen ({@code /__admin/users}): the bound tenancy's sub-users. List / + * create / edit (display name, recovery email, access tier) / suspend / resume / reset-password / delete over + * {@link SiteUserStore} (edit and suspend through {@link ConsoleUserService}), always scoped to the resolved tenancy — a tenant + * manager can never reach another tenancy's users. A created sub-user belongs to exactly this tenancy. + * + *

Gates. The screen opens with {@code MANAGE_USERS} or {@code DELETE_USERS}; create / edit / suspend / + * resume / reset-password need {@code MANAGE_USERS}, delete needs {@code DELETE_USERS} (method security, so the + * site's superadmin and administrators pass as before and an operator needs the grant). On top of the verb, every + * action on an existing user passes {@link SiteUserAuthority#requireMayActOn}: a holder who is not a site + * administrator reaches only users who hold nothing beyond their own permissions — never an administrator. A + * non-administrator creates {@code OPERATOR}-tier users only, without custom roles (role assignment stays with + * the administrators). A new user's login name must be free on this site — not held, case-insensitively, by + * another user of the site or by a tenant superadmin assigned to it ({@link SiteUserStore#save}); otherwise a + * {@code MANAGE_USERS} holder could create a user named like the superadmin and sign in under that name. + * + *

A user's role model has two layers. The access tier ({@code OPERATOR} or {@code ADMIN}) + * lives in the user's own record ({@code User.roles()}) — it is the coarse console-access gate (see + * {@code TenantSiteAuthorizationManager}) and the Spring authority, so every console user must have exactly + * one. Any additional custom roles are layered on through the per-tenancy grant file via + * {@link AuthorizationAdminService#assignRole} — the same channel the permissions matrix uses, so create and + * the matrix agree on where a custom-role assignment is stored (and a later revoke can find it). + */ +@Controller +@RequestMapping("/__admin/users") +public class TenantUsersController { + + private final SiteUserStore siteUsers; + private final SiteResolver siteResolver; + private final PasswordEncoder passwordEncoder; + private final SiteUserAuthority userAuthority; + private final RoleStore roleStore; + private final AuthorizationAdminService admin; + private final ConsoleUserService userService; + private final SiteLogService siteLog; + private final MessageSource messages; + + public TenantUsersController(SiteUserStore siteUsers, SiteResolver siteResolver, PasswordEncoder passwordEncoder, + SiteUserAuthority userAuthority, RoleStore roleStore, AuthorizationAdminService admin, + ConsoleUserService userService, SiteLogService siteLog, + @Qualifier("operatorAwareMessageSource") MessageSource messages) { + this.siteUsers = siteUsers; + this.siteResolver = siteResolver; + this.passwordEncoder = passwordEncoder; + this.userAuthority = userAuthority; + this.roleStore = roleStore; + this.admin = admin; + this.userService = userService; + this.siteLog = siteLog; + this.messages = messages; + } + + /** + * The users list. Every affordance is shown only where the action behind it would be allowed (UX only — each + * POST re-checks): {@code canManage}/{@code canDelete} for the verbs, {@code siteAdmin} for the tier choice + * and custom roles, {@code manageable} for the rows this manager may act on. + */ + @GetMapping + @PreAuthorize("@authz.may('MANAGE_USERS') or @authz.may('DELETE_USERS')") + public String list(Authentication authentication, Model model) { + String tenancyId = tenancy(); + RunwayUserDetails actor = actor(authentication); + List users = siteUsers.list(tenancyId); + model.addAttribute("users", users); + // The signed-in manager's own row offers no Suspend and no tier change (the service refuses both). + model.addAttribute("selfId", actor.principalId()); + boolean siteAdmin = userAuthority.isSiteAdmin(actor, tenancyId); + model.addAttribute("siteAdmin", siteAdmin); + model.addAttribute("canManage", userAuthority.mayManage(actor, tenancyId)); + model.addAttribute("canDelete", userAuthority.mayDelete(actor, tenancyId)); + model.addAttribute("manageable", users.stream().filter(u -> userAuthority.mayActOn(actor, tenancyId, u)) + .map(User::principalId).collect(java.util.stream.Collectors.toSet())); + model.addAttribute("customRoles", siteAdmin + ? roleStore.siteRoleList(tenancyId).stream().map(Role::name).toList() : List.of()); + model.addAttribute("contentTemplate", "operator/admin/users"); + model.addAttribute("pageTitleKey", "op.users.title"); + return "operator/op-layout"; + } + + /** + * Creates a user of this site. A non-administrator ({@code MANAGE_USERS} granted) creates {@code OPERATOR}-tier + * users only and cannot layer custom roles; the tier is checked with the same bounded-grant rule as a tier + * change ({@link AuthorizationAdminService#mayGrantRole}). + */ + @PostMapping("/create") + @PreAuthorize("@authz.may('MANAGE_USERS')") + public String create(@RequestParam String username, @RequestParam String password, @RequestParam String tier, + @RequestParam(name = "roles", required = false) List roles, + @RequestParam(required = false) String displayName, @RequestParam(required = false) String email, + Authentication authentication, RedirectAttributes redirect) { + String tenancyId = tenancy(); + RunwayUserDetails actor = actor(authentication); + try { + if (!Roles.OPERATOR.equals(tier) && !Roles.ADMIN.equals(tier)) { + throw new IllegalArgumentException("invalid access tier '" + tier + "'"); + } + if (!admin.mayGrantRole(actor, tier, tenancyId)) { + throw new IllegalArgumentException(message("op.users.error.tierNotAllowed", null)); + } + boolean siteAdmin = userAuthority.isSiteAdmin(actor, tenancyId); + // Only real custom roles of this tenancy may be layered on — reject anything else (a tier here, or + // a stale/foreign name) before touching the store, so the create never half-succeeds. + Set customNames = roleStore.siteRoleList(tenancyId).stream().map(Role::name) + .collect(java.util.stream.Collectors.toSet()); + List requested = new ArrayList<>(); + if (roles != null) { + for (String r : roles) { + if (r != null && !r.isBlank() && !requested.contains(r)) { + if (!siteAdmin) { + throw new IllegalArgumentException(message("op.users.error.rolesAdminOnly", null)); + } + if (!customNames.contains(r)) { + throw new IllegalArgumentException("no such custom role '" + r + "'"); + } + requested.add(r); + } + } + } + String newId = UUID.randomUUID().toString(); + siteUsers.save(tenancyId, new User(newId, username.trim(), + passwordEncoder.encode(password), displayName == null || displayName.isBlank() ? username.trim() + : displayName.trim(), email == null ? "" : email.trim(), true, false, Realm.TENANT, + Set.of(tier), List.of())); + List assigned = new ArrayList<>(); + for (String r : requested) { + try { + admin.assignRole(actor, tenancyId, newId, r); // grant file — bounded-grant enforced here + assigned.add(r); + } catch (RuntimeException ex) { + // Roll back COMPLETELY: strip grant-file roles written so far, then delete the user — no + // orphaned principalId→role mapping left behind on a half-created user. + for (String done : assigned) { + try { + admin.revokeRole(actor, tenancyId, newId, done); + } catch (RuntimeException ignored) { + // best-effort cleanup; the user delete below removes the principal regardless + } + } + siteUsers.delete(tenancyId, newId); + throw new IllegalArgumentException("could not assign role '" + r + "': " + ex.getMessage()); + } + } + siteLog.audit(tenancyId, authentication.getName(), "user.created", username.trim() + " (" + tier + ")" + + (assigned.isEmpty() ? "" : " roles=" + String.join(",", assigned))); + redirect.addFlashAttribute("flash", "Created user '" + username.trim() + "'" + + (requested.isEmpty() ? "." : " with role(s): " + String.join(", ", requested) + ".")); + } catch (mx.quest.runway.security.UsernameTakenException e) { + // The name is held by another user of this site or by a superadmin assigned to it (the store checks + // both): refused, so no one can sign in under a name that is already someone else's here. + redirect.addFlashAttribute("error", message("op.users.error.usernameTaken", e.username())); + } catch (RuntimeException e) { + redirect.addFlashAttribute("error", e.getMessage()); + } + return "redirect:/__admin/users"; + } + + private RunwayUserDetails actor(Authentication authentication) { + if (authentication != null && authentication.getPrincipal() instanceof RunwayUserDetails principal) { + return principal; + } + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "not authenticated in this realm"); + } + + /** + * Edits one of this tenancy's users: display name, recovery email and — except for the manager's own account — + * access tier. Guards (tenant scope, self, bounded grant) live in {@link ConsoleUserService}. Recorded in the + * site's audit log. + */ + @PostMapping("/{principalId}/edit") + @PreAuthorize("@authz.may('MANAGE_USERS')") + public String edit(@PathVariable String principalId, @RequestParam(required = false) String displayName, + @RequestParam(required = false) String email, @RequestParam(required = false) String tier, + Authentication authentication, RedirectAttributes redirect) { + String tenancyId = tenancy(); + try { + requireMayActOn(authentication, tenancyId, principalId); + User updated = userService.updateSiteUser(actor(authentication), tenancyId, principalId, displayName, + email, tier); + siteLog.audit(tenancyId, authentication.getName(), "user.updated", + updated.username() + " (" + String.join(",", new java.util.TreeSet<>(updated.roles())) + ")"); + redirect.addFlashAttribute("flash", message("op.users.edit.saved", updated.username())); + } catch (ConsoleUserService.UserEditException e) { + redirect.addFlashAttribute("error", error(e)); + } catch (IllegalStateException | java.io.UncheckedIOException e) { + redirect.addFlashAttribute("error", e.getMessage()); // a store guard or a failed write: never a 500 + } + return "redirect:/__admin/users"; + } + + /** Suspends one of this tenancy's users: sign-in refused, and an open session is dropped on its next request. */ + @PostMapping("/{principalId}/suspend") + @PreAuthorize("@authz.may('MANAGE_USERS')") + public String suspend(@PathVariable String principalId, Authentication authentication, + RedirectAttributes redirect) { + return setEnabled(principalId, false, authentication, redirect); + } + + /** Resumes a suspended user of this tenancy (sign-in allowed again; the password is unchanged). */ + @PostMapping("/{principalId}/resume") + @PreAuthorize("@authz.may('MANAGE_USERS')") + public String resume(@PathVariable String principalId, Authentication authentication, + RedirectAttributes redirect) { + return setEnabled(principalId, true, authentication, redirect); + } + + private String setEnabled(String principalId, boolean enabled, Authentication authentication, + RedirectAttributes redirect) { + String tenancyId = tenancy(); + try { + requireMayActOn(authentication, tenancyId, principalId); + User updated = userService.setSiteUserEnabled(actor(authentication), tenancyId, principalId, enabled); + siteLog.audit(tenancyId, authentication.getName(), enabled ? "user.resumed" : "user.suspended", + updated.username()); + redirect.addFlashAttribute("flash", + message(enabled ? "op.users.resumed" : "op.users.suspended", updated.username())); + } catch (ConsoleUserService.UserEditException e) { + redirect.addFlashAttribute("error", error(e)); + } catch (IllegalStateException | java.io.UncheckedIOException e) { + redirect.addFlashAttribute("error", e.getMessage()); // a store guard or a failed write: never a 500 + } + return "redirect:/__admin/users"; + } + + private String message(String key, Object arg) { + return messages.getMessage(key, arg == null ? null : new Object[] {arg}, key, LocaleContextHolder.getLocale()); + } + + /** + * The target bound ({@link SiteUserAuthority#requireMayActOn}) for an action on an existing user of this site. + * An unknown id passes through, so the action reports "no such user" exactly as before. + */ + private void requireMayActOn(Authentication authentication, String tenancyId, String principalId) { + java.util.Optional target = siteUsers.findByPrincipalId(tenancyId, principalId); + if (target.isPresent()) { + userAuthority.requireMayActOn(actor(authentication), tenancyId, target.get()); + } + } + + private String error(ConsoleUserService.UserEditException e) { + return messages.getMessage("op.users.error." + e.code(), null, e.getMessage(), + LocaleContextHolder.getLocale()); + } + + /** + * Sets one of this site's users' password. Every open session of that user on this site ends on its next + * request ({@code AccountStateFilter} sees the hash change); an administrator resetting their OWN password + * here keeps this session, like the Account screen. + */ + @PostMapping("/reset-password") + @PreAuthorize("@authz.may('MANAGE_USERS')") + public String resetPassword(@RequestParam String principalId, @RequestParam String password, + Authentication authentication, RedirectAttributes redirect, + jakarta.servlet.http.HttpServletRequest request) { + String tenancyId = tenancy(); + try { + User user = siteUsers.list(tenancyId).stream().filter(u -> u.principalId().equals(principalId)).findFirst() + .orElseThrow(() -> new IllegalArgumentException("no such user")); + userAuthority.requireMayActOn(actor(authentication), tenancyId, user); + User updated = user.withPasswordHash(passwordEncoder.encode(password)); + siteUsers.save(tenancyId, updated); + mx.quest.runway.security.AccountStateFilter.rebindIfSelf(request, updated); + siteLog.audit(tenancyId, authentication.getName(), "user.password-reset", user.username()); + redirect.addFlashAttribute("flash", "Reset the password for '" + user.username() + "'."); + } catch (ConsoleUserService.UserEditException e) { + redirect.addFlashAttribute("error", error(e)); + } catch (RuntimeException e) { + redirect.addFlashAttribute("error", e.getMessage()); + } + return "redirect:/__admin/users"; + } + + /** Deletes one of this site's users — {@code DELETE_USERS}, within the same target bound as the other actions. */ + @PostMapping("/{principalId}/delete") + @PreAuthorize("@authz.may('DELETE_USERS')") + public String delete(@PathVariable String principalId, Authentication authentication, RedirectAttributes redirect) { + String tenancyId = tenancy(); + java.util.Optional target = siteUsers.findByPrincipalId(tenancyId, principalId); + if (target.isPresent() && !userAuthority.mayActOn(actor(authentication), tenancyId, target.get())) { + redirect.addFlashAttribute("error", message("op.users.error.beyondAuthority", null)); + return "redirect:/__admin/users"; + } + String username = target.map(User::username).orElse(principalId); + boolean deleted = siteUsers.delete(tenancyId, principalId); + if (deleted) { + siteLog.audit(tenancyId, authentication.getName(), "user.deleted", username); + } + redirect.addFlashAttribute(deleted ? "flash" : "error", deleted ? "Deleted the user." : "No such user."); + return "redirect:/__admin/users"; + } + + private String tenancy() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")).id(); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/WidgetInstancesController.java b/runway-app/src/main/java/mx/quest/runway/console/WidgetInstancesController.java new file mode 100644 index 0000000..9dd16fa --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/WidgetInstancesController.java @@ -0,0 +1,124 @@ +package mx.quest.runway.console; + +import jakarta.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.List; +import mx.quest.runway.plugin.PluginSettingDef; +import mx.quest.runway.plugin.SettingValidationException; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.storage.PathSafety; +import mx.quest.runway.widget.WidgetInstanceConfigService; +import mx.quest.runway.widget.WidgetInstanceDiscovery; +import mx.quest.runway.widget.WidgetInstanceDiscovery.PlacedWidget; +import mx.quest.runway.widget.WidgetSettingsCatalog; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.server.ResponseStatusException; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +/** + * The tenant console's Content widgets screen ({@code /__admin/widgets}): a site manager configures each + * content-widget placement a designer anchored into the site's templates. The screen discovers the + * placements ({@link WidgetInstanceDiscovery}), and for each whose widget declares a per-instance schema + * ({@link WidgetSettingsCatalog}) renders a typed editor bound to the tenant's {@code widget-instances.yml} + * ({@link WidgetInstanceConfigService}); a placement whose widget declares no settings is shown as present but + * not configurable. Changes apply immediately. Gated by the grantable {@code CONFIGURE_SITE} permission; the + * tenancy is the request's resolved site, never a parameter — a manager only ever configures the site they are + * signed into. + */ +@Controller +public class WidgetInstancesController { + + private final SettingRefusals refusals; + private final SiteResolver siteResolver; + private final WidgetInstanceDiscovery discovery; + private final WidgetSettingsCatalog catalog; + private final WidgetInstanceConfigService config; + private final MessageSource messages; + + public WidgetInstancesController(SiteResolver siteResolver, WidgetInstanceDiscovery discovery, + WidgetSettingsCatalog catalog, WidgetInstanceConfigService config, + @Qualifier("operatorAwareMessageSource") MessageSource messages, + SettingRefusals refusals) { + this.refusals = refusals; + this.siteResolver = siteResolver; + this.discovery = discovery; + this.catalog = catalog; + this.config = config; + this.messages = messages; + } + + /** + * A placement row for the screen: its identity and the template(s) it sits in, whether it is configurable, + * and — when it is — the current form fields and the save action. + */ + public record InstanceView(String type, String instance, String templates, boolean configurable, + List fields, String action) { + } + + @GetMapping("/__admin/widgets") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String list(Model model) { + String siteId = currentSiteId(); + List placed = discovery.discover(siteId); + List instances = new ArrayList<>(placed.size()); + for (PlacedWidget widget : placed) { + List schema = catalog.schemaFor(widget.type()); + List fields = schema.isEmpty() + ? List.of() + : config.render(siteId, widget.type(), widget.instance(), schema).stream() + .map(SettingField::of).toList(); + instances.add(new InstanceView(widget.type(), widget.instance(), + String.join(", ", widget.templates()), !schema.isEmpty(), fields, + "/__admin/widgets/" + widget.type() + "/" + widget.instance())); + } + model.addAttribute("instances", instances); + model.addAttribute("contentTemplate", "operator/admin/widget-instances"); + model.addAttribute("pageTitleKey", "op.widgets.title"); + return "operator/op-layout"; + } + + @PostMapping("/__admin/widgets/{type}/{instance}") + @PreAuthorize("@authz.may('CONFIGURE_SITE')") + public String save(@PathVariable String type, @PathVariable String instance, HttpServletRequest request, + RedirectAttributes redirect) { + String siteId = currentSiteId(); + if (!PathSafety.isSafeId(type) || !PathSafety.isSafeId(instance)) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "invalid widget instance"); + } + List schema = catalog.schemaFor(type); + if (schema.isEmpty()) { + // No such configurable widget type — either the widget declares no settings or its plugin is absent. + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "widget type '" + type + "' is not configurable"); + } + try { + config.save(siteId, type, instance, schema, + PluginSettingsController.submittedValues(request, schema)); + redirect.addFlashAttribute("flash", + message("op.widgets.saved", "Widget settings saved — applied immediately.")); + } catch (SettingValidationException invalid) { + redirect.addFlashAttribute("error", refusals.describe(invalid)); + } catch (RuntimeException e) { + redirect.addFlashAttribute("error", message("op.widgets.failed", "Could not save widget settings.")); + } + return "redirect:/__admin/widgets"; + } + + private String currentSiteId() { + return siteResolver.current() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "no bound tenancy")) + .id(); + } + + private String message(String key, String fallback) { + return messages.getMessage(key, null, fallback, LocaleContextHolder.getLocale()); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/console/WrongPasswordCounter.java b/runway-app/src/main/java/mx/quest/runway/console/WrongPasswordCounter.java new file mode 100644 index 0000000..fdc575a --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/console/WrongPasswordCounter.java @@ -0,0 +1,49 @@ +package mx.quest.runway.console; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; +import org.springframework.stereotype.Component; + +/** + * Counts the wrong current passwords typed on the Account screens, per session and account ({@link AccountSupport}). + * A guess reserves its number before its password is hashed, atomically, so a burst of simultaneous guesses + * cannot all read the same count: guesses past {@link AccountSupport#MAX_WRONG_PASSWORDS} are refused before any + * hashing, however many arrive at once. + * + *

Why not a session attribute

+ * Until 1.0.0 the count was a session attribute, read and written back by each request: two requests at the same + * moment read the same number, and a burst of eight was answered eight times. Locking the session object does not + * fix that everywhere: with clustered sessions each request works on its own copy of the session, saved when it + * ends. This counter lives on the node, where an atomic increment is one step. With clustering on and requests of + * one session spread over several nodes (no sticky sessions), each node counts its own; the per-IP gate still + * applies on every node. + * + *

Bounded and self-cleaning: an entry is dropped by a right password or a spent session, and otherwise expires + * after {@link #IDLE} without a guess; at most {@link #MAX_ENTRIES} are kept. + */ +@Component +public class WrongPasswordCounter { + + /** How long a count is kept after its last guess: longer than any console session stays idle. */ + static final Duration IDLE = Duration.ofHours(12); + /** The most counts kept at once; each needs a signed-in session that guessed wrong. */ + static final long MAX_ENTRIES = 100_000; + + private final Cache counts = + Caffeine.newBuilder().maximumSize(MAX_ENTRIES).expireAfterAccess(IDLE).build(); + + /** + * Reserves the next guess for {@code key} and returns its number: 1 for the first guess since the last reset. + * Called before the password is checked, so the number counts the guesses still being checked too. + */ + public int reserve(String key) { + return counts.get(key, unused -> new AtomicInteger()).incrementAndGet(); + } + + /** Clears {@code key}'s count: the right password was typed, or the session's sign-in was dropped. */ + public void reset(String key) { + counts.invalidate(key); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/content/ContentCatalog.java b/runway-app/src/main/java/mx/quest/runway/content/ContentCatalog.java new file mode 100644 index 0000000..5a64247 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/content/ContentCatalog.java @@ -0,0 +1,409 @@ +package mx.quest.runway.content; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import mx.quest.runway.endpoint.EndpointContributorRegistry; +import mx.quest.runway.page.ContentUrls; +import mx.quest.runway.page.LocaleUrls; +import mx.quest.runway.plugin.ContributionGuard; +import mx.quest.runway.spi.ContentSource; +import mx.quest.runway.spi.model.CatalogEntry; +import mx.quest.runway.spi.model.ContentRef; +import mx.quest.runway.spi.model.LocalizedUrl; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.storage.PathSafety; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +/** + * The kernel's enumeration authority over every content source (pages included): the one call the + * listing consumers — the sitemap, llms.txt, URL maps, search indexing — make to see a site's whole published + * content surface, already kernel-re-filtered fail-closed. Consumers never iterate the registry raw; + * this class is where the source-discipline backstops live: + * + *

    + *
  • published-only — an unpublished ref a source leaks is dropped;
  • + *
  • path-safe — a ref whose default or localized path fails {@link PathSafety} is dropped;
  • + *
  • reserved-path drop — a ref whose URL (in any of its locales) would collide with the reserved + * kernel surface ({@code /__…}, {@code /actuator}, {@code /error}, {@code /login}, {@code /logout}, + * {@code /app/…}) or with an exact {@link mx.quest.runway.spi.EndpointContributor} route + * ({@code /sitemap.xml}, {@code /robots.txt}, …) is dropped — a listing must never advertise a URL the + * router will not serve as content;
  • + *
  • failure containment — a throwing source contributes nothing (WARN) and never breaks the + * listing of the others.
  • + *
+ * + *

The contributor registry arrives lazily ({@link ObjectProvider}) because endpoint contributors (the + * sitemap itself) may depend on this catalog — resolving at call time breaks the construction cycle. + * + *

Caching

+ * {@link #enumerate} is cached per site (evicted by the page/content/site/plugin-config change events — the + * kernel's first {@code ContentChangedEvent} listeners — with a 30s TTL backstop for changes no event + * announces). {@link #enumerateContributed} and {@link #urlMap} stay uncached: sources self-cache their own + * enumeration (the authoring-guide discipline), and the pages projection is skipped there entirely. + */ +@Component +public class ContentCatalog { + + private static final Logger log = LoggerFactory.getLogger(ContentCatalog.class); + + /** How long a cached enumeration may serve without an eviction event (the no-event safety net). */ + private static final long CACHE_TTL_MILLIS = 30_000L; + + /** One site's listing: the routable items and their SPI entries (built together, so they always agree). */ + private record CachedList(List items, List entries, long at) { + } + + /** + * The last-seen URL index: per site, composite id → the URLs the item had in the + * most recent uncached enumeration. Replaced whole on every enumeration and never cleared by eviction, so it + * outlives the 30-second cache: when a page or an entry is deleted or moved, the SPI bridge snapshots its old + * URLs from here before any listener evicts anything (that is how a deletion reaches IndexNow). Dropped only when + * the site itself is deleted. Empty for a site not enumerated since boot (documented on {@code CatalogChange}). + */ + private final java.util.concurrent.ConcurrentMap>> lastSeen = + new java.util.concurrent.ConcurrentHashMap<>(); + + private final ContentSourceRegistry registry; + private final ObjectProvider endpoints; + /** Per-site cached enumeration — evicted by the four content-shaping events below, TTL as backstop. */ + private final java.util.concurrent.ConcurrentMap cache = + new java.util.concurrent.ConcurrentHashMap<>(); + /** + * Per-site eviction epoch, bumped BEFORE each cache removal. An in-flight enumeration records the epoch + * before loading and declines to cache its result if an eviction landed meanwhile — otherwise the + * get→load→put sequence would re-install a pre-change list over the eviction with a fresh timestamp, + * nullifying the event and (worse) letting a search engine that rebuilds on that very event cache an index + * over the stale list for its full freshness window. + */ + private final java.util.concurrent.ConcurrentMap evictionEpoch = + new java.util.concurrent.ConcurrentHashMap<>(); + + @Autowired + public ContentCatalog(ContentSourceRegistry registry, ObjectProvider endpoints) { + this.registry = registry; + this.endpoints = endpoints; + } + + /** Bare form for unit tests / fixtures — no contributor registry (its reserved drops don't apply). */ + public ContentCatalog(ContentSourceRegistry registry) { + this.registry = registry; + this.endpoints = new ObjectProvider() { + @Override public EndpointContributorRegistry getObject() { throw new IllegalStateException("none"); } + @Override public EndpointContributorRegistry getIfAvailable() { return null; } + }; + } + + /** + * Every source's published content for {@code site} — pages and plugin content alike, in registration + * order, re-filtered per the class contract. Metadata only ({@code enumerate} never reads bodies), so this + * is safe on public, anonymous request paths. + * + * @param site the site being listed (never {@code null}) + * @return the sanitized refs, each with its owning source key (never {@code null}; may be empty) + */ + public List enumerate(SiteView site) { + return listing(site).items(); + } + + /** + * The same listing as {@link #enumerate}, as the SPI's {@link CatalogEntry} values (what + * {@code ContentCatalogView.entries} hands plugins) — built in the same pass and cached with it. + * + * @param site the site being listed (never {@code null}) + * @return the entries (never {@code null}; unmodifiable) + */ + public List entries(SiteView site) { + return listing(site).entries(); + } + + /** + * The URLs {@code compositeId} had when {@code siteId} was last enumerated (see {@link #lastSeen}): what a change + * event reports as the item's previous URLs. + * + * @return the URLs, or an empty list when the item was not in the last listing (or the site was never listed) + */ + public List lastSeenUrls(String siteId, String compositeId) { + Map> index = lastSeen.get(siteId); + if (index == null) { + return List.of(); + } + List urls = index.get(compositeId); + return urls == null ? List.of() : urls; + } + + private CachedList listing(SiteView site) { + // Cached per site: a sitemap/llms.txt hit or a conflicts screen must not re-stat every page file and + // re-read every source on each request. Evicted by the content-shaping events; TTL is the backstop + // for changes no event announces (a hand-edited file). System time is fine here (a freshness window). + CachedList cached = cache.get(site.id()); + if (cached != null && System.currentTimeMillis() - cached.at() < CACHE_TTL_MILLIS) { + return cached; + } + long epoch = evictionEpoch.getOrDefault(site.id(), 0L); + List items = enumerateUncached(site); + List entries = new ArrayList<>(items.size()); + Map> index = new HashMap<>(items.size() * 2); + for (RoutableContent item : items) { + CatalogEntry entry = item.toCatalogEntry(site); + entries.add(entry); + index.put(entry.compositeId(), entry.urls()); + } + CachedList fresh = new CachedList(items, List.copyOf(entries), System.currentTimeMillis()); + lastSeen.put(site.id(), Map.copyOf(index)); // replaced whole; outlives eviction on purpose + // Cache only if no eviction landed while we loaded — see evictionEpoch. A skipped put is cheap + // (the next caller reloads); a stale put would outlive the event that tried to kill it. + if (evictionEpoch.getOrDefault(site.id(), 0L) == epoch) { + cache.put(site.id(), fresh); + } + return fresh; + } + + private List enumerateUncached(SiteView site) { + EndpointContributorRegistry routes = endpoints.getIfAvailable(); + List out = new ArrayList<>(); + for (ContentSource source : registry.sources()) { + List refs = enumerate(source, site); + if (refs == null) { + continue; + } + for (ContentRef ref : refs) { + if (ref != null && admissible(source, ref, site, routes)) { + out.add(new RoutableContent(source.key(), ref)); + } + } + } + return List.copyOf(out); + } + + // --- cache eviction: the four events that can change a site's content surface -------------------------- + // + // Ordering across the stacked cache layers matters. A source self-caches its own enumeration (e.g. a + // plugin's ref index), THIS catalog caches the union, and each search engine caches an index built FROM the + // union. All three evict on the same events, dispatched synchronously on the publishing thread. If a + // concurrent request rebuilt an engine's index mid-dispatch while an inner layer were still stale, it would + // cache stale content. The kernel's convention: evict OUTERMOST-LAST — sources at HIGHEST_PRECEDENCE, the + // page record caches at KernelEventOrder.STORES, this catalog at KernelEventOrder.CATALOG, engines at + // LOWEST_PRECEDENCE (see the search plugins). The page caches MUST precede this catalog: the pages source + // enumerates through them, so a catalog rebuilt between the two evictions would re-cache stale Page records + // for the whole TTL (the defect KernelEventOrder fixed). Because the engine's own + // invalidation is the last act of the dispatch, any index a concurrent query built during the dispatch is + // discarded, so the next query rebuilds through fully-evicted inner layers. + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.CATALOG) + public void onPageChanged(mx.quest.runway.page.PageChangedEvent event) { + evict(event.siteId()); + } + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.CATALOG) + public void onContentChanged(ContentChangedEvent event) { + evict(event.siteId()); + } + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.CATALOG) + public void onSiteChanged(mx.quest.runway.site.SiteChangedEvent event) { + evict(event.siteId()); + if (event.kind() == mx.quest.runway.site.SiteChangedEvent.Kind.DELETED) { + lastSeen.remove(event.siteId()); // the site is gone; a later site with this id starts unlisted + } + } + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.CATALOG) + public void onSitePluginConfigChanged(mx.quest.runway.plugin.SitePluginConfigChangedEvent event) { + evict(event.siteId()); // any plugin's per-site config may reshape its source's output + } + + /** + * The catalog's eviction order: just after a self-caching source (which sits at {@code HIGHEST_PRECEDENCE}) + * and well before the engines (at {@code LOWEST_PRECEDENCE}), so the union is fresh before any consumer + * rebuilds from it. Sources that self-cache MUST evict at a higher precedence than this — the authoring + * guide states the convention. + */ + public static final int CATALOG_EVICT_ORDER = mx.quest.runway.event.KernelEventOrder.CATALOG; + + /** + * Forces the next {@link #enumerate} of {@code siteId} to reload — drops the cached listing and bumps the + * eviction epoch (so an in-flight load cannot re-install the stale list). Called by the search engines' + * manual-reindex hook: an operator presses "reindex" precisely for out-of-band changes that fire no event + * (an SFTP-uploaded or hand-edited page file), so the shared catalog cache — which those changes never + * evict — must be refreshed too, or the rebuild would read a listing up to the TTL out of date. + * + * @param siteId the site whose cached enumeration to drop (never {@code null}) + */ + public void evict(String siteId) { + evictionEpoch.merge(siteId, 1L, Long::sum); + cache.remove(siteId); + } + + /** + * As {@link #enumerate} but over the contributed (non-pages) sources only — the variant for + * consumers that only care about plugin content (the visibility triple's claims/conflicts): the pages + * projection is skipped before enumeration, so no per-page file stats are paid for a question + * pages cannot answer. + */ + public List enumerateContributed(SiteView site) { + EndpointContributorRegistry routes = endpoints.getIfAvailable(); + List out = new ArrayList<>(); + for (ContentSource source : registry.sources()) { + if (PagesContentSource.KEY.equals(source.key())) { + continue; + } + List refs = enumerate(source, site); + if (refs == null) { + continue; + } + for (ContentRef ref : refs) { + if (ref != null && admissible(source, ref, site, routes)) { + out.add(new RoutableContent(source.key(), ref)); + } + } + } + return out; + } + + /** + * By-id link targets for source content — the {@code ${urls[':']}} half of the render + * model's URL map (pages keep their bare-slug keys via {@code PageRouting.urlMap}): each non-pages item's + * locale-correct URL for {@code locale} (its URL there when available, else its primary's — the same + * fallback pages use, so an internal link never 404s). The pages projection is skipped ENTIRELY — not even + * enumerated — so a site with no content plugins pays nothing here. + * + * @param locale the locale the linking page is being rendered in + * @return composite id → root-relative URL (never {@code null}) + */ + public Map urlMap(SiteView site, Locale locale) { + Locale siteDefault = site.defaultLocale(); + EndpointContributorRegistry routes = endpoints.getIfAvailable(); + Map urls = new HashMap<>(); + for (ContentSource source : registry.sources()) { + if (PagesContentSource.KEY.equals(source.key())) { + continue; // pages are keyed by bare slug in PageRouting.urlMap — no second enumeration + } + List refs = enumerate(source, site); + if (refs == null) { + continue; + } + for (ContentRef ref : refs) { + if (ref == null || !admissible(source, ref, site, routes)) { + continue; + } + RoutableContent item = new RoutableContent(source.key(), ref); + Locale target = item.hasLocale(locale, siteDefault) ? locale : item.primaryLocale(siteDefault); + urls.put(item.compositeId(), LocaleUrls.urlFor(item, target, siteDefault)); + } + } + return urls; + } + + /** + * The inputs {@link #urlMap} reads for {@code site}: every non-pages source's enumeration, by source key in + * registration order — exactly the lists {@code urlMap} iterates (a throwing source contributes an empty list + * there and here alike). The page validator folds them (each list memoized by identity, so a source that hands out + * its cached list costs nothing per request), so a content item's URL change moves the ETag of every page whose + * {@code ${urls}} could link to it. Unfiltered on purpose: a superset of what the map keeps is a correct fold, and + * re-checking admissibility here would log every inadmissible ref twice per request. + * + * @return source key → that source's enumeration (never {@code null}; empty when there are no content plugins) + */ + public Map> urlMapInputs(SiteView site) { + Map> inputs = new java.util.LinkedHashMap<>(); + for (ContentSource source : registry.sources()) { + if (!PagesContentSource.KEY.equals(source.key())) { + inputs.put(source.key(), enumerate(source, site)); + } + } + return inputs; + } + + /** + * The item's raw indexable material for {@code locale} — the search integration's one entry point: + * capability-gated (a source that never opted into {@code content.indexable-text} is never called) and + * failure-contained (a throwing source indexes as metadata-only, never breaks an index build). Engines + * strip markup themselves; this returns material "as authored". + */ + public String indexableText(SiteView site, RoutableContent item, java.util.Locale locale) { + return registry.byKey(item.sourceKey()) + .filter(source -> source.capabilities().has(ContentSource.CAP_INDEXABLE_TEXT)) + .map(source -> { + String text = registry.guard().call(source, ContributionGuard.Axis.CONTENT_SOURCE, + source.key(), () -> source.indexableText(site, item.ref().id(), locale), () -> ""); + return text == null ? "" : text; + }) + .orElse(""); + } + + /** + * One source's enumeration under the containment policy: a source that throws contributes nothing (logged with its + * stack once per minute, counted against its plugin) and never breaks the listing of the others. A + * {@code null} answer is "nothing" too. + */ + private List enumerate(ContentSource source, SiteView site) { + List refs = registry.guard().call(source, ContributionGuard.Axis.CONTENT_SOURCE, source.key(), + () -> source.enumerate(site), List::of); + return refs == null ? List.of() : refs; + } + + /** The fail-closed listing re-check; a {@code false} means dropped (already WARNed when noteworthy). */ + private boolean admissible(ContentSource source, ContentRef ref, SiteView site, + EndpointContributorRegistry routes) { + if (!ref.published()) { + log.warn("content source '{}' enumerated an UNPUBLISHED ref '{}' (site '{}') — dropped", + source.key(), ref.id(), site.id()); + return false; + } + if (ref.id().indexOf(':') >= 0) { + log.warn("content source '{}' ref id '{}' contains ':' — dropped (the composite : " + + "identity must stay unambiguous)", source.key(), ref.id()); + return false; + } + RoutableContent content = new RoutableContent(source.key(), ref); + for (Locale locale : ContentUrls.availableLocales(content, site)) { + String path = ref.pathFor(locale); + if (!PathSafety.isSafePagePath(path)) { + log.warn("content source '{}' ref '{}' has an unsafe path '{}' — dropped", source.key(), + ref.id(), path); + return false; + } + if (reserved(path, routes)) { + // Not a source bug per se (an operator CAN name a page /login) — but a listing must never + // advertise a URL the reserved surface will serve instead. Info-level: expected occasionally. + log.info("content source '{}' ref '{}' path '{}' collides with the reserved surface — " + + "not listed", source.key(), ref.id(), path); + return false; + } + } + return true; + } + + /** + * Whether the host would route content at {@code path} at all — the same path rules a listing applies to every + * item (a safe page path, not reserved, not an exact endpoint route), with no source consulted. What + * {@code ContentCatalogView.servablePath} answers. + */ + public boolean servablePath(String path) { + return path != null && PathSafety.isSafePagePath(path) && !reserved(path, endpoints.getIfAvailable()); + } + + /** + * Whether {@code path} belongs to the reserved kernel surface ({@link + * mx.quest.runway.web.ReservedPaths#atEnumerationTime the single authority}) or an exact contributor + * route (this catalog owns that registry lookup). + */ + private static boolean reserved(String path, EndpointContributorRegistry routes) { + if (mx.quest.runway.web.ReservedPaths.atEnumerationTime(path)) { + return true; + } + return routes != null && routes.match("GET", path).isPresent(); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/content/ContentCatalogViewImpl.java b/runway-app/src/main/java/mx/quest/runway/content/ContentCatalogViewImpl.java new file mode 100644 index 0000000..8022297 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/content/ContentCatalogViewImpl.java @@ -0,0 +1,108 @@ +package mx.quest.runway.content; + +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import mx.quest.runway.page.Page; +import mx.quest.runway.page.PageStore; +import mx.quest.runway.spi.model.CatalogEntry; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.spi.service.ContentCatalogView; +import mx.quest.runway.spi.service.Sites; +import mx.quest.runway.storage.PathSafety; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * The kernel's {@link ContentCatalogView}: a thin, id-keyed face over {@link ContentCatalog}, which keeps the + * fail-closed re-filter, the per-site cache with its eviction epochs, the per-source failure containment and the + * last-seen URL index. Every method resolves the site here from its id (review m1) — a plugin can never fill + * the shared per-site cache from a stale or hand-built {@link SiteView}. + * + *

Unsafe ids throw {@link IllegalArgumentException} (through {@link Sites#find}); an unknown, well-formed id + * answers empty/{@code ""}/{@code false}. + */ +@Component +public class ContentCatalogViewImpl implements ContentCatalogView { + + private final ObjectProvider catalogProvider; + private final Sites sites; + private final PageStore pages; + + /** + * @param catalog resolved lazily: a plugin content source may itself depend on this view (to check a prefix with + * {@link #servablePath}), while the catalog depends on every source through its registry — an + * eager reference would be a construction cycle + */ + @Autowired + public ContentCatalogViewImpl(ObjectProvider catalog, Sites sites, PageStore pages) { + this.catalogProvider = Objects.requireNonNull(catalog, "catalog"); + this.sites = Objects.requireNonNull(sites, "sites"); + this.pages = Objects.requireNonNull(pages, "pages"); + } + + /** Test form over a ready catalog. */ + public ContentCatalogViewImpl(ContentCatalog catalog, Sites sites, PageStore pages) { + this(new ObjectProvider<>() { + @Override + public ContentCatalog getObject() { + return catalog; + } + }, sites, pages); + } + + private ContentCatalog catalog() { + return catalogProvider.getObject(); + } + + @Override + public List entries(String siteId) { + return sites.find(siteId).map(catalog()::entries).orElse(List.of()); + } + + @Override + public String indexableText(String siteId, CatalogEntry entry, Locale locale) { + Objects.requireNonNull(entry, "entry"); + Objects.requireNonNull(locale, "locale"); + Optional site = sites.find(siteId); + if (site.isEmpty()) { + return ""; + } + // ContentCatalog.indexableText is capability-gated and failure-contained already ("" on a throwing source). + return catalog().indexableText(site.get(), new RoutableContent(entry.sourceKey(), entry.ref()), locale); + } + + @Override + public Optional pageAt(String siteId, String path, Locale locale) { + Objects.requireNonNull(path, "path"); + Objects.requireNonNull(locale, "locale"); + if (sites.find(siteId).isEmpty()) { + return Optional.empty(); + } + // Not PageStore.findByPath: that one THROWS on an ambiguous route (right for serving, where a silent pick + // would shadow a page). This is an advisory question — "is the path taken?" — and two claimants still mean + // "taken"; answer the first by slug, deterministically. + return pages.findAll(siteId).stream() + .filter(Page::published) + .filter(page -> path.equals(page.pathFor(locale))) + .map(Page::slug) + .min(Comparator.naturalOrder()); + } + + @Override + public boolean servablePath(String siteId, String path) { + Objects.requireNonNull(path, "path"); + return sites.find(siteId).isPresent() && catalog().servablePath(path); + } + + @Override + public void refresh(String siteId) { + if (siteId == null || !PathSafety.isSafeId(siteId)) { + throw new IllegalArgumentException("unsafe site id: " + siteId); + } + catalog().evict(siteId); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/content/ContentChangedEvent.java b/runway-app/src/main/java/mx/quest/runway/content/ContentChangedEvent.java new file mode 100644 index 0000000..aa9e1fb --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/content/ContentChangedEvent.java @@ -0,0 +1,45 @@ +package mx.quest.runway.content; + +import java.util.Objects; + +/** + * Published whenever a {@link mx.quest.runway.spi.ContentSource}'s content changes for a site — an entry + * created, edited, deleted, published or unpublished, or the source's whole per-site corpus replaced. It is + * the single freshness trigger for server-side derived state: routing/urlMap caches, the search index, + * and any source-private lookup index all evict on it (publish → listeners evict), mirroring + * {@link mx.quest.runway.page.PageChangedEvent}'s discipline for kernel pages — the write path never pokes + * caches directly. + * + *

It does NOT affect HTTP caching. A render's ETag/{@code Last-Modified} are computed from the + * ref's metadata (notably {@link mx.quest.runway.spi.model.ContentRef#updatedAt()}) — a source whose body + * output changed must bump the ref, or revalidating clients keep getting {@code 304}s; publishing this event + * alone does not refresh them. + * + *

Every source change must reach it. The kernel cannot see a plugin's files change; a plugin source calls + * the SPI's {@link mx.quest.runway.spi.service.ContentChanges#changed}, which publishes this event (a plugin may not + * link this host type — from SPI 1.0.0 one that does is refused). A source that forgets leaves stale + * routing/search/sitemap output until an unrelated eviction happens to run. Kernel-internal: plugins observe changes + * through {@link mx.quest.runway.spi.service.SiteEventListener}, never by listening to this type. + * + *

The event is published regardless of clustering; with clustering OFF it drives purely local eviction. + * When clustering is ON, {@code cluster.ClusterEventRelay} fans it out to peer nodes over the Hazelcast topic + * (envelope kind {@code CONTENT_CHANGED}) so every node's caches evict — the same cross-node invalidation the + * kernel gives site, plugin-config and page events. + * + *

Synchronous. Spring publishes events synchronously by default, so local listeners' evictions have + * run by the time {@code publishEvent} returns. + * + * @param siteId the affected tenancy (never {@code null}) + * @param sourceKey the {@link mx.quest.runway.spi.ContentSource#key()} whose content changed (never + * {@code null}) + * @param id the changed content's {@link mx.quest.runway.spi.model.ContentRef#id()}; {@code null} + * means the source's whole corpus for this site (a wholesale drop — e.g. a prefix + * reconfiguration or a restore) + */ +public record ContentChangedEvent(String siteId, String sourceKey, String id) { + + public ContentChangedEvent { + Objects.requireNonNull(siteId, "siteId"); + Objects.requireNonNull(sourceKey, "sourceKey"); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/content/ContentChangesImpl.java b/runway-app/src/main/java/mx/quest/runway/content/ContentChangesImpl.java new file mode 100644 index 0000000..37f0736 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/content/ContentChangesImpl.java @@ -0,0 +1,66 @@ +package mx.quest.runway.content; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; +import java.util.function.Supplier; +import mx.quest.runway.event.SpiEventBridge; +import mx.quest.runway.spi.ContentSource; +import mx.quest.runway.spi.service.ContentChanges; +import mx.quest.runway.storage.PathSafety; +import org.springframework.context.ApplicationEventPublisher; + +/** + * The kernel's {@link ContentChanges}, bound to one plugin (built by {@code PluginScopedServices} from the injecting + * class's code source). A call publishes the host's {@link ContentChangedEvent}, which is the one path every + * consumer already follows: the kernel listeners evict routing, URL maps and the catalog in their bands, plugins that + * still listen to the host event receive it, the cluster relay fans it out, and the SPI bridge delivers + * {@code onCatalogChanged} (cause {@code CONTENT}) last. Publication is synchronous, so all of that has happened when + * {@link #changed} returns. + * + *

Refusals, before anything is published: an unsafe site id; a source key that is not a {@link ContentSource} this + * plugin contributes (a plugin cannot evict, or make listeners react to, another plugin's content); a call from inside + * a {@code SiteEventListener} callback (a re-entrant change storm). + */ +public final class ContentChangesImpl implements ContentChanges { + + private final String pluginId; + private final Supplier registry; + private final Function, Optional> pluginOf; + private final ApplicationEventPublisher events; + + /** + * @param pluginId the plugin this instance answers for + * @param registry the content sources, resolved at call time (sources may depend on this service) + * @param pluginOf which plugin's own jar a class came from (empty for kernel classes) + * @param events where the host event is published + */ + public ContentChangesImpl(String pluginId, Supplier registry, + Function, Optional> pluginOf, ApplicationEventPublisher events) { + this.pluginId = Objects.requireNonNull(pluginId, "pluginId"); + this.registry = Objects.requireNonNull(registry, "registry"); + this.pluginOf = Objects.requireNonNull(pluginOf, "pluginOf"); + this.events = Objects.requireNonNull(events, "events"); + } + + @Override + public void changed(String siteId, String sourceKey, String id) { + if (siteId == null || !PathSafety.isSafeId(siteId)) { + throw new IllegalArgumentException("unsafe site id: " + siteId); + } + if (SpiEventBridge.inCallback()) { + throw new IllegalStateException("ContentChanges.changed was called from inside a SiteEventListener " + + "callback (plugin '" + pluginId + "'); announce changes from the code that made them, not from " + + "a reaction to a change"); + } + ContentSource source = registry.get().byKey(sourceKey == null ? "" : sourceKey).orElseThrow(() -> + new IllegalArgumentException("no content source '" + sourceKey + "' is registered")); + String owner = pluginOf.apply(source.getClass()).orElse(null); + if (!pluginId.equals(owner)) { + throw new IllegalArgumentException("content source '" + sourceKey + "' is not contributed by plugin '" + + pluginId + "'" + (owner == null ? " (it is a kernel source)" : " (it belongs to '" + owner + + "')")); + } + events.publishEvent(new ContentChangedEvent(siteId, sourceKey, id)); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/content/ContentRouter.java b/runway-app/src/main/java/mx/quest/runway/content/ContentRouter.java new file mode 100644 index 0000000..d0cf73b --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/content/ContentRouter.java @@ -0,0 +1,145 @@ +package mx.quest.runway.content; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import mx.quest.runway.plugin.ContributionGuard; +import mx.quest.runway.spi.ContentSource; +import mx.quest.runway.spi.model.ContentBody; +import mx.quest.runway.spi.model.ContentRef; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.storage.PathSafety; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +/** + * Resolves a request path to a content source's page — the kernel half of virtual-page routing, consulted by + * the page controller only after real pages miss (the structural "real page wins" precedence). The {@link + * PagesContentSource} is skipped here — routing + * already resolved pages against the store directly, so consulting their projection again would be a redundant + * second lookup of the same data. + * + *

Fail-closed sanitization

+ * Every source answer is re-checked before it routes — the kernel backstop for the contracts a source could + * violate: the ref must be published, its matched path must be path-safe and actually equal the + * requested path for the lookup locale (a source cannot answer for a different URL), and its + * {@code bodyTemplate} must live in an allowed namespace ({@code __plugin__//…} or + * {@code __site__//…}) so a source can never point the renderer at another tenant's files. A + * violating answer is dropped with a WARN — omission, never disclosure. + * + *

Failure containment vs. loud collisions

+ * A throwing source is logged and treated as a miss (degrade-don't-crash: a broken plugin must not 500 + * a tenant's whole 404 surface). But two sources claiming the same path is a real configuration + * conflict and stays LOUD: an {@link IllegalStateException} naming both sources and ids (the controller turns + * it into a 500) — byte-consistent with the page store's never-silently-shadow discipline for duplicate page + * paths. Recovery is operator action (the per-tenant plugin settings), not a silent arbitrary winner. + */ +@Component +public class ContentRouter { + + private static final Logger log = LoggerFactory.getLogger(ContentRouter.class); + + /** A resolved virtual page: the owning source and its matched, sanitized ref. */ + public record ContentMatch(ContentSource source, RoutableContent content) { + } + + private final ContentSourceRegistry registry; + + public ContentRouter(ContentSourceRegistry registry) { + this.registry = registry; + } + + /** Whether any source beyond the built-in pages projection is registered (else routing skips the seam). */ + public boolean hasVirtualSources() { + return registry.sources().stream().anyMatch(s -> !PagesContentSource.KEY.equals(s.key())); + } + + /** + * Resolves {@code path} (locale prefix already stripped) for the locale the URL implies, consulting every + * registered source except the pages projection. See the class contract for sanitization, failure + * containment, and the loud virtual-vs-virtual collision. + * + * @param site the site being served + * @param path the request path, leading {@code /}, no locale prefix + * @param lookupLocale the locale the URL implies (prefix locale, else the site default) + * @return the single matching virtual page, or empty + * @throws IllegalStateException when two sources claim the same path (the loud collision) + */ + public Optional resolve(SiteView site, String path, Locale lookupLocale) { + List matches = new ArrayList<>(1); + for (ContentSource source : registry.sources()) { + if (PagesContentSource.KEY.equals(source.key())) { + continue; // real pages were already consulted first, against the store itself + } + // Contained: a source that throws is treated as a miss (logged once per minute, counted against its plugin). + Optional answer = registry.guard().call(source, ContributionGuard.Axis.CONTENT_SOURCE, + source.key(), () -> source.resolve(site, path, lookupLocale), Optional::empty); + if (answer == null || answer.isEmpty()) { + continue; + } + ContentRef ref = answer.get(); + if (sanitize(source, ref, site, path, lookupLocale)) { + matches.add(new ContentMatch(source, new RoutableContent(source.key(), ref))); + } + } + if (matches.size() > 1) { + // Two plugins claiming one URL is a configuration conflict, not a tie to break silently. + throw new IllegalStateException("virtual-path collision on '" + path + "' for site '" + site.id() + + "': " + matches.get(0).source().key() + ":" + matches.get(0).content().ref().id() + + " and " + matches.get(1).source().key() + ":" + matches.get(1).content().ref().id()); + } + return matches.isEmpty() ? Optional.empty() : Optional.of(matches.get(0)); + } + + /** + * The matched item's body payload under the containment policy: empty when the source's {@code body()} throws or + * returns {@code null} (logged once per minute, counted against its plugin), so the caller can render the + * chrome around an empty body and serve it uncacheable. + */ + public Optional body(ContentMatch match, SiteView site, Locale locale) { + ContentSource source = match.source(); + return Optional.ofNullable(registry.guard().callNonNull(source, ContributionGuard.Axis.CONTENT_SOURCE, + source.key(), () -> source.body(site, match.content().ref().id(), locale), () -> null)); + } + + /** The fail-closed re-check of a source's answer; a {@code false} means dropped (already WARNed). */ + private boolean sanitize(ContentSource source, ContentRef ref, SiteView site, String path, + Locale lookupLocale) { + if (!ref.published()) { + log.warn("content source '{}' answered an UNPUBLISHED ref '{}' for '{}' (site '{}') — dropped", + source.key(), ref.id(), path, site.id()); + return false; + } + String matched = ref.pathFor(lookupLocale); + if (!path.equals(matched)) { + log.warn("content source '{}' ref '{}' does not actually serve '{}' in {} (its path is '{}') — dropped", + source.key(), ref.id(), path, lookupLocale.toLanguageTag(), matched); + return false; + } + if (!PathSafety.isSafePagePath(matched)) { + log.warn("content source '{}' ref '{}' has an unsafe path '{}' — dropped", source.key(), ref.id(), + matched); + return false; + } + String template = ref.bodyTemplate(); + boolean allowedNamespace = template.startsWith("__plugin__/") + || template.startsWith("__site__/" + site.id() + "/"); + if (!allowedNamespace) { + log.warn("content source '{}' ref '{}' names a body template outside the allowed namespaces: '{}' " + + "— dropped", source.key(), ref.id(), template); + return false; + } + // The master param becomes a template name inside the tenant's templates/ dir; resolution is + // traversal-confined downstream, but rejecting a suspicious name HERE turns a would-be per-URL 500 + // into a clean drop with a diagnosable log line. + String master = new RoutableContent(source.key(), ref).masterTemplate(); + if (master.contains("..") || master.startsWith("/") || master.contains("\\")) { + log.warn("content source '{}' ref '{}' names a suspicious master template '{}' — dropped", + source.key(), ref.id(), master); + return false; + } + return true; + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/content/ContentSourceRegistry.java b/runway-app/src/main/java/mx/quest/runway/content/ContentSourceRegistry.java new file mode 100644 index 0000000..0eb522d --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/content/ContentSourceRegistry.java @@ -0,0 +1,74 @@ +package mx.quest.runway.content; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import mx.quest.runway.plugin.ContributionGuard; +import mx.quest.runway.spi.ContentSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Collects every {@link ContentSource} bean — core and plugin alike — and indexes them by their stable + * {@link ContentSource#key()}. This is the kernel half of the content-source seam: sources arrive as ordinary beans + * (a plugin contributes one exactly as the + * core does), and every consumer — the content router, the sitemap/llms.txt endpoints, the search indexer — + * iterates this one registry rather than knowing any source individually. + * + *

Key collisions: a duplicate or blank key among kernel sources fails startup; a plugin + * source that collides (with the kernel's {@code pages}, or an earlier plugin in load order) or has a blank key is + * refused and its plugin marked degraded — a source can never silently shadow another's content namespace + * ({@code :} identities, per-tenant {@code sites//plugins//} folders). + * + *

The registration order (Spring's collection order) is preserved and exposed by {@link #sources()}; + * consumers that enumerate all sources iterate in that stable order. Per-request failure containment + * (degrade-don't-crash around a throwing source) is the consumer's job, done through the one containment helper + * the registry exposes ({@link #guard()}). + * + *

Thread-safe and immutable after construction. + */ +@Component +public class ContentSourceRegistry { + + private final Map byKey; + private final ContributionGuard guard; + + /** Unit-test form: every source counts as kernel code, so a collision fails fast. */ + public ContentSourceRegistry(List sources) { + this(sources, ContributionGuard.standalone()); + } + + /** + * @param sources every {@link ContentSource} bean Spring discovered (possibly empty) + * @param guard the plugin-contribution containment policy + * @throws IllegalStateException if a kernel source has a blank key or two kernel sources share one + */ + @Autowired + public ContentSourceRegistry(List sources, ContributionGuard guard) { + this.guard = guard; + // Collections.unmodifiableMap over the guard's LinkedHashMap (not Map.copyOf, which does not keep order) — + // the registration order is part of the contract sources()/consumers iterate in. + this.byKey = Collections.unmodifiableMap(guard.index("ContentSource", sources, ContentSource::key)); + } + + /** The containment policy every consumer wraps its calls into a source with. */ + public ContributionGuard guard() { + return guard; + } + + /** Whether no sources are registered (consumers then skip the seam entirely — today's behaviour). */ + public boolean isEmpty() { + return byKey.isEmpty(); + } + + /** All registered sources, in registration order. */ + public List sources() { + return List.copyOf(byKey.values()); + } + + /** The source with the given key, if registered. */ + public Optional byKey(String key) { + return Optional.ofNullable(byKey.get(key)); + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/content/PagesContentSource.java b/runway-app/src/main/java/mx/quest/runway/content/PagesContentSource.java new file mode 100644 index 0000000..c57cfa3 --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/content/PagesContentSource.java @@ -0,0 +1,372 @@ +package mx.quest.runway.content; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import mx.quest.runway.i18n.SiteAwareMessageSource; +import mx.quest.runway.page.Page; +import mx.quest.runway.page.PageChangedEvent; +import mx.quest.runway.page.PageStore; +import mx.quest.runway.plugin.SitePluginConfigChangedEvent; +import mx.quest.runway.site.SiteChangedEvent; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.ContentSource; +import mx.quest.runway.spi.model.ContentBody; +import mx.quest.runway.spi.model.ContentRef; +import mx.quest.runway.spi.model.SiteView; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.web.DraftRenderer; +import mx.quest.runway.web.SiteTemplateResolver; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +/** + * Kernel pages exposed as a {@link ContentSource} — the no-two-class-system rule realized: every + * enumeration consumer (the sitemap, llms.txt, URL maps, search) sees pages and plugin content through the + * same registry and the same {@link ContentRef} noun, so a plugin's content is a first-class peer of + * the built-ins by construction. Pages also gain what the noun carries and they never had: an + * {@link ContentRef#updatedAt() updatedAt} (from the page files' mtimes) that becomes the sitemap's + * {@code }. + * + *

Routing does NOT consult this source. The controller resolves real pages against + * {@link PageStore} first — the structural "real page wins" precedence — so {@code ContentRouter} skips + * {@link #KEY} to avoid a redundant second lookup of the same data. This source exists for the + * enumeration consumers. + * + *

{@link #body} is empty: a page's body renders through its own leaf template (the {@code bodyTemplate} + * this source declares), never through a source body payload. Search reads the page's content slot (the + * {@code id="content"} element) via {@link #indexableText} instead (the capability-gated search integration) — + * taken from the page as rendered in the requested locale, so text the site's bundles supply through + * decoupled logic is searchable in every language the site speaks. + */ +@Component +public class PagesContentSource implements ContentSource { + + /** This source's stable key — also the marker {@code ContentRouter} skips for routing. */ + public static final String KEY = "pages"; + + private static final String TEMPLATES = "templates"; + + /** The page contract's content slot: the one region of a page file that is the page's own. */ + static final String CONTENT_SLOT_ID = "content"; + + private static final Logger log = LoggerFactory.getLogger(PagesContentSource.class); + + /** A page or master file name ({@code about}, {@code _master}): no separator, no traversal. */ + private static final java.util.regex.Pattern TEMPLATE_NAME = + java.util.regex.Pattern.compile("[A-Za-z0-9_][A-Za-z0-9._-]*"); + + /** What a visitor cannot read as prose: code, inert markup, no-script fallbacks, and forms with all they hold. */ + private static final String NOT_PROSE = "script, style, template, noscript, form, button, input, select, textarea"; + + private final PageStore pages; + private final StorageLayout layout; + private final SiteStore sites; + /** Lazy: the renderer reaches the content catalog, which holds this source. */ + private final ObjectProvider renderer; + /** Lazy, like {@link #renderer}: the bundles whose fingerprint keys the cache. */ + private final ObjectProvider messages; + /** {@code site/page/locale} keys already warned about, so a page that cannot render logs once, not per query. */ + private final Set warned = ConcurrentHashMap.newKeySet(); + /** Rendered slot texts by {@code site|page|locale}; see {@link #indexableText}. */ + private final Map cache = new ConcurrentHashMap<>(); + + /** The longest a cached text is served without a render, whatever its fingerprint says. */ + static final long MAX_AGE_MILLIS = 10 * 60 * 1000L; + /** Entries held before the cache is emptied (a crude bound; one entry per page and language). */ + static final int MAX_CACHED = 50_000; + + /** One cached slot text, the fingerprint it was rendered under, and when. */ + private record Cached(String fingerprint, String text, long atMillis) { + } + + /** Template-file text only (no rendering) — for tests of the enumeration and the slot extraction. */ + public PagesContentSource(PageStore pages, StorageLayout layout) { + this(pages, layout, null, null, null); + } + + @Autowired + public PagesContentSource(PageStore pages, StorageLayout layout, SiteStore sites, + ObjectProvider renderer, ObjectProvider messages) { + this.pages = pages; + this.layout = layout; + this.sites = sites; + this.renderer = renderer; + this.messages = messages; + } + + @Override + public String key() { + return KEY; + } + + @Override + public List enumerate(SiteView site) { + List refs = new ArrayList<>(); + for (Page page : pages.findAll(site.id())) { + if (page.published()) { + refs.add(toRef(site.id(), page)); + } + } + return refs; + } + + @Override + public ContentBody body(SiteView site, String id, Locale locale) { + return ContentBody.empty(); // a page renders through its own leaf template, not a body payload + } + + @Override + public mx.quest.runway.spi.model.Capabilities capabilities() { + return mx.quest.runway.spi.model.Capabilities.of(CAP_INDEXABLE_TEXT); + } + + /** + * The page's own content from its {@code .html} — search's indexable material (engines strip the + * markup). Only the content slot is returned (see {@link #contentSlot}): the inner HTML of the + * element with {@code id="content"}, the page contract's {@code

} and the one region a + * page owns. The rest of the file is the designer's offline copy of the shared chrome (header, navigation, + * language switcher, footer), which the render replaces with the master's live seams; indexing it put the + * same navigation words into every page and into every result snippet. + * + *

Since 1.0.0-rc6 the slot is taken from the page as rendered in {@code locale}, so the strings the + * render takes from the site's message bundles (decoupled {@code th:text="#{key}"}) are indexed in that + * language; a page that is unknown, unpublished or fails to render gives its file's slot instead. + * + *

Cached. A rendered text is kept per page and locale under a fingerprint of everything a render of + * the slot reads that can change without an event: the page's files, its master's files and the site's + * bundles ({@link SiteAwareMessageSource#bundleState}, which also re-reads bundles edited on disk before the + * render). An engine's freshness backstop — search-lucene rebuilds every 30 s under query load — therefore + * costs one {@code stat} per file instead of a render. Page, content, site and plugin-settings events drop the + * site's entries; {@link #MAX_AGE_MILLIS} bounds what no fingerprint sees (a content widget's own data). + */ + @Override + public String indexableText(SiteView site, String id, Locale locale) { + if (!mx.quest.runway.storage.PathSafety.isSafeId(id)) { + return ""; // defense in depth — never let an unsafe id reach a filesystem resolve (mirrors PageStore) + } + Optional page = pages.find(site.id(), id).filter(Page::published); + if (page.isPresent() && renderer != null && sites != null) { + String key = site.id() + "|" + id + "|" + locale.toLanguageTag(); + String fingerprint = fingerprint(site.id(), page.get()); + Cached hit = cache.get(key); + long now = System.currentTimeMillis(); + if (hit != null && hit.fingerprint().equals(fingerprint) && now - hit.atMillis() < MAX_AGE_MILLIS) { + return hit.text(); + } + String rendered = rendered(site.id(), page.get(), locale); + String text = rendered != null ? contentSlot(rendered) : fileText(site.id(), id); + if (cache.size() >= MAX_CACHED) { + cache.clear(); // a crude bound: the next rebuild renders again, nothing is wrong + } + cache.put(key, new Cached(fingerprint, text, now)); + return text; + } + return fileText(site.id(), id); + } + + /** The page file's own slot text (no render): unknown or unpublished pages, and the fallback of a failed render. */ + private String fileText(String siteId, String id) { + Path file = layout.siteDir(siteId).resolve(TEMPLATES).resolve(id + ".html"); + if (!Files.isRegularFile(file)) { + return ""; + } + try { + return contentSlot(Files.readString(file, java.nio.charset.StandardCharsets.UTF_8)); + } catch (IOException ex) { + return ""; // an unreadable body indexes as title/description only — degrade, don't fail + } + } + + /** + * The published page rendered in {@code locale}, or {@code null} when it cannot be (no renderer, the page is + * unknown or unpublished, or the render failed). A failed render falls back to the template file's text — + * the literal text is still searchable — and is logged once per page and locale. + */ + private String rendered(String siteId, Page page, Locale locale) { + DraftRenderer draft = renderer.getIfAvailable(); + Optional site = sites.find(siteId); + if (draft == null || site.isEmpty()) { + return null; + } + String id = page.slug(); + try { + return draft.renderForIndex(site.get(), page, locale); + } catch (RuntimeException ex) { + if (warned.add(siteId + "/" + id + "/" + locale.toLanguageTag())) { + log.warn("search: page '{}' of site '{}' could not be rendered in {}; indexing its template text " + + "instead (strings from the site's bundles are missing from the index)", + id, siteId, locale.toLanguageTag(), ex); + } + return null; + } + } + + /** + * What a cached text is valid for: the mtimes of the page's and its master's files, and the site's bundle + * fingerprint (taken after the bundles are re-checked, so a render that follows reads the same bundles). + */ + private String fingerprint(String siteId, Page page) { + StringBuilder b = new StringBuilder(96); + Path templates = layout.siteDir(siteId).resolve(TEMPLATES); + for (String name : new String[] {page.slug(), page.template()}) { + if (name == null || !TEMPLATE_NAME.matcher(name).matches() || name.contains("..")) { + continue; + } + for (String suffix : new String[] {".meta.yml", ".html", ".th.xml"}) { + try { + Path file = templates.resolve(name + suffix); + b.append(Files.isRegularFile(file) ? Files.getLastModifiedTime(file).toMillis() : 0L).append(','); + } catch (IOException ex) { + b.append("?,"); + } + } + } + SiteAwareMessageSource bundles = messages == null ? null : messages.getIfAvailable(); + if (bundles != null) { + try { + b.append(bundles.bundleState(siteId).fingerprint()); + } catch (RuntimeException ex) { + b.append("?"); // no fingerprint: an unchanged "?" still lets MAX_AGE_MILLIS refresh the entry + } + } + return b.toString(); + } + + /** + * Drops every cached text of a site: its pages, content, settings or the site itself changed. At + * {@code DERIVED}: after the stores and bundles it reads have evicted, before plugins hear of the change and + * rebuild their indexes. + */ + private void evict(String siteId) { + String prefix = siteId + "|"; + cache.keySet().removeIf(k -> k.startsWith(prefix)); + } + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.DERIVED) + public void onPageChanged(PageChangedEvent event) { + evict(event.siteId()); + } + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.DERIVED) + public void onContentChanged(ContentChangedEvent event) { + evict(event.siteId()); + } + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.DERIVED) + public void onSiteChanged(SiteChangedEvent event) { + evict(event.siteId()); + } + + @EventListener + @org.springframework.core.annotation.Order(mx.quest.runway.event.KernelEventOrder.DERIVED) + public void onSitePluginConfigChanged(SitePluginConfigChangedEvent event) { + if (event.siteId() != null) { + evict(event.siteId()); + } + } + + /** + * The indexable part of a page (rendered, or its template file): the inner HTML of the element with + * {@code id="content"}; without one (a standalone page that skipped the slot), the {@code }'s inner + * HTML; and when the body is empty too, the text as it is. Code ({@code } would run {@code evil()} under the stamp + * (proven in Chrome 155). + * + * The cost, fail-closed: an SVG script that names its file only through {@code href}/{@code xlink:href} is no + * longer stamped (so {@code 'strict-dynamic'} blocks it), nor is a {@code } is ONE element that ends at the second close tag — reading it as + * two made the first {@code } look like the end, after which a {@code } and {@code } are complete, empty comments, + * and a comment closes at the first {@code -->} or {@code --!>}. (Reading {@code } as an open comment made the + * scanner skip — and so leave unstamped — a same-origin script the browser runs.) + */ + private static int commentEnd(String html, int from, int limit) { + if (startsWith(html, ">", from, limit)) { + return from + 1; + } + if (startsWith(html, "->", from, limit)) { + return from + 2; + } + for (int k = from; k + 2 < limit; k++) { + if (html.charAt(k) != '-' || html.charAt(k + 1) != '-') { + continue; + } + if (html.charAt(k + 2) == '>') { + return k + 3; + } + if (html.charAt(k + 2) == '!' && k + 3 < limit && html.charAt(k + 3) == '>') { + return k + 4; + } + } + return -1; + } + + /** ASCII case-insensitive search ({@code needle} is lower-case) in {@code [from, limit)}, as end tags match. */ + private static int indexOfIgnoreCase(String haystack, String needle, int from, int limit) { + int last = limit - needle.length(); + outer: + for (int i = from; i <= last; i++) { + for (int k = 0; k < needle.length(); k++) { + char c = haystack.charAt(i + k); + if (c >= 'A' && c <= 'Z') { + c = (char) (c + 32); + } + if (c != needle.charAt(k)) { + continue outer; + } + } + return i; + } + return -1; + } + + private static boolean isAsciiLetter(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + } + + private static boolean isAsciiAlphanumeric(char c) { + return isAsciiLetter(c) || (c >= '0' && c <= '9'); + } + + /** ASCII-only lower-casing, as the HTML tokenizer does for tag and attribute names. */ + static String asciiLower(String s) { + StringBuilder out = null; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c >= 'A' && c <= 'Z') { + if (out == null) { + out = new StringBuilder(s); + } + out.setCharAt(i, (char) (c + 32)); + } + } + return out == null ? s : out.toString(); + } + + private static boolean isTagNameEnd(char c) { + return isSpace(c) || c == '/' || c == '>'; + } + + static boolean isSpace(char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; + } +} diff --git a/runway-app/src/main/java/mx/quest/runway/head/ScriptPreloadStripper.java b/runway-app/src/main/java/mx/quest/runway/head/ScriptPreloadStripper.java new file mode 100644 index 0000000..bcffcbd --- /dev/null +++ b/runway-app/src/main/java/mx/quest/runway/head/ScriptPreloadStripper.java @@ -0,0 +1,246 @@ +package mx.quest.runway.head; + +import java.net.URI; +import java.util.Set; +import mx.quest.runway.web.CspScriptAllowlist; + +/** + * Removes, from a public page served under the ETag-derived nonce and {@code 'strict-dynamic'}, every {@code } + * that would make the visitor's browser fetch a script-class resource from a host the host-allowlist policy did not + * allow — the preload half of "never loosen what the allowlist blocked" ({@link ScriptNonceStamper} is the script + * half). It runs at the response edge, only where the stamp runs (a public nonce is in force); when the nonce is + * withdrawn the page gets the host-allowlist policy, whose {@code 'self'} + hosts already block these fetches, and + * nothing is removed. + * + *

Why

+ * Under {@code 'strict-dynamic'} a browser ignores {@code 'self'} and the host list for any request that is not + * "parser-inserted". A module preload is fetched as not-parser-inserted, so injected markup could make every + * visitor's browser contact any host — a beacon channel that beta13's {@code script-src 'self'} closed. Nothing runs + * (a preload never executes), but the visit, the visitor's address and the page it came from leak. The edge removes + * such a link, judged by the same rule as a {@code "; + } + + /** + * Wraps {@code cardBody} in a styled, self-hosted-chrome page (Tabler + runway-chrome, no CDN). Every + * {@code /__assets} reference carries the {@link AssetVersion} token, so an upgraded build's chrome is never + * shadowed by the previous one's cached copy. + */ + private String document(String title, String cardBody) { + return "\n" + + "" + + "" + title + "" + + "" + + "" + + "" + + "" + + "" + + "
" + + "
" + + "\"Runway\"Runway
" + + "
" + cardBody + "
" + + "
"; + } + + /** + * The {@code nonce=""} attribute for a {@code + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/fragment-editor.th.xml b/runway-app/src/main/resources/templates/operator/admin/fragment-editor.th.xml new file mode 100644 index 0000000..cd26c0e --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/fragment-editor.th.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/fragments.html b/runway-app/src/main/resources/templates/operator/admin/fragments.html new file mode 100644 index 0000000..a9c9f2e --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/fragments.html @@ -0,0 +1,98 @@ + + +Fragments + +
+ + + + +
+
+ + + + + + + + + + + + + + + + + + +
NameLogicSizeActions
No fragments yet.
_headlogicsize + Edit +
+ + +
+
+ + +
+
+
+
+ +
+

Error pages

+
+

What a visitor sees for an error, in the site's own look.

+
+ + + + + + + + + + + + + + + + +
StatusFileActions
None: every error gets the platform's plain page.
404 Not Found_404 + Edit +
+ + +
+
+
+
+ +
+ +
+
+
Starts from the site's master.
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/fragments.th.xml b/runway-app/src/main/resources/templates/operator/admin/fragments.th.xml new file mode 100644 index 0000000..12ca25f --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/fragments.th.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/home.html b/runway-app/src/main/resources/templates/operator/admin/home.html new file mode 100644 index 0000000..ad03a3b --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/home.html @@ -0,0 +1,35 @@ + + +site admin home + +
+ + +
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/home.th.xml b/runway-app/src/main/resources/templates/operator/admin/home.th.xml new file mode 100644 index 0000000..de00924 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/home.th.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/icons.html b/runway-app/src/main/resources/templates/operator/admin/icons.html new file mode 100644 index 0000000..a4cb050 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/icons.html @@ -0,0 +1,62 @@ + + +Icons + +
+ + +
+

Generate from an SVG

+
+

Upload one master SVG; the platform generates every raster + icon (apple-touch, 192, 512 and favicon.ico) and keeps the SVG as the SVG favicon.

+
+ +
+ + +
+
+
+
+ +
+

Site icons

+
+

Upload each icon a browser or device may ask for. Missing + slots simply return 404; the icons a page references are injected into its head automatically.

+
+
+ + — +
+
+
/icon
+ status +
+
+
+ + + +
+
+ + +
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/icons.th.xml b/runway-app/src/main/resources/templates/operator/admin/icons.th.xml new file mode 100644 index 0000000..2ff4e7f --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/icons.th.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/insights.html b/runway-app/src/main/resources/templates/operator/admin/insights.html new file mode 100644 index 0000000..7392df7 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/insights.html @@ -0,0 +1,96 @@ + + +Site insights + +
+ + + + + + +
+
+
+
Page views
+
0
+
+
+
+
+
Not-found requests (404)
+
0
+
+
+
+

window

+ +
+
+
+

Most-visited pages

+
+ + + + + + + + + + + + + + + + +
PathViewsLast seen
No page views.
/0-
+
+
+
+
+
+

Top 404 paths

+

hint

+
+ + + + + + + + + + + + + + + + +
PathRequestsLast seen
No 404s.
/0-
+
+
+
+
+ +

note

+

retention

+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/insights.th.xml b/runway-app/src/main/resources/templates/operator/admin/insights.th.xml new file mode 100644 index 0000000..c2880f5 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/insights.th.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/logs.html b/runway-app/src/main/resources/templates/operator/admin/logs.html new file mode 100644 index 0000000..d95c04c --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/logs.html @@ -0,0 +1,51 @@ + + +Logs + +
+ + +
+
+
+

Access log

+
+
access
+
+
+
+
+
+

Log settings

+
+
+ + +
+ + + Capped by the platform. +
Above the platform's maximum.
+
+ +
+

dropped

+
+
+
+
+ +
audit journal
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/logs.th.xml b/runway-app/src/main/resources/templates/operator/admin/logs.th.xml new file mode 100644 index 0000000..6fd2bd9 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/logs.th.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/maintenance.html b/runway-app/src/main/resources/templates/operator/admin/maintenance.html new file mode 100644 index 0000000..22c1672 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/maintenance.html @@ -0,0 +1,48 @@ + + +Maintenance + +
+ + + + +
+ + +
+

Maintenance mode

+
+ + +
+ + + Shown to visitors on the maintenance page. Leave + blank for a default notice. Plain text only. +
+
+
+ + + + +
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/maintenance.th.xml b/runway-app/src/main/resources/templates/operator/admin/maintenance.th.xml new file mode 100644 index 0000000..c05fdf8 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/maintenance.th.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/messages.html b/runway-app/src/main/resources/templates/operator/admin/messages.html new file mode 100644 index 0000000..79442a6 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/messages.html @@ -0,0 +1,121 @@ + + +Messages + +
+ + + + +
+ + +
+
+

Messages

+ +
+
+ + +
+
+
+
+ + + + + + + + + + + + + + + + + + +
KeepKeyValue
+ + + + +
+ en + +
+
No messages yet.
+
+ + +
+ +
+

Add a message

+
+
+ + +
+
+ + +
+
+
+ +
+ + +
+
+
+ + +
+ + + + +
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/messages.th.xml b/runway-app/src/main/resources/templates/operator/admin/messages.th.xml new file mode 100644 index 0000000..20bf616 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/messages.th.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/page-editor.html b/runway-app/src/main/resources/templates/operator/admin/page-editor.html new file mode 100644 index 0000000..6606b1a --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/page-editor.html @@ -0,0 +1,389 @@ + + +page editor + +
+ + + + +
+ You are editing a pending + revision. The live page is unchanged until it is approved. + Submitted by someone. +
+
+ This site requires review: saving + keeps your changes as a pending revision, and the live page stays as it is until they are approved. +
+
+ Waiting for review. +
+
+
Sent back for changes
+
by someone
+
note
+
+ +
+ + + +
+ +
+
+
+

Page HTML

+
+ + + + + + +
+
+
+
+ + +
+ +
Tab indents in the code editors. To move on, press Esc and then Tab.
+
+
+ +
+
+
+

Decoupled logic

+
Optional
+
+
+ + + + +
+
+
+
+ +
+
+
+ +
+

Metadata

+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
Author help
+
+
+ + +
Published on help
+
+
+ + +
Canonical override
+
+
+ + +
Cache-Control override
+
+
+ +
nosnippet help
+
+
+ +
gone help
+
+
+ +
noindex help
+
+ + +
+ +
+ + +
+
+
en
+ + + +
+
+ + +
Parameters help
+
+ +
+
+ +
+
+ + Overrides the site value +
+
+
+
+ +
+
+ +
+
+
+ +
+
Inherited from the site
+ + + + + + + +
keyvalue
+
+
+
+ + +
+

Page quality

+
+
No issues.
+
    + +
  • + warning + message + +
  • +
+
+
+ +
+
+ + +
+
+
+

Preview

+
+ + + + Unsaved changes + + +
+
+
+ + + + +
+
+
+
+
+ + +
+ + + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ Open in the review queue +
+ + +
+ + + Refresh the chrome from the master. +
+ + +
+ + +
+ + +
+ Renames the page's files. +
+ + +
+ + + Removes the page and its files. +
+
+ + +
+ + + + + +
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/page-editor.th.xml b/runway-app/src/main/resources/templates/operator/admin/page-editor.th.xml new file mode 100644 index 0000000..e750e03 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/page-editor.th.xml @@ -0,0 +1,205 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/page-new.html b/runway-app/src/main/resources/templates/operator/admin/page-new.html new file mode 100644 index 0000000..b25a35d --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/page-new.html @@ -0,0 +1,50 @@ + + +new page + +
+ +
+
+
+
+
+ +
+ + +
The page id and file name.
+
+
+ + +
+
+ + +
+
+ + +
+ +
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/page-new.th.xml b/runway-app/src/main/resources/templates/operator/admin/page-new.th.xml new file mode 100644 index 0000000..67ceb7b --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/page-new.th.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/pages.html b/runway-app/src/main/resources/templates/operator/admin/pages.html new file mode 100644 index 0000000..e56a449 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/pages.html @@ -0,0 +1,73 @@ + + +pages + +
+ + +
+

URL conflicts

+
+ + + + + + + + + + + + + + + +
PathLanguageWhat happens
/pathenexplanation
+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + +
SlugPathLocalesStatusActions
No pages.
slug——status + Edit +
+ + +
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/pages.th.xml b/runway-app/src/main/resources/templates/operator/admin/pages.th.xml new file mode 100644 index 0000000..f7abd48 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/pages.th.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/review-item.html b/runway-app/src/main/resources/templates/operator/admin/review-item.html new file mode 100644 index 0000000..78d3867 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/review-item.html @@ -0,0 +1,146 @@ + + +Review + +
+ + +
+
+ kind + Submitted by someone +
+
+ +
+
+ +
+

Page quality

+
+ +
No issues found.
+
    +
  • + warning + message +
  • +
+
+
+ + +
+

Decision

+
+
+ + + +
+
+ + + + +
+
+
+ + +
+

Settings changed

+
+ + + + + + + + + + + + + + + +
FieldLiveProposed
fieldbeforeafter
+
+
No settings changed.
+
+
+ +
+ +
+
+
+

Live

+
+ +
+
+
+
+
+

Proposed

+
+ +
+
+
+
+ + +
+

Page HTML changes

+
No changes.
+
Too large to compare line by line; use the + side-by-side preview.
+
+ + + + +
+line
+
+
+
+

Decoupled logic changes

+
No changes.
+
Too large to compare line by line.
+
+ + + + +
+line
+
+
+
+
+ +
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/review-item.th.xml b/runway-app/src/main/resources/templates/operator/admin/review-item.th.xml new file mode 100644 index 0000000..a4018f8 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/review-item.th.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/review.html b/runway-app/src/main/resources/templates/operator/admin/review.html new file mode 100644 index 0000000..4c4a129 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/review.html @@ -0,0 +1,49 @@ + + +Review queue + +
+ + + +

Pages waiting for an approver.

+
This site does not require review.
+ +
+
+ + + + + + + + + + + + + + + + + + + + + +
PagePathKindSubmitted bySubmittedActions
slug/pathkinduserwhenReview
+
+
Nothing is waiting for review.
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/review.th.xml b/runway-app/src/main/resources/templates/operator/admin/review.th.xml new file mode 100644 index 0000000..566c689 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/review.th.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/seo.html b/runway-app/src/main/resources/templates/operator/admin/seo.html new file mode 100644 index 0000000..908abc1 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/seo.html @@ -0,0 +1,99 @@ + + +SEO + +
+ + + + +
+ + +
+

Social sharing

+
+
+ + + Absolute URL of the image shown when a page is shared. +
+
+ + + + e.g. website or article. +
+
+ + + e.g. summary or summary_large_image. +
+
+ + + The site's @handle. +
+
+
+ +
+

Search-engine verification

+
+
+ + + The content value from Google Search Console's meta-tag method. +
+
+ + + The content value from Bing Webmaster Tools' meta-tag method. +
+
+
+ +
+

Uploaded documents

+
+ + Sends X-Robots-Tag: noindex with every file under + /static/doc/. A PDF has no page markup, so this header is the only way to ask a search + engine not to list it. It applies to all of them together, and only to engines that honour it — it is + not access control: the files stay publicly downloadable to anyone with the link. +
+
+ +
+

Extra <head> markup

+
+ + Injected verbatim into every page's <head>. For + trusted markup only (link tags, structured-data scripts) — it is not escaped. +
+
+ + +
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/seo.th.xml b/runway-app/src/main/resources/templates/operator/admin/seo.th.xml new file mode 100644 index 0000000..c83091c --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/seo.th.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/site-config.html b/runway-app/src/main/resources/templates/operator/admin/site-config.html new file mode 100644 index 0000000..91d9d68 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/site-config.html @@ -0,0 +1,172 @@ + + +Site config + +
+ + + + +
+ + +
+

General

+
+
+ + + The site's public display name. +
+
+
Addresses
+
example.com
+
Links built on
+
https://example.com +
Set by the platform operator.
+
+
+
+ +
+

Languages

+
+
Tick every language this site offers, and mark one + as the default. The default is always offered.
+
+ +
+
+ +
+
+ +
+
+
+
+ + + A BCP 47 language tag, e.g. fr or pt-BR. +
+
+
+ +
+

Contact

+
+
+ + +
+
+ + +
+
+ + + Shown by templates that surface a contact block. + The kernel does not send mail — a contact form is a plugin feature. +
+
+
+ +
+

Template parameters

+
+
Static key/value pairs exposed to every page as + ${params.key}. A page's own parameters override these.
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+
+ + +
+

Editorial workflow

+
+
How strictly page publishing is governed on this + site.
+ + + +
Only a user who may approve pages can change + this.
+
+
+ + +
+ +
+ +
+

Embedded content

+
+

Third-party hosts your pages may embed.

+

The platform operator has not approved any.

+ + +
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/site-config.th.xml b/runway-app/src/main/resources/templates/operator/admin/site-config.th.xml new file mode 100644 index 0000000..fed9f78 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/site-config.th.xml @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/static-files.html b/runway-app/src/main/resources/templates/operator/admin/static-files.html new file mode 100644 index 0000000..2f8a947 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/static-files.html @@ -0,0 +1,104 @@ + + +Static files + +
+ + +
+
Stylesheets, scripts, images, fonts and media your pages use, served at /static/…
+
+ +

Storage used.

+
+ This site is over its storage limit. +
+ + + +
+ This folder holds the site's documents. + Documents +
+ +
+
+ + + + + + + + + + + + + + + + + + +
NameSizeModifiedActions
This folder is empty.
+ folder + file.css + sizedate + + Documents +
+ + + +
+
+
+
+ +
+
+
+

Upload files

+
+
+ + + + + + Allowed types and size. +
+
+
+
+
+
+

New folder

+
+
+ + +
+ + +
+
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/static-files.th.xml b/runway-app/src/main/resources/templates/operator/admin/static-files.th.xml new file mode 100644 index 0000000..88c5086 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/static-files.th.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/users.html b/runway-app/src/main/resources/templates/operator/admin/users.html new file mode 100644 index 0000000..87969c3 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/users.html @@ -0,0 +1,135 @@ + + +site users + +
+ + +
+
+
+

Create a user

+
+
+ +
+
+
+
+
+
+
+
+
+
+
+ + Optional. Custom roles layered on top of the access tier.
+
+
+
+
+
+
+
+

Reset a password

+
+
+ +
+
+
+
+
+
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + + + +
UsernameDisplay nameEmailRolesActions
No users.
user suspended——— + — + + +
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/users.th.xml b/runway-app/src/main/resources/templates/operator/admin/users.th.xml new file mode 100644 index 0000000..ceb2258 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/users.th.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/web-manifest.html b/runway-app/src/main/resources/templates/operator/admin/web-manifest.html new file mode 100644 index 0000000..409c512 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/web-manifest.html @@ -0,0 +1,65 @@ + + +Web app manifest + +
+ + +
+
+

These fields populate the site's manifest.webmanifest, + so it can be installed as a progressive web app. Icons come from the Icons screen.

+
+ +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/web-manifest.th.xml b/runway-app/src/main/resources/templates/operator/admin/web-manifest.th.xml new file mode 100644 index 0000000..0b6ea33 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/web-manifest.th.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/admin/widget-instances.html b/runway-app/src/main/resources/templates/operator/admin/widget-instances.html new file mode 100644 index 0000000..2fe2ea0 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/widget-instances.html @@ -0,0 +1,64 @@ + + +content widgets + +
+ + +

+ Each widget placed in this site's templates is listed below; configure how each placement behaves. +

+ +
+
No widgets are placed in this site.
+
+ A designer adds one with a data-widget="type/instance" anchor in a template. +
+
+ +
+
+
+

+ type + / instance +

+
+ Placed in: home +
+
+
+
+
This widget offers no per-instance settings.
+ +
+ +
+ + + + + + help + hint +
+
+ +
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/admin/widget-instances.th.xml b/runway-app/src/main/resources/templates/operator/admin/widget-instances.th.xml new file mode 100644 index 0000000..0f6b188 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/admin/widget-instances.th.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/about.html b/runway-app/src/main/resources/templates/operator/app/about.html new file mode 100644 index 0000000..e268a03 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/about.html @@ -0,0 +1,73 @@ + + +about runway + +
+ + +
+
+
+

Effective configuration

+
+

Set in application.yml — a restart is needed to change these.

+ + + + + + + +
settingvalue
+
+
+
+ +
+
+

Runtime environment

+
+

Describes the node serving this page.

+ + + + + + + +
namevalue
+
+
+
+
+ +
+
+
+

Bundled components

+
+

Notable third-party libraries in this build.

+
+
+ name + value +
+
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/about.th.xml b/runway-app/src/main/resources/templates/operator/app/about.th.xml new file mode 100644 index 0000000..ca8fe8c --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/about.th.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/backups.html b/runway-app/src/main/resources/templates/operator/app/backups.html new file mode 100644 index 0000000..dab6b1e --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/backups.html @@ -0,0 +1,89 @@ + + +Backups + +
+ + +
+

Create a site from a backup

+
+

Upload a backup to create a new, independent site (a clone + or a migration). The new id, name and hosts are yours to choose; the content comes from the backup.

+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+ +
+

Per-site backups

+
+

Off-site copies: not configured.

+
No sites yet.
+
+
+ site + Download + Transfer copy +
+ + +
+
+ + + +
+
+
    +
  • + name + size +
    + + +
    +
    + + +
    +
  • +
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/backups.th.xml b/runway-app/src/main/resources/templates/operator/app/backups.th.xml new file mode 100644 index 0000000..339c478 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/backups.th.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/bandwidth.html b/runway-app/src/main/resources/templates/operator/app/bandwidth.html new file mode 100644 index 0000000..8984743 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/bandwidth.html @@ -0,0 +1,58 @@ + + +Bandwidth + +
+ + +
+
+
+
Sent (30 days)
+
0
+
+
+
+
+
Received (30 days)
+
0
+
+
+
+ +
+

By site (30 days)

+
+ + + + + + + + + + + + + + + + +
SiteSentReceived
No traffic recorded yet.
sitesentrecv
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/bandwidth.th.xml b/runway-app/src/main/resources/templates/operator/app/bandwidth.th.xml new file mode 100644 index 0000000..10d02a2 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/bandwidth.th.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/embed-hosts.html b/runway-app/src/main/resources/templates/operator/app/embed-hosts.html new file mode 100644 index 0000000..d660e28 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/embed-hosts.html @@ -0,0 +1,73 @@ + + +Embed hosts + +
+ + +
Hosts sites may add to their own pages' policy.
+ +
+
+ + + + + + + + + + + + + + + + + + + + +
NameSourceMay joinSites using itActions
No hosts approved.
YouTube youtubehttps://www.youtube-nocookie.comframe-src0 +
+ + + +
+
+
+
+ +
+

Approve a host

+
+
+ +
+
+
+
+
+
+
+ May join + +
+
Saving with an existing id replaces it.
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/embed-hosts.th.xml b/runway-app/src/main/resources/templates/operator/app/embed-hosts.th.xml new file mode 100644 index 0000000..97585a8 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/embed-hosts.th.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/home.html b/runway-app/src/main/resources/templates/operator/app/home.html new file mode 100644 index 0000000..e3712bf --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/home.html @@ -0,0 +1,49 @@ + + +operator home + +
+ + +
+
+

Use the menu above to open the screens you have access to.

+
+
+ +
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/home.th.xml b/runway-app/src/main/resources/templates/operator/app/home.th.xml new file mode 100644 index 0000000..ce52cce --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/home.th.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/log-levels.html b/runway-app/src/main/resources/templates/operator/app/log-levels.html new file mode 100644 index 0000000..4ff232f --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/log-levels.html @@ -0,0 +1,67 @@ + + +Log levels + +
+ + +
How much each part of the server writes to the server log.
+ +
+
+ + + + + + + + + + + + + + + +
LoggerNowSet to
mx.quest.runway
what
INFO +
+ + + + +
+
Set on the server.
+
+
+
+ +
+

Another logger

+
+
+ +
+
+
+
+
+
A Java package or class name.
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/log-levels.th.xml b/runway-app/src/main/resources/templates/operator/app/log-levels.th.xml new file mode 100644 index 0000000..b4dcb91 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/log-levels.th.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/logs.html b/runway-app/src/main/resources/templates/operator/app/logs.html new file mode 100644 index 0000000..6db3ab6 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/logs.html @@ -0,0 +1,29 @@ + + +Activity log + +
+ + +

+ Sign-ins, password recovery, sign-outs and every change operators make (users, roles and permissions, + sites, settings, plugins, backups), newest first.

+
journal
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/logs.th.xml b/runway-app/src/main/resources/templates/operator/app/logs.th.xml new file mode 100644 index 0000000..7351c55 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/logs.th.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/masters.html b/runway-app/src/main/resources/templates/operator/app/masters.html new file mode 100644 index 0000000..5dcc91c --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/masters.html @@ -0,0 +1,135 @@ + + +site masters + +
+ + +
+
+
+

Create a tenant superadmin

+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

Assign / unassign a tenancy

+
+ +
+
+
+
+
+ +
+
+
+
+
+
+

Reset a password

+
+ +
+
+
+
+
+
+
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + +
UsernameDisplay nameTenanciesActions
No tenant superadmins.
user suspended—— + + +
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/masters.th.xml b/runway-app/src/main/resources/templates/operator/app/masters.th.xml new file mode 100644 index 0000000..97dc10f --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/masters.th.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/plugins.html b/runway-app/src/main/resources/templates/operator/app/plugins.html new file mode 100644 index 0000000..ada62cd --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/plugins.html @@ -0,0 +1,122 @@ + + +plugins + +
+ + + + + +
+ +
+
+

Install a plugin

+
+
+ +
+ + +
+
+ +
+
Applies on the next restart.
+
+
+
+
+ + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
IDNameVersionStatusRequired byActions
No plugins installed.
idname1.0.0 + status + Uses host internals + Failures: 0 +
blocked because …
+
+ Details +
    +
  • last error
  • +
  • refused
  • +
  • warning
  • +
+
+
— + Settings +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ Essential +
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/plugins.th.xml b/runway-app/src/main/resources/templates/operator/app/plugins.th.xml new file mode 100644 index 0000000..feb847d --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/plugins.th.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/settings.html b/runway-app/src/main/resources/templates/operator/app/settings.html new file mode 100644 index 0000000..01e6a7f --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/settings.html @@ -0,0 +1,172 @@ + + +platform settings + +
+ + +
+
+
+
+
+ + +
+ + + + The site that answers requests whose host is not bound to another site. +
+ +
+ + + + Argon2id memory-cost profile for new passwords. Applies after the next restart. +
+ +
+ + + + A name for this node, shown on the About page. Blank uses the server host name. +
+ +
+
Response compression
+ + Compress text responses before sending. Applies immediately. + + + + Set on the server. + + Brotli's native library did not load on this server; it falls back to gzip. +
+ +
+
Platform mail (SMTP)
+ + Used for password recovery and other application messages. Not used for a site's + own contact-form mail. +
+
+ + +
+
+ + +
+
+
+ + +
+ +
+
+ + +
+
+ + + + A password is stored; leave blank to keep it. +
+
+ + +
+ + +
+
+
+ +
+
+
Send test email
+ + Verify the platform mail account. Save your changes above first. +
+ +
+ + +
+
+ +
+
+
+
+ +
+
+
Template cache
+ + Console edits refresh templates automatically. Clear the cache only after changing template + files outside the console. Affects this node only. +
+ + +
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/settings.th.xml b/runway-app/src/main/resources/templates/operator/app/settings.th.xml new file mode 100644 index 0000000..ea1b55c --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/settings.th.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/site-template-edit.html b/runway-app/src/main/resources/templates/operator/app/site-template-edit.html new file mode 100644 index 0000000..bd16c5c --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/site-template-edit.html @@ -0,0 +1,51 @@ + + +edit site template + +
+ + +
+
+
+
+

+ Saving changes only what future sites from this template are created with.

+
+ + + + + +
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/site-template-edit.th.xml b/runway-app/src/main/resources/templates/operator/app/site-template-edit.th.xml new file mode 100644 index 0000000..f77d70e --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/site-template-edit.th.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/site-template-files.html b/runway-app/src/main/resources/templates/operator/app/site-template-files.html new file mode 100644 index 0000000..0becc90 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/site-template-files.html @@ -0,0 +1,82 @@ + + +template files + +
+ + +
+
+
+

Name and description

+
+
+ +
+
+
+
+
Shown in the template list and when creating a site. The id stays the same.
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + +
FileWhat it isStatusActions
_master.htmldescriptionInherits default + + Edit +
+ + + +
+
+
+ +
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/site-template-files.th.xml b/runway-app/src/main/resources/templates/operator/app/site-template-files.th.xml new file mode 100644 index 0000000..78492d7 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/site-template-files.th.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/site-templates.html b/runway-app/src/main/resources/templates/operator/app/site-templates.html new file mode 100644 index 0000000..401606a --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/site-templates.html @@ -0,0 +1,130 @@ + + +site templates + +
+ + +
+
+
+
+

+ A catalog of starter presentations a new site can be born from. When you create a site you + pick one. Editing a template affects only sites created afterward — existing sites keep + their own copy.

+
+
+ +
+
+ + + + + + + + + + + + + + + + + +
TemplateIdDescriptionActions
+ Default + built-in + default— + + Edit files + + Export +
+ + +
+
+
+
+ +
+
+
+

New template

+
+
+ +
+ + + Letters, digits, dot, underscore, hyphen. +
+
+ + +
+
+ + +
+
+ + + The new template starts as a copy of this one. +
+ +
+
+
+
+ +
+
+

Import template

+
+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + + A .zip exported from another template. +
+ +
+
+
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/site-templates.th.xml b/runway-app/src/main/resources/templates/operator/app/site-templates.th.xml new file mode 100644 index 0000000..1b3e34d --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/site-templates.th.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/sites.html b/runway-app/src/main/resources/templates/operator/app/sites.html new file mode 100644 index 0000000..a73e04d --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/sites.html @@ -0,0 +1,188 @@ + + +sites + +
+ + +
+
+
+

Create a site

+
+
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + +
IDNameHostsSuperadminsStatusActions
No sites.
iddefaultname—
base
—status
cap
storage
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + + + +
+
+
+
+ +
+
+

Install a demo site

+
+

Bundled example sites you can install as independent tenants — each gets its own host and superadmin.

+
All bundled demos are installed.
+
+
+ + +
+
Demo
+
id
+
+
+
+
+
+
+
+
+ + +
+
+
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/sites.th.xml b/runway-app/src/main/resources/templates/operator/app/sites.th.xml new file mode 100644 index 0000000..f76c89f --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/sites.th.xml @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/app/users.html b/runway-app/src/main/resources/templates/operator/app/users.html new file mode 100644 index 0000000..4866817 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/users.html @@ -0,0 +1,135 @@ + + +app users + +
+ + +
+
+
+

Create a user

+
+
+ +
+
+
+
+
+
+
+
+
+
+
+ + Optional. Custom roles layered on top of the access tier.
+
+
+
+
+
+
+
+

Reset a password

+
+
+ +
+
+
+
+
+
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + + +
UsernameDisplay nameEmailRolesActions
user superadmin + suspended——— + + +
+ + +
+
+ + +
+
+ + +
+ protected +
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/app/users.th.xml b/runway-app/src/main/resources/templates/operator/app/users.th.xml new file mode 100644 index 0000000..dd164fd --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/app/users.th.xml @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/audit-journal.html b/runway-app/src/main/resources/templates/operator/audit-journal.html new file mode 100644 index 0000000..f21cff0 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/audit-journal.html @@ -0,0 +1,72 @@ + + +Audit journal + + +
+
+

Audit journal

+ +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + Reset +
+
+

Bounds.

+ +
+
+ + + + + + + + + + + + + + + + + + +
TimeActorActionDetail
Nothing recorded.
timeactorlabel
key
detail
+
+ +
+ + diff --git a/runway-app/src/main/resources/templates/operator/audit-journal.th.xml b/runway-app/src/main/resources/templates/operator/audit-journal.th.xml new file mode 100644 index 0000000..4f9e673 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/audit-journal.th.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/fragments/admin-topbar.html b/runway-app/src/main/resources/templates/operator/fragments/admin-topbar.html new file mode 100644 index 0000000..5f518ab --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/fragments/admin-topbar.html @@ -0,0 +1,101 @@ + + +admin topbar + + + + diff --git a/runway-app/src/main/resources/templates/operator/fragments/admin-topbar.th.xml b/runway-app/src/main/resources/templates/operator/fragments/admin-topbar.th.xml new file mode 100644 index 0000000..a6841cc --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/fragments/admin-topbar.th.xml @@ -0,0 +1,113 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/fragments/app-topbar.html b/runway-app/src/main/resources/templates/operator/fragments/app-topbar.html new file mode 100644 index 0000000..06ccfef --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/fragments/app-topbar.html @@ -0,0 +1,95 @@ + + +app topbar + + + + diff --git a/runway-app/src/main/resources/templates/operator/fragments/app-topbar.th.xml b/runway-app/src/main/resources/templates/operator/fragments/app-topbar.th.xml new file mode 100644 index 0000000..058f382 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/fragments/app-topbar.th.xml @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/login-app.html b/runway-app/src/main/resources/templates/operator/login-app.html new file mode 100644 index 0000000..dc2dce1 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/login-app.html @@ -0,0 +1,110 @@ + + + + + + + Sign in + + + + + + +
+
+
+ + Runway + +
+
+
+

Operator sign in

+ + + + + + + +
+ + + +
+ + +
+
+ + +
+ + + +
+ + +
+ +
+ +
+
+
+ +
+ + language +
+
+
+ + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/login-app.th.xml b/runway-app/src/main/resources/templates/operator/login-app.th.xml new file mode 100644 index 0000000..f2c8bb0 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/login-app.th.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/login-tenant.html b/runway-app/src/main/resources/templates/operator/login-tenant.html new file mode 100644 index 0000000..6f4b745 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/login-tenant.html @@ -0,0 +1,105 @@ + + + + + + + Sign in + + + + + + +
+
+
+ + Site + +
+
+
+

Site sign in

+ + + + + + +
+ + + +
+ + +
+
+ + +
+ + + +
+ + +
+ +
+ +
+
+
+ +
+ + language +
+
+
+ + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/login-tenant.th.xml b/runway-app/src/main/resources/templates/operator/login-tenant.th.xml new file mode 100644 index 0000000..69e5bc0 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/login-tenant.th.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/op-layout.html b/runway-app/src/main/resources/templates/operator/op-layout.html new file mode 100644 index 0000000..5e79fc9 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/op-layout.html @@ -0,0 +1,68 @@ + + + + + + + Runway + + + + + + + + + + +Skip to main content +
+
+
+
+
+
+ + + + + + +
+
+
+
+
+ +
+
+
+
Runway
+
+
+
+
+ + + + +
+ + diff --git a/runway-app/src/main/resources/templates/operator/op-layout.th.xml b/runway-app/src/main/resources/templates/operator/op-layout.th.xml new file mode 100644 index 0000000..b6cb966 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/op-layout.th.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/permissions.html b/runway-app/src/main/resources/templates/operator/permissions.html new file mode 100644 index 0000000..155cdc9 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/permissions.html @@ -0,0 +1,174 @@ + + +permissions + +
+ + +
+ +
+
+

Users

+
+ + + + + + + + + + + + + + + + +
UserRolesDirect grants
No users.
name master——
+
+
+
+ + +
+
+

Roles

+
+ + + + + + + + + + + + + + + +
RoleInheritsGranted permissions
role custom——
+
+
+
+ + +
+
+

Manage roles

+
+
+

Create role

+
+ +
+ +
+
+ +
+
+
+

hint

+
+
+

Delete role

+
+ +
+
+
+
+
+

Role hierarchy

+
+ +
+
inherits
+
+
+
+
+ +
+
inherits
+
+
+
+
+
+
+
+ + +
+
+

Assign

+
+
+

User roles

+
+ +
+
+
+
+
+ +
+
+
+
+
+
+

User direct grants

+
+ +
+
+
+
+
+ +
+
+
+
+
+
+

Role permission deltas

+
+ +
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/permissions.th.xml b/runway-app/src/main/resources/templates/operator/permissions.th.xml new file mode 100644 index 0000000..bda0a5a --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/permissions.th.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/plugin-settings.html b/runway-app/src/main/resources/templates/operator/plugin-settings.html new file mode 100644 index 0000000..240e546 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/plugin-settings.html @@ -0,0 +1,77 @@ + + +plugin settings + +
+ + + + + +
+
Some sites set their own value.
+
+ +
+ +
+
This plugin declares no settings.
+ + + + + +
+
+
+

Section

+
Section introduction.
+ Learn more +
+
+ +
+ +
+ +
+ Advanced +
+
+
+
+
+ +
+ + +
+ +
+ +
+
+ + diff --git a/runway-app/src/main/resources/templates/operator/plugin-settings.th.xml b/runway-app/src/main/resources/templates/operator/plugin-settings.th.xml new file mode 100644 index 0000000..93847bd --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/plugin-settings.th.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/recovery-forgot.html b/runway-app/src/main/resources/templates/operator/recovery-forgot.html new file mode 100644 index 0000000..7ac351c --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/recovery-forgot.html @@ -0,0 +1,81 @@ + + + + + + + Reset your password + + + + + + +
+
+
+ + Runway + +
+
+
+
+

Reset your password

+

+ Enter the email address for your account and we'll send you a link to reset your password.

+ +
+ + + +
+ + +
+ +
+ + +
+
+
+

Check your email

+

+ If an account with that email exists, we've sent it a link to reset the password. The link + expires in one hour.

+
+ +
+
+ +
+ + language +
+
+
+ + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/recovery-forgot.th.xml b/runway-app/src/main/resources/templates/operator/recovery-forgot.th.xml new file mode 100644 index 0000000..7629d3e --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/recovery-forgot.th.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/recovery-reset.html b/runway-app/src/main/resources/templates/operator/recovery-reset.html new file mode 100644 index 0000000..53b3dba --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/recovery-reset.html @@ -0,0 +1,67 @@ + + + + + + + Choose a new password + + + + + + +
+
+
+ + Runway + +
+
+
+
+

Choose a new password

+

+ Setting a new password for account.

+ +
+ + +
+ + +
+
+ + +
+ +
+
+
+

Link expired or invalid

+

+ This password-reset link is invalid or has expired. Request a new one from the sign-in page.

+
+ +
+
+ +
+ + language +
+
+
+ + + + diff --git a/runway-app/src/main/resources/templates/operator/recovery-reset.th.xml b/runway-app/src/main/resources/templates/operator/recovery-reset.th.xml new file mode 100644 index 0000000..3bafaca --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/recovery-reset.th.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/restarting.html b/runway-app/src/main/resources/templates/operator/restarting.html new file mode 100644 index 0000000..a34a781 --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/restarting.html @@ -0,0 +1,26 @@ + + + + + + + + + Restarting + + + + +
+
+
+

Restarting Runway…

+

This page reloads automatically once the console is back.

+
+
+ + + + diff --git a/runway-app/src/main/resources/templates/operator/restarting.th.xml b/runway-app/src/main/resources/templates/operator/restarting.th.xml new file mode 100644 index 0000000..ee5ebdd --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/restarting.th.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/runway-app/src/main/resources/templates/operator/setting-row.html b/runway-app/src/main/resources/templates/operator/setting-row.html new file mode 100644 index 0000000..161083a --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/setting-row.html @@ -0,0 +1,41 @@ + + +setting row + + +
+ + + + + + + + +
+ Set on the server. + The console holds no value of its own. +
+ + +
+ The platform operator has turned this off. +
+ What this setting does. + + One per line. + Allowed: 1..10. + Default: x. + Learn more + +
+ + diff --git a/runway-app/src/main/resources/templates/operator/setting-row.th.xml b/runway-app/src/main/resources/templates/operator/setting-row.th.xml new file mode 100644 index 0000000..bd0ac6f --- /dev/null +++ b/runway-app/src/main/resources/templates/operator/setting-row.th.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/runway-app/src/test/java/mx/quest/runway/ConfigurationMetadataTest.java b/runway-app/src/test/java/mx/quest/runway/ConfigurationMetadataTest.java new file mode 100644 index 0000000..d2a5e60 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/ConfigurationMetadataTest.java @@ -0,0 +1,83 @@ +package mx.quest.runway; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import mx.quest.runway.storage.Yaml; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The {@code runway.*} configuration namespace is documented in the generated Spring configuration + * metadata (IDE completion, and the source of the key list in CONFIGURATION-AND-DATA-STABILITY.md). Guards two + * regressions: the configuration processor silently not running (it once did not — JDK 23+ dropped implicit + * annotation processing), and a key added to {@code application.yml} or read via {@code @Value} without metadata. + */ +class ConfigurationMetadataTest { + + private static Set documentedKeys() throws IOException { + try (InputStream in = ConfigurationMetadataTest.class.getResourceAsStream( + "/META-INF/spring-configuration-metadata.json")) { + assertNotNull(in, "spring-configuration-metadata.json is generated (is the processor on the " + + "maven-compiler-plugin annotationProcessorPaths?)"); + JsonNode root = JsonMapper.builder().build().readTree(in); + Set names = new TreeSet<>(); + root.get("properties").forEach(p -> names.add(p.get("name").asString())); + return names; + } + } + + /** The keys read only via {@code @Value} or straight from the Environment, which no properties class covers. */ + @ParameterizedTest + @ValueSource(strings = { + "runway.backups.schedule.cron", + "runway.demo.first-run.id", + "runway.demo.first-run.host", + "runway.demo.first-run.master-username", + "runway.demo.first-run.master-password", + "runway.endpoints.max-body-bytes", + "runway.plugins.max-entry-bytes", + "runway.security.app-master-id", + "runway.node.name", + "runway.plugins.root", + "runway.storage.external", + }) + void everyValueAndEnvironmentKeyIsDocumented(String key) throws IOException { + assertTrue(documentedKeys().contains(key), key + " is missing from the configuration metadata"); + } + + /** Every runway.* default in the shipped application.yml names a documented key (a typo there binds nothing). */ + @Test + void everyKeyInTheShippedApplicationYmlIsDocumented() throws IOException { + Map yml; + try (InputStream in = ConfigurationMetadataTest.class.getResourceAsStream("/application.yml")) { + yml = Yaml.read(in, Map.class); + } + List leaves = new ArrayList<>(); + collect(yml.get("runway"), "runway", leaves); + Set documented = documentedKeys(); + List undocumented = leaves.stream() + .filter(k -> !documented.contains(k) && documented.stream().noneMatch(d -> k.startsWith(d + "."))) + .toList(); + assertTrue(leaves.size() > 50, "the walk found the runway tree: " + leaves.size()); + assertTrue(undocumented.isEmpty(), "application.yml keys with no metadata: " + undocumented); + } + + private static void collect(Object node, String prefix, List out) { + if (node instanceof Map map && !map.isEmpty()) { + map.forEach((k, v) -> collect(v, prefix + "." + k, out)); + } else { + out.add(prefix); + } + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/AuthorizationAdminServiceTest.java b/runway-app/src/test/java/mx/quest/runway/authz/AuthorizationAdminServiceTest.java new file mode 100644 index 0000000..f704ac6 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/AuthorizationAdminServiceTest.java @@ -0,0 +1,364 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwaySecurityProperties; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.security.access.AccessDeniedException; + +/** The bounded-grant rules: no self-escalation, reserved-key limits, grantable-only, master-target. */ +class AuthorizationAdminServiceTest { + + private record Wiring(AuthorizationAdminService admin, AuthorizationService authz, RoleStore roles, + mx.quest.runway.security.SiteUserStore siteUsers, GrantStore grants) {} + + private static Wiring wire(Path tmp) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + return wire(layout, new GrantStore(layout, new YamlStore())); + } + + /** A grants store whose next site write fails, as a full disk or a permission problem would make it. */ + private static final class FailingGrantStore extends GrantStore { + boolean failNextWrite; + + FailingGrantStore(StorageLayout layout) { + super(layout, new YamlStore()); + } + + @Override + public void saveSiteGrants(String siteId, GrantFile grants) { + failIfAsked(); + super.saveSiteGrants(siteId, grants); + } + + /** The console's changes go through the atomic update: fail it as a full disk fails its write. */ + @Override + public GrantFile updateSiteGrants(String siteId, java.util.function.UnaryOperator change) { + failIfAsked(); + return super.updateSiteGrants(siteId, change); + } + + private void failIfAsked() { + if (failNextWrite) { + failNextWrite = false; + throw new java.io.UncheckedIOException(new java.io.IOException("No space left on device")); + } + } + } + + private static Wiring wire(StorageLayout layout, GrantStore grants) { + YamlStore yaml = new YamlStore(); + RoleStore roles = new RoleStore(layout, yaml); + PermissionCatalog catalog = new PermissionCatalog(); + RunwaySecurityProperties security = new RunwaySecurityProperties(); + security.setAppMasterId("app-master"); + AuthorizationService authz = new AuthorizationService(roles, grants, catalog, security); + mx.quest.runway.security.UserStore users = new mx.quest.runway.security.UserStore(yaml); + mx.quest.runway.security.AppUserStore appUsers = + new mx.quest.runway.security.AppUserStore(layout, users, security); + mx.quest.runway.security.SiteUserStore siteUsers = + new mx.quest.runway.security.SiteUserStore(layout, users); + return new Wiring(new AuthorizationAdminService(roles, grants, catalog, authz, security, appUsers, siteUsers), + authz, roles, siteUsers, grants); + } + + private static RunwayUserDetails user(String id, Realm realm, boolean master, List sites, String... roles) { + return new RunwayUserDetails(new User(id, id, "$h", "", "", true, master, realm, Set.of(roles), sites)); + } + + private static RunwayUserDetails tenantWildcard() { + return user("ad", Realm.TENANT, false, List.of(), Roles.ADMIN); + } + + @Test + void anAdminCanDefineARoleAndAssignItEndToEnd(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().saveRole(tenantWildcard(), "acme", new Role("editor", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of())); + w.admin().assignRole(tenantWildcard(), "acme", "sub", "editor"); + + RunwayUserDetails sub = user("sub", Realm.TENANT, false, List.of()); + assertTrue(w.authz().mayAccess(sub, Permissions.EDIT_PAGES, "acme"), "assigned role grants the permission"); + } + + @Test + void revokingAGrantFileRoleWorksButAnAccessTierIsRejectedNotSilentlyNoOped(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().saveRole(tenantWildcard(), "acme", new Role("blogger", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of())); + // A sub-user created with OPERATOR in its OWN record (the access tier), plus a matrix-assigned custom role. + w.siteUsers().save("acme", new User("sub", "sub", "$h", "", "", true, false, Realm.TENANT, + Set.of(Roles.OPERATOR), List.of())); + w.admin().assignRole(tenantWildcard(), "acme", "sub", "blogger"); // grant-file layer + + // Revoking the grant-file custom role works. + w.admin().revokeRole(tenantWildcard(), "acme", "sub", "blogger"); + RunwayUserDetails after = user("sub", Realm.TENANT, false, List.of(), Roles.OPERATOR); + assertFalse(w.authz().mayAccess(after, Permissions.EDIT_PAGES, "acme"), "the custom role was revoked"); + + // Revoking the access tier (held in the user's own record, not the grant file) is REJECTED with a clear + // message — the old behaviour silently no-oped because the grant-file delete found nothing to remove. + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> w.admin().revokeRole(tenantWildcard(), "acme", "sub", Roles.OPERATOR)); + assertTrue(ex.getMessage().contains("access tier"), "explains why, was: " + ex.getMessage()); + } + + @Test + void effectiveRolePermissionKeysGivesTheWildcardEverythingAndAConcreteRoleItsOwn(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().saveRole(tenantWildcard(), "acme", new Role("editor", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of())); + + Set wildcard = w.authz().effectiveRolePermissionKeys(Realm.TENANT, "acme", Roles.ADMIN); + assertTrue(wildcard.contains(Permissions.EDIT_PAGES.key()) && wildcard.contains(Permissions.MANAGE_USERS.key()), + "the wildcard tier effectively holds every grantable permission (not an empty row)"); + + Set operator = w.authz().effectiveRolePermissionKeys(Realm.TENANT, "acme", Roles.OPERATOR); + assertTrue(operator.isEmpty(), "the seed OPERATOR role starts blank — no core or plugin permissions"); + + Set editor = w.authz().effectiveRolePermissionKeys(Realm.TENANT, "acme", "editor"); + assertEquals(Set.of(Permissions.EDIT_PAGES.key()), editor, "a custom role holds exactly its stored permission"); + } + + @Test + void aNonAdminCannotManageRoles(@TempDir Path tmp) { + Wiring w = wire(tmp); + RunwayUserDetails operator = user("op", Realm.TENANT, false, List.of(), Roles.OPERATOR); + assertThrows(AccessDeniedException.class, () -> w.admin().saveRole(operator, "acme", + new Role("x", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of()))); + } + + @Test + void noSelfEscalation(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().saveRole(tenantWildcard(), "acme", new Role("editor", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of())); + w.admin().saveRole(tenantWildcard(), "acme", new Role("boss", Realm.TENANT, Set.of("MANAGE_USERS"), Set.of())); + + // An "editor"-holder may grant "editor" (they hold it) but not "boss" (they do not). + RunwayUserDetails editorHolder = user("e", Realm.TENANT, false, List.of(), "editor"); + w.admin().assignRole(editorHolder, "acme", "t", "editor"); // ok + assertThrows(AccessDeniedException.class, () -> w.admin().assignRole(editorHolder, "acme", "t", "boss")); + // …and may grant a permission they hold, but not one they do not. + w.admin().grantPermission(editorHolder, "acme", "t", Permissions.EDIT_PAGES); // ok + assertThrows(AccessDeniedException.class, + () -> w.admin().grantPermission(editorHolder, "acme", "t", Permissions.MANAGE_USERS)); + } + + @Test + void theWildcardKeyIsGrantableOnlyByAdministrators(@TempDir Path tmp) { + Wiring w = wire(tmp); + RunwayUserDetails operator = user("op", Realm.TENANT, false, List.of(), Roles.OPERATOR); + assertThrows(AccessDeniedException.class, () -> w.admin().assignRole(operator, "acme", "t", Roles.ADMIN)); + w.admin().assignRole(tenantWildcard(), "acme", "t", Roles.ADMIN); // a wildcard may grant the wildcard key + } + + @Test + void theMasterKeyIsNeverGrantable(@TempDir Path tmp) { + Wiring w = wire(tmp); + // Even a tenant master cannot hand out the master key. + RunwayUserDetails master = user("boss", Realm.TENANT, true, List.of("acme"), Roles.SUPERADMIN); + assertThrows(AccessDeniedException.class, () -> w.admin().assignRole(master, "acme", "t", Roles.SUPERADMIN)); + } + + @Test + void privilegedPermissionsAreNeverGrantableAndRolesRejectThem(@TempDir Path tmp) { + Wiring w = wire(tmp); + RunwayUserDetails appAdmin = user("ad", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_ADMIN); + // master/wildcard-only permission can't be granted, even by a wildcard. + assertThrows(AccessDeniedException.class, + () -> w.admin().grantPermission(appAdmin, null, "t", Permissions.MANAGE_TENANCIES)); + // …nor placed into a custom role. + assertThrows(IllegalArgumentException.class, () -> w.admin().saveRole(appAdmin, null, + new Role("superops", Realm.APPLICATION, Set.of("MANAGE_TENANCIES"), Set.of()))); + } + + @Test + void reservedRoleNamesAndMasterTargetsAreRejected(@TempDir Path tmp) { + Wiring w = wire(tmp); + RunwayUserDetails appAdmin = user("ad", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_ADMIN); + assertThrows(IllegalArgumentException.class, () -> w.admin().saveRole(appAdmin, null, + new Role(Roles.SYSTEM_ADMIN, Realm.APPLICATION, Set.of(), Set.of()))); + // The application master's authorization cannot be reassigned. + assertThrows(AccessDeniedException.class, + () -> w.admin().grantPermission(appAdmin, null, "app-master", Permissions.VIEW_AUDIT)); + } + + // --- create / delete / DAG hierarchy ----------------------------------------- + + @Test + void createRolePersistsANewRole(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "editor", Set.of("EDIT_PAGES"), Set.of()); + assertTrue(w.roles().siteRoles("acme").hasRole("editor"), "the new role is in the graph"); + assertTrue(w.roles().siteRoles("acme").effectivePermissionKeys("editor").contains("EDIT_PAGES")); + } + + @Test + void createRoleRejectsADuplicateName(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "editor", Set.of(), Set.of()); + assertThrows(IllegalArgumentException.class, + () -> w.admin().createRole(tenantWildcard(), "acme", "editor", Set.of(), Set.of())); + } + + @Test + void createRoleRejectsAReservedOrPredefinedName(@TempDir Path tmp) { + Wiring w = wire(tmp); + assertThrows(IllegalArgumentException.class, + () -> w.admin().createRole(tenantWildcard(), "acme", Roles.ADMIN, Set.of(), Set.of())); + // A seeded predefined role name (OPERATOR) is also taken. + assertThrows(IllegalArgumentException.class, + () -> w.admin().createRole(tenantWildcard(), "acme", Roles.OPERATOR, Set.of(), Set.of())); + } + + @Test + void createRoleRejectsAMalformedName(@TempDir Path tmp) { + Wiring w = wire(tmp); + assertThrows(IllegalArgumentException.class, + () -> w.admin().createRole(tenantWildcard(), "acme", "bad name/../x", Set.of(), Set.of())); + assertThrows(IllegalArgumentException.class, + () -> w.admin().createRole(tenantWildcard(), "acme", " ", Set.of(), Set.of())); + } + + @Test + void deleteRoleRemovesACustomRole(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "editor", Set.of(), Set.of()); + w.admin().deleteRole(tenantWildcard(), "acme", "editor"); + assertTrue(!w.roles().siteRoles("acme").hasRole("editor"), "the role is gone"); + } + + @Test + void deletingARoleTakesItsPermissionsAwayFromItsHolders(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "editor", Set.of("EDIT_PAGES"), Set.of()); + w.admin().grantToRole(tenantWildcard(), "acme", "editor", Permissions.MANAGE_DOCUMENTS); + w.admin().assignRole(tenantWildcard(), "acme", "sub", "editor"); + RunwayUserDetails sub = user("sub", Realm.TENANT, false, List.of()); + assertTrue(w.authz().mayAccess(sub, Permissions.EDIT_PAGES, "acme")); + assertTrue(w.authz().mayAccess(sub, Permissions.MANAGE_DOCUMENTS, "acme")); + + w.admin().deleteRole(tenantWildcard(), "acme", "editor"); + + assertFalse(w.authz().mayAccess(sub, Permissions.EDIT_PAGES, "acme"), "the stored permission went with it"); + assertFalse(w.authz().mayAccess(sub, Permissions.MANAGE_DOCUMENTS, "acme"), + "the permission granted to the role from the console went with it too"); + assertTrue(w.grants().siteGrants("acme").rolesOf("sub").isEmpty(), "no holder keeps the deleted name"); + w.admin().createRole(tenantWildcard(), "acme", "editor", Set.of(), Set.of()); + assertTrue(w.grants().siteGrants("acme").roleGrantsOf("editor").isEmpty(), + "a role created later under the same name starts clean"); + } + + @Test + void deleteRoleRejectsAReservedRole(@TempDir Path tmp) { + Wiring w = wire(tmp); + assertThrows(IllegalArgumentException.class, + () -> w.admin().deleteRole(tenantWildcard(), "acme", Roles.ADMIN)); + } + + @Test + void deleteRoleRejectsARoleStillInherited(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "base", Set.of("EDIT_PAGES"), Set.of()); + w.admin().createRole(tenantWildcard(), "acme", "boss", Set.of(), Set.of("base")); + w.admin().assignRole(tenantWildcard(), "acme", "sub", "base"); + // Deleting "base" would leave "boss" with a dangling inherit edge — the store rejects it. + assertThrows(IllegalStateException.class, + () -> w.admin().deleteRole(tenantWildcard(), "acme", "base")); + assertEquals(Set.of("base"), w.grants().siteGrants("acme").rolesOf("sub"), + "a refused delete leaves the role's holders as they were"); + } + + @Test + void aDeleteThatFailsHalfwayNeverLeavesTheRolesGrantsLive(@TempDir Path tmp) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + FailingGrantStore failing = new FailingGrantStore(layout); + Wiring w = wire(layout, failing); + w.admin().createRole(tenantWildcard(), "acme", "editor", Set.of("EDIT_PAGES"), Set.of()); + w.admin().grantToRole(tenantWildcard(), "acme", "editor", Permissions.MANAGE_DOCUMENTS); + w.admin().assignRole(tenantWildcard(), "acme", "sub", "editor"); + RunwayUserDetails sub = user("sub", Realm.TENANT, false, List.of()); + + failing.failNextWrite = true; + assertThrows(java.io.UncheckedIOException.class, + () -> w.admin().deleteRole(tenantWildcard(), "acme", "editor")); + // The grants write failed first, so nothing changed: the role is still defined and can be deleted again. + // (The other order removed the role and then failed, leaving the console grant live on its holder, with + // no role left to delete.) + assertTrue(w.roles().siteRoleList("acme").stream().anyMatch(role -> role.name().equals("editor")), + "the role is still defined"); + assertTrue(w.authz().mayAccess(sub, Permissions.MANAGE_DOCUMENTS, "acme"), "the state before the delete"); + + w.admin().deleteRole(tenantWildcard(), "acme", "editor"); + assertFalse(w.authz().mayAccess(sub, Permissions.MANAGE_DOCUMENTS, "acme")); + assertFalse(w.authz().mayAccess(sub, Permissions.EDIT_PAGES, "acme")); + assertFalse(w.roles().siteRoles("acme").hasRole("editor")); + } + + @Test + void addInheritEdgeComposesPermissionsDownward(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "base", Set.of("EDIT_PAGES"), Set.of()); + w.admin().createRole(tenantWildcard(), "acme", "boss", Set.of("MANAGE_USERS"), Set.of()); + w.admin().addRoleInherit(tenantWildcard(), "acme", "boss", "base"); + Set effective = w.roles().siteRoles("acme").effectivePermissionKeys("boss"); + assertTrue(effective.contains("MANAGE_USERS") && effective.contains("EDIT_PAGES"), + "boss inherits base's permissions plus its own"); + } + + @Test + void addInheritEdgeRejectsACycle(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "a", Set.of(), Set.of()); + w.admin().createRole(tenantWildcard(), "acme", "b", Set.of(), Set.of("a")); // b → a + // a → b would close the loop; the cycle-checked graph rejects it, and the store is left untouched. + assertThrows(IllegalStateException.class, () -> w.admin().addRoleInherit(tenantWildcard(), "acme", "a", "b")); + assertTrue(w.roles().siteRoles("acme").effectiveRoleNames("a").equals(Set.of("a")), + "the rejected edge did not persist"); + } + + @Test + void addInheritEdgeRejectsSelfAndUnknownRoles(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "a", Set.of(), Set.of()); + assertThrows(IllegalArgumentException.class, () -> w.admin().addRoleInherit(tenantWildcard(), "acme", "a", "a")); + assertThrows(IllegalArgumentException.class, () -> w.admin().addRoleInherit(tenantWildcard(), "acme", "a", "ghost")); + } + + @Test + void removeInheritEdgeDropsTheEdge(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.admin().createRole(tenantWildcard(), "acme", "base", Set.of("EDIT_PAGES"), Set.of()); + w.admin().createRole(tenantWildcard(), "acme", "boss", Set.of(), Set.of("base")); + w.admin().removeRoleInherit(tenantWildcard(), "acme", "boss", "base"); + assertTrue(!w.roles().siteRoles("acme").effectivePermissionKeys("boss").contains("EDIT_PAGES"), + "the edge is gone so the inherited permission no longer applies"); + } + + @Test + void roleMutationsAreReservedToAdministrators(@TempDir Path tmp) { + Wiring w = wire(tmp); + RunwayUserDetails operator = user("op", Realm.TENANT, false, List.of(), Roles.OPERATOR); + assertThrows(AccessDeniedException.class, + () -> w.admin().createRole(operator, "acme", "x", Set.of(), Set.of())); + assertThrows(AccessDeniedException.class, + () -> w.admin().deleteRole(operator, "acme", "x")); + assertThrows(AccessDeniedException.class, + () -> w.admin().addRoleInherit(operator, "acme", "x", "y")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/AuthorizationServiceTest.java b/runway-app/src/test/java/mx/quest/runway/authz/AuthorizationServiceTest.java new file mode 100644 index 0000000..a751fc8 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/AuthorizationServiceTest.java @@ -0,0 +1,145 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Set; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwaySecurityProperties; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** The mayAccess precedence: realm match, fail-closed, master/wildcard short-circuits, and effective resolution. */ +class AuthorizationServiceTest { + + private record Wiring(AuthorizationService authz, RoleStore roles, GrantStore grants) {} + + private static Wiring wire(Path tmp, String appMasterId) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + RoleStore roles = new RoleStore(layout, yaml); + GrantStore grants = new GrantStore(layout, yaml); + RunwaySecurityProperties security = new RunwaySecurityProperties(); + security.setAppMasterId(appMasterId); + return new Wiring(new AuthorizationService(roles, grants, new PermissionCatalog(), security), roles, grants); + } + + private static RunwayUserDetails user(String id, Realm realm, boolean master, List sites, String... roles) { + return new RunwayUserDetails(new User(id, id, "$h", "", "", true, master, realm, Set.of(roles), sites)); + } + + // --- gate conditions --------------------------------------------------------------------- + + @Test + void aPermissionOfTheWrongRealmIsDenied(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + // An application user can never exercise a TENANT permission. + assertFalse(w.authz().mayAccess(user("a", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_ADMIN), + Permissions.EDIT_PAGES, null)); + } + + @Test + void aTenantUserCannotExerciseAnApplicationPermission(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + // The mirror of the above (guarding against an inverted realm check): even a tenant SUPERADMIN wildcard + // is denied an APPLICATION-realm permission — authenticating in the tenant realm never grants the app one. + RunwayUserDetails tenantBoss = user("boss", Realm.TENANT, true, List.of("acme"), Roles.SUPERADMIN); + assertFalse(w.authz().mayAccess(tenantBoss, Permissions.MANAGE_APP_USERS, "acme"), + "a tenant superadmin cannot exercise an application-realm permission"); + assertFalse(w.authz().mayAccess(tenantBoss, Permissions.MANAGE_APP_USERS, null), + "…nor with no tenancy bound"); + } + + @Test + void aTenantPermissionWithNoResolvedTenancyIsDenied(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + // No bound tenancy (tenancyId == null): even a tenant wildcard cannot pass — and the store is never + // probed with a null id, so this denies cleanly instead of throwing. + assertFalse(w.authz().mayAccess(user("ad", Realm.TENANT, false, List.of(), Roles.ADMIN), + Permissions.EDIT_PAGES, null)); + } + + @Test + void anUndeclaredPermissionIsDenied(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + Permission madeUp = new Permission("TOTALLY_MADE_UP", Realm.APPLICATION); + // Even the wildcard cannot pass an undeclared permission. + assertFalse(w.authz().mayAccess(user("a", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_ADMIN), madeUp, null)); + } + + // --- the precedence ---------------------------------------------------------------------- + + @Test + void theApplicationMasterPassesEverything(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + RunwayUserDetails master = user("app-master", Realm.APPLICATION, true, List.of(), Roles.SYSTEM_SUPERADMIN); + assertTrue(w.authz().mayAccess(master, Permissions.MANAGE_TENANCIES, null), "even master/wildcard-only"); + assertTrue(w.authz().mayAccess(master, Permissions.VIEW_AUDIT, null)); + } + + @Test + void aWildcardAdminPassesEverythingIncludingPrivileged(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + RunwayUserDetails admin = user("ad", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_ADMIN); + assertTrue(w.authz().mayAccess(admin, Permissions.MANAGE_TENANCIES, null), "privileged passes by wildcard"); + assertTrue(w.authz().mayAccess(admin, Permissions.VIEW_AUDIT, null)); + } + + @Test + void anOrdinaryUserNeedsTheConcretePermission(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + RunwayUserDetails operator = user("op", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_OPERATOR); + // SYSTEMOPERATOR is a seed role with no permissions and is not in the role file → nothing granted. + assertFalse(w.authz().mayAccess(operator, Permissions.VIEW_AUDIT, null)); + assertFalse(w.authz().mayAccess(operator, Permissions.MANAGE_TENANCIES, null), "never grantable to ordinary users"); + } + + @Test + void theTenantMasterShortCircuitIsTenancyScoped(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + // A tenant-master assigned to acme only. + RunwayUserDetails boss = user("boss", Realm.TENANT, true, List.of("acme"), Roles.SUPERADMIN); + assertTrue(w.authz().mayAccess(boss, Permissions.EDIT_PAGES, "acme"), "master of acme"); + assertFalse(w.authz().mayAccess(boss, Permissions.EDIT_PAGES, "beta"), "not master of beta — no short-circuit"); + } + + // --- effective resolution (roles + closure + direct grants + override deltas) ------------ + + @Test + void aCustomRoleGrantsViaTheEffectiveSet(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + w.roles().saveSiteRoles("acme", List.of( + new Role("viewer", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of()), + new Role("lead", Realm.TENANT, Set.of("CONFIGURE_SITE"), Set.of("viewer")))); + // A sub-user carrying the "lead" role gets lead's own + inherited (viewer) permissions. + RunwayUserDetails sub = user("sub", Realm.TENANT, false, List.of(), "lead"); + assertTrue(w.authz().mayAccess(sub, Permissions.EDIT_PAGES, "acme"), "inherited from viewer"); + assertTrue(w.authz().mayAccess(sub, Permissions.CONFIGURE_SITE, "acme")); + assertFalse(w.authz().mayAccess(sub, Permissions.MANAGE_USERS, "acme"), "not granted"); + } + + @Test + void directGrantsAndPerTenancyRoleAssignmentsApply(@TempDir Path tmp) { + Wiring w = wire(tmp, "app-master"); + w.roles().saveSiteRoles("acme", List.of(new Role("editor", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of()))); + // permissions.yml: assign "editor" to sub-1 and grant MANAGE_DOCUMENTS directly to sub-1. + w.grants().saveSiteGrants("acme", new GrantFile( + Map.of("sub-1", Set.of("editor")), Map.of("sub-1", Set.of("MANAGE_DOCUMENTS")))); + RunwayUserDetails sub = user("sub-1", Realm.TENANT, false, List.of()); // no roles on the record itself + + assertTrue(w.authz().mayAccess(sub, Permissions.EDIT_PAGES, "acme"), "role assigned via permissions.yml"); + assertTrue(w.authz().mayAccess(sub, Permissions.MANAGE_DOCUMENTS, "acme"), "direct user grant"); + assertFalse(w.authz().mayAccess(sub, Permissions.DELETE_USERS, "acme")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/AuthzExpressionsTest.java b/runway-app/src/test/java/mx/quest/runway/authz/AuthzExpressionsTest.java new file mode 100644 index 0000000..2a00abc --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/AuthzExpressionsTest.java @@ -0,0 +1,107 @@ +package mx.quest.runway.authz; +import mx.quest.runway.platform.TestPlatformSettings; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwaySecurityProperties; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; + +/** The @authz method-security helper: principal from the SecurityContext, tenancy from the resolver, fail-closed. */ +class AuthzExpressionsTest { + + private record Wiring(AuthzExpressions authz, SiteResolver siteResolver) {} + + private static Wiring wire(Path tmp) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + RunwaySecurityProperties security = new RunwaySecurityProperties(); + security.setAppMasterId("app-master"); + AuthorizationService service = new AuthorizationService( + new RoleStore(layout, yaml), new GrantStore(layout, yaml), new PermissionCatalog(), security); + SiteResolver siteResolver = new SiteResolver(new SiteStore(layout, yaml), TestPlatformSettings.empty()); + return new Wiring(new AuthzExpressions(service, new PermissionCatalog(), siteResolver), siteResolver); + } + + private static RunwayUserDetails user(String id, Realm realm, boolean master, List sites, String... roles) { + return new RunwayUserDetails(new User(id, id, "$h", "", "", true, master, realm, Set.of(roles), sites)); + } + + private static void authenticate(Object principal) { + SecurityContextHolder.getContext().setAuthentication( + UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of())); + } + + @AfterEach + void cleanUp() { + SecurityContextHolder.clearContext(); + } + + @Test + void noAuthenticationDenies(@TempDir Path tmp) { + assertFalse(wire(tmp).authz().may("VIEW_AUDIT")); + } + + @Test + void aForeignPrincipalTypeDenies(@TempDir Path tmp) { + authenticate("bob"); + assertFalse(wire(tmp).authz().may("VIEW_AUDIT")); + } + + @Test + void anUndeclaredKeyDenies(@TempDir Path tmp) { + Wiring w = wire(tmp); + authenticate(user("app-master", Realm.APPLICATION, true, List.of(), Roles.SYSTEM_SUPERADMIN)); + assertFalse(w.authz().may("NOT_A_PERMISSION"), "even the master cannot pass an undeclared key"); + } + + @Test + void theApplicationMasterMayExercisePrivilegedPermissions(@TempDir Path tmp) { + Wiring w = wire(tmp); + authenticate(user("app-master", Realm.APPLICATION, true, List.of(), Roles.SYSTEM_SUPERADMIN)); + assertTrue(w.authz().may("MANAGE_TENANCIES")); + authenticate(user("op", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_OPERATOR)); + assertFalse(w.authz().may("VIEW_AUDIT"), "an ordinary operator holds nothing"); + } + + @Test + void theBoundTenancyIsResolvedForTenantPermissions(@TempDir Path tmp) { + Wiring w = wire(tmp); + authenticate(user("boss", Realm.TENANT, true, List.of("acme"), Roles.SUPERADMIN)); + try { + w.siteResolver().bind(new Site("acme", "Acme", null, Locale.ENGLISH, null, null, null)); + assertTrue(w.authz().may("EDIT_PAGES"), "master of the bound tenancy"); + } finally { + w.siteResolver().clear(); + } + } + + @Test + void theExplicitTenancyFormScopesToThatTenancyAndRejectsAppKeys(@TempDir Path tmp) { + Wiring w = wire(tmp); + authenticate(user("boss", Realm.TENANT, true, List.of("acme"), Roles.SUPERADMIN)); + assertTrue(w.authz().mayInTenancy("EDIT_PAGES", "acme"), "master of acme"); + assertFalse(w.authz().mayInTenancy("EDIT_PAGES", "beta"), "not master of beta"); + assertFalse(w.authz().mayInTenancy("VIEW_AUDIT", "acme"), "an application key is not valid in the tenancy form"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/AuthzStoreIntegrityTest.java b/runway-app/src/test/java/mx/quest/runway/authz/AuthzStoreIntegrityTest.java new file mode 100644 index 0000000..b91ad7b --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/AuthzStoreIntegrityTest.java @@ -0,0 +1,82 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Startup integrity routing: app-store corruption blocks the boot, a tenancy's corruption only quarantines it. */ +class AuthzStoreIntegrityTest { + + private record Wiring(AuthzStoreIntegrity integrity, RoleStore roles, SiteStore sites, StorageLayout layout, + YamlStore yaml) {} + + private static Wiring wire(Path tmp) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + RoleStore roles = new RoleStore(layout, yaml); + SiteStore sites = new SiteStore(layout, yaml); + return new Wiring(new AuthzStoreIntegrity(roles, sites), roles, sites, layout, yaml); + } + + /** A role whose inherited role does not exist — {@link RoleGraph#of} rejects it (an invalid graph). */ + private static RoleFile invalidGraph(Realm realm) { + return new RoleFile(List.of(new Role("a", realm, Set.of(), Set.of("ghost")))); + } + + private static Site site(String id) { + return new Site(id, id, null, Locale.ENGLISH, null, null, null); + } + + @Test + void validStoresPassWithoutQuarantine(@TempDir Path tmp) { + Wiring w = wire(tmp); + w.roles().saveAppRoles(List.of(new Role("auditor", Realm.APPLICATION, Set.of("VIEW_AUDIT"), Set.of()))); + w.sites().save(site("acme")); + w.roles().saveSiteRoles("acme", List.of(new Role("editor", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of()))); + + w.integrity().validateOnStartup(); + assertTrue(w.integrity().quarantined().isEmpty()); + assertFalse(w.integrity().isQuarantined("acme")); + } + + @Test + void anInvalidApplicationStoreAbortsStartup(@TempDir Path tmp) throws IOException { + Wiring w = wire(tmp); + // Bypass saveAppRoles (which validates) to plant a tampered file directly. + w.yaml().write(w.layout().external().resolve("app-roles.yml"), invalidGraph(Realm.APPLICATION)); + + assertThrows(IllegalStateException.class, () -> w.integrity().validateOnStartup()); + } + + @Test + void anInvalidTenancyIsQuarantinedAndOthersSurvive(@TempDir Path tmp) throws IOException { + Wiring w = wire(tmp); + w.sites().save(site("acme")); + w.sites().save(site("beta")); + // acme's roles.yml is tampered (invalid graph); beta's is well-formed. + w.yaml().write(w.layout().siteDir("acme").resolve("roles.yml"), invalidGraph(Realm.TENANT)); + w.roles().saveSiteRoles("beta", List.of(new Role("editor", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of()))); + + w.integrity().validateOnStartup(); // must NOT throw — degrade, don't crash + assertEquals(Set.of("acme"), w.integrity().quarantined()); + assertTrue(w.integrity().isQuarantined("acme")); + assertFalse(w.integrity().isQuarantined("beta"), "a healthy tenancy is unaffected"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/GrantWriteConcurrencyTest.java b/runway-app/src/test/java/mx/quest/runway/authz/GrantWriteConcurrencyTest.java new file mode 100644 index 0000000..5592197 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/GrantWriteConcurrencyTest.java @@ -0,0 +1,146 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import mx.quest.runway.security.AppUserStore; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwaySecurityProperties; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.SiteUserStore; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * The grants file is written by read-modify-write, and nothing serialised it. Two administrators writing + * the same scope at the same moment lost one change, and an assignment landing between a role delete's two writes left + * the holder with a role the graph no longer knows (which still resolves to itself and keeps its console grants). + * + *

Each test makes the second writer start while the first is inside its critical section and gives it time to + * finish there; with the scope's lock it cannot, so the outcome is the same as running the two one after the other. + */ +class GrantWriteConcurrencyTest { + + /** How long the second writer is given to slip in. Long enough to finish a small file write many times over. */ + private static final long WINDOW_MILLIS = 300; + + /** A role store that runs a hook just before it writes the roles file. */ + static final class HookedRoleStore extends RoleStore { + Runnable beforeWrite = () -> { }; + + HookedRoleStore(StorageLayout layout, YamlStore yaml) { + super(layout, yaml); + } + + @Override + public void saveSiteRoles(String siteId, List roles) { + Runnable hook = beforeWrite; + beforeWrite = () -> { }; + hook.run(); + super.saveSiteRoles(siteId, roles); + } + } + + private record Wiring(AuthorizationAdminService admin, HookedRoleStore roles, GrantStore grants) { + } + + private static Wiring wire(Path dir) { + StorageProperties props = new StorageProperties(); + props.setExternal(dir); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + HookedRoleStore roles = new HookedRoleStore(layout, yaml); + GrantStore grants = new GrantStore(layout, yaml); + PermissionCatalog catalog = new PermissionCatalog(); + RunwaySecurityProperties security = new RunwaySecurityProperties(); + security.setAppMasterId("app-master"); + AuthorizationService authz = new AuthorizationService(roles, grants, catalog, security); + UserStore users = new UserStore(yaml); + return new Wiring(new AuthorizationAdminService(roles, grants, catalog, authz, security, + new AppUserStore(layout, users, security), new SiteUserStore(layout, users)), roles, grants); + } + + private static RunwayUserDetails tenantAdmin() { + return new RunwayUserDetails(new User("ad", "ad", "$h", "", "", true, false, Realm.TENANT, + Set.of(Roles.ADMIN), List.of())); + } + + /** Starts {@code work} on another thread and gives it {@link #WINDOW_MILLIS} to finish; returns the thread. */ + private static Thread startAndWait(Runnable work) { + Thread other = new Thread(work, "second-admin"); + other.start(); + try { + other.join(WINDOW_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return other; + } + + @Test + void anAssignmentDuringARoleDeleteNeverLeavesAHolderOfTheGoneRole(@TempDir Path dir) throws Exception { + Wiring w = wire(dir); + w.admin().createRole(tenantAdmin(), "acme", "editor", Set.of("EDIT_PAGES"), Set.of()); + w.admin().assignRole(tenantAdmin(), "acme", "sub", "editor"); + AtomicReference second = new AtomicReference<>(); + AtomicReference thread = new AtomicReference<>(); + // Between the delete's grants write and its roles write, a second admin assigns the role to someone else. + w.roles().beforeWrite = () -> thread.set(startAndWait(() -> { + try { + w.admin().assignRole(tenantAdmin(), "acme", "x", "editor"); + } catch (RuntimeException refused) { + second.set(refused); + } + })); + + w.admin().deleteRole(tenantAdmin(), "acme", "editor"); + thread.get().join(); + + assertFalse(w.roles().siteRoles("acme").hasRole("editor"), "the role is gone"); + assertEquals(Set.of(), w.grants().siteGrants("acme").rolesOf("x"), "and nobody holds it"); + assertEquals(Set.of(), w.grants().siteGrants("acme").rolesOf("sub")); + assertInstanceOf(IllegalArgumentException.class, second.get(), + "the second admin ran after the delete and was told there is no such role"); + } + + @Test + void twoChangesToTheSameScopeAtTheSameMomentBothStay(@TempDir Path dir) throws Exception { + Wiring w = wire(dir); + AtomicReference thread = new AtomicReference<>(); + w.grants().updateSiteGrants("acme", current -> { + thread.set(startAndWait(() -> w.grants().updateSiteGrants("acme", + latest -> latest.withUserPermission("b", "EDIT_PAGES")))); + return current.withUserPermission("a", "EDIT_PAGES"); + }); + thread.get().join(); + + GrantFile stored = w.grants().siteGrants("acme"); + assertTrue(stored.permissionsOf("a").contains("EDIT_PAGES"), "the first change"); + assertTrue(stored.permissionsOf("b").contains("EDIT_PAGES"), "and the second, not lost"); + } + + @Test + void twoSitesDoNotWaitForEachOther(@TempDir Path dir) throws Exception { + Wiring w = wire(dir); + AtomicReference thread = new AtomicReference<>(); + w.grants().updateSiteGrants("acme", current -> { + thread.set(startAndWait(() -> w.grants().updateSiteGrants("beta", + latest -> latest.withUserPermission("b", "EDIT_PAGES")))); + assertFalse(thread.get().isAlive(), "another site's change finished while this one was in progress"); + return current.withUserPermission("a", "EDIT_PAGES"); + }); + assertTrue(w.grants().siteGrants("beta").permissionsOf("b").contains("EDIT_PAGES")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/MethodSecurityIntegrationTest.java b/runway-app/src/test/java/mx/quest/runway/authz/MethodSecurityIntegrationTest.java new file mode 100644 index 0000000..4d4fd3d --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/MethodSecurityIntegrationTest.java @@ -0,0 +1,96 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +/** + * Proves the per-operation layer is actually live: {@code @EnableMethodSecurity} intercepts a + * {@code @PreAuthorize("@authz.may(...)")} method and routes the decision through {@code mayAccess}. The + * unit tests cover the helper's logic; this confirms the Spring wiring (the advisor, the {@code authz} bean). + */ +@SpringBootTest +class MethodSecurityIntegrationTest { + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-6e"); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode("Sup3r-Secret-9"); + new UserStore(new YamlStore()).save(external.resolve("app-users.yml"), + new User("app-master", "admin", hash, "Admin", "a@x", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); // ACTIVE mode + } + + /** A guarded bean — plain class so method security proxies it; the kernel has no business ops yet. */ + @TestConfiguration + static class Beans { + @Bean + Guarded guarded() { + return new Guarded(); + } + } + + static class Guarded { + @PreAuthorize("@authz.may('VIEW_AUDIT')") + public String audit() { + return "ok"; + } + } + + @Autowired + private Guarded guarded; + + @AfterEach + void cleanUp() { + SecurityContextHolder.clearContext(); + } + + private static void authenticate(RunwayUserDetails principal) { + SecurityContextHolder.getContext().setAuthentication( + UsernamePasswordAuthenticationToken.authenticated(principal, null, principal.getAuthorities())); + } + + private static RunwayUserDetails user(String id, boolean master, String... roles) { + return new RunwayUserDetails( + new User(id, id, "$h", "", "", true, master, Realm.APPLICATION, Set.of(roles), List.of())); + } + + @Test + void theGuardDeniesAPrincipalWithoutThePermission() { + authenticate(user("op", false, Roles.SYSTEM_OPERATOR)); + assertThrows(AccessDeniedException.class, guarded::audit); + } + + @Test + void theGuardAllowsTheMaster() { + authenticate(user("app-master", true, Roles.SYSTEM_SUPERADMIN)); + assertEquals("ok", guarded.audit()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/PermissionAuthorizationManagerTest.java b/runway-app/src/test/java/mx/quest/runway/authz/PermissionAuthorizationManagerTest.java new file mode 100644 index 0000000..e0eb8c7 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/PermissionAuthorizationManagerTest.java @@ -0,0 +1,102 @@ +package mx.quest.runway.authz; +import mx.quest.runway.platform.TestPlatformSettings; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwaySecurityProperties; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authorization.AuthorizationResult; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.access.intercept.RequestAuthorizationContext; + +/** The request-gate manager: fail-closed on no/foreign principal, and the bound tenancy resolved per request. */ +class PermissionAuthorizationManagerTest { + + private record Wiring(RequestAuthorizers authorizers, SiteResolver siteResolver) {} + + private static Wiring wire(Path tmp) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + RunwaySecurityProperties security = new RunwaySecurityProperties(); + security.setAppMasterId("app-master"); + AuthorizationService authz = new AuthorizationService( + new RoleStore(layout, yaml), new GrantStore(layout, yaml), new PermissionCatalog(), security); + SiteResolver siteResolver = new SiteResolver(new SiteStore(layout, yaml), TestPlatformSettings.empty()); + return new Wiring(new RequestAuthorizers(authz, siteResolver), siteResolver); + } + + private static RunwayUserDetails user(String id, Realm realm, boolean master, List sites, String... roles) { + return new RunwayUserDetails(new User(id, id, "$h", "", "", true, master, realm, Set.of(roles), sites)); + } + + private static AuthorizationResult check(PermissionAuthorizationManager manager, Authentication auth) { + return manager.authorize(() -> auth, new RequestAuthorizationContext(new MockHttpServletRequest())); + } + + private static Authentication authed(RunwayUserDetails principal) { + return UsernamePasswordAuthenticationToken.authenticated(principal, null, principal.getAuthorities()); + } + + private static Site site(String id) { + return new Site(id, id, null, Locale.ENGLISH, null, null, null); + } + + @Test + void noAuthenticationDenies(@TempDir Path tmp) { + PermissionAuthorizationManager gate = wire(tmp).authorizers().requirePermission(Permissions.VIEW_AUDIT); + assertFalse(check(gate, null).isGranted()); + } + + @Test + void aForeignPrincipalTypeDenies(@TempDir Path tmp) { + PermissionAuthorizationManager gate = wire(tmp).authorizers().requirePermission(Permissions.VIEW_AUDIT); + Authentication notRunway = UsernamePasswordAuthenticationToken.authenticated("bob", null, List.of()); + assertFalse(check(gate, notRunway).isGranted()); + } + + @Test + void anApplicationGateResolvesWithoutASite(@TempDir Path tmp) { + Wiring w = wire(tmp); + PermissionAuthorizationManager privileged = w.authorizers().requirePermission(Permissions.MANAGE_TENANCIES); + assertTrue(check(privileged, authed(user("app-master", Realm.APPLICATION, true, List.of(), Roles.SYSTEM_SUPERADMIN))) + .isGranted(), "the application master passes a privileged gate"); + assertFalse(check(privileged, authed(user("op", Realm.APPLICATION, false, List.of(), Roles.SYSTEM_OPERATOR))) + .isGranted(), "an ordinary operator does not"); + } + + @Test + void aTenantGateResolvesTheBoundTenancy(@TempDir Path tmp) { + Wiring w = wire(tmp); + PermissionAuthorizationManager editPages = w.authorizers().requirePermission(Permissions.EDIT_PAGES); + RunwayUserDetails boss = user("boss", Realm.TENANT, true, List.of("acme"), Roles.SUPERADMIN); + try { + w.siteResolver().bind(site("acme")); + assertTrue(check(editPages, authed(boss)).isGranted(), "master of the bound tenancy passes"); + w.siteResolver().clear(); + w.siteResolver().bind(site("beta")); + assertFalse(check(editPages, authed(boss)).isGranted(), "not master of a different bound tenancy"); + } finally { + w.siteResolver().clear(); + } + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/PermissionCatalogTest.java b/runway-app/src/test/java/mx/quest/runway/authz/PermissionCatalogTest.java new file mode 100644 index 0000000..dad3c88 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/PermissionCatalogTest.java @@ -0,0 +1,49 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import mx.quest.runway.spi.model.Realm; +import org.junit.jupiter.api.Test; + +/** The declared catalog: fail-closed lookup, the grantable/privileged split, and realm tagging. */ +class PermissionCatalogTest { + + private final PermissionCatalog catalog = new PermissionCatalog(); + + @Test + void declaredPermissionsResolveAndUnknownOnesFailClosed() { + assertTrue(catalog.find("EDIT_PAGES").isPresent()); + assertTrue(catalog.isDeclared("MANAGE_TENANCIES")); // privileged ones are still declared + assertTrue(catalog.find("NOPE_NOT_A_PERMISSION").isEmpty(), "an unknown key is undeclared (fail-closed)"); + assertFalse(catalog.isDeclared("NOPE_NOT_A_PERMISSION")); + } + + @Test + void grantablePermissionsAreAssignableAndPrivilegedOnesAreNot() { + assertTrue(catalog.isGrantable(Permissions.EDIT_PAGES)); + assertTrue(catalog.isGrantable(Permissions.VIEW_TENANCIES)); + assertTrue(catalog.isGrantable(Permissions.MANAGE_SITE_HOSTS), "hosts editing is delegable to roles/users"); + assertFalse(catalog.isGrantable(Permissions.MANAGE_TENANCIES), "master/wildcard-only is never grantable"); + assertFalse(catalog.isGrantable(Permissions.CONFIGURE_PLATFORM)); + } + + @Test + void grantableSetsAreRealmScoped() { + assertTrue(catalog.grantable(Realm.TENANT).contains(Permissions.EDIT_PAGES)); + assertFalse(catalog.grantable(Realm.TENANT).contains(Permissions.VIEW_TENANCIES), "app permission, not tenant"); + + assertTrue(catalog.grantable(Realm.APPLICATION).contains(Permissions.VIEW_TENANCIES)); + assertFalse(catalog.grantable(Realm.APPLICATION).contains(Permissions.MANAGE_TENANCIES), "privileged, not grantable"); + assertFalse(catalog.grantable(Realm.APPLICATION).contains(Permissions.EDIT_PAGES), "tenant permission, not app"); + } + + @Test + void everyPermissionIsRealmTaggedAndAllIncludesBothClasses() { + assertEquals(Realm.TENANT, Permissions.EDIT_PAGES.realm()); + assertEquals(Realm.APPLICATION, Permissions.MANAGE_TENANCIES.realm()); + assertTrue(catalog.all().contains(Permissions.EDIT_PAGES)); // grantable + assertTrue(catalog.all().contains(Permissions.MANAGE_TENANCIES)); // privileged + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/PermissionTest.java b/runway-app/src/test/java/mx/quest/runway/authz/PermissionTest.java new file mode 100644 index 0000000..46a97aa --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/PermissionTest.java @@ -0,0 +1,26 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import mx.quest.runway.spi.model.Realm; +import org.junit.jupiter.api.Test; + +/** The realm-tagged permission boundary record: validation and value semantics. */ +class PermissionTest { + + @Test + void requiresAKeyAndARealm() { + assertThrows(IllegalArgumentException.class, () -> new Permission(null, Realm.TENANT)); + assertThrows(IllegalArgumentException.class, () -> new Permission(" ", Realm.TENANT)); + assertThrows(NullPointerException.class, () -> new Permission("EDIT_PAGES", null)); + } + + @Test + void isEqualByKeyAndRealm() { + assertEquals(new Permission("EDIT_PAGES", Realm.TENANT), new Permission("EDIT_PAGES", Realm.TENANT)); + // The same key in a different realm is a different permission (realm-meaningful). + assertNotEquals(new Permission("VIEW", Realm.TENANT), new Permission("VIEW", Realm.APPLICATION)); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/PluginPermissionMergeTest.java b/runway-app/src/test/java/mx/quest/runway/authz/PluginPermissionMergeTest.java new file mode 100644 index 0000000..778e15b --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/PluginPermissionMergeTest.java @@ -0,0 +1,72 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.List; +import mx.quest.runway.plugin.LoadedPlugin; +import mx.quest.runway.plugin.PluginDescriptor; +import mx.quest.runway.spi.model.Realm; +import org.junit.jupiter.api.Test; + +/** Plugin-declared permissions merge into the catalog namespaced; collisions and reserved-role defaults fail. */ +class PluginPermissionMergeTest { + + private static LoadedPlugin plugin(String id, String permissionsYaml) { + String yaml = "id: " + id + "\nversion: 1.0.0\n" + permissionsYaml; + PluginDescriptor descriptor = PluginDescriptor.read( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))); + return new LoadedPlugin(descriptor, Path.of("/tmp/plugins", id)); + } + + private static PluginPermissionContributions contributions(LoadedPlugin... plugins) { + return new PluginPermissionContributions(List.of(plugins)); + } + + @Test + void pluginGrantablePermissionsMergeNamespacedAndAreGrantable() { + PermissionCatalog catalog = new PermissionCatalog(contributions(plugin("contact", """ + permissions: + - { id: settings, realm: tenant, label: contact.perm.settings, defaultRoles: [OPERATOR] } + - { id: dashboard, realm: application, label: contact.perm.dashboard } + """))); + assertTrue(catalog.isDeclared("contact|settings"), "namespaced by plugin id"); + assertTrue(catalog.find("contact|settings").isPresent()); + assertTrue(catalog.find("contact|settings").get().realm() == Realm.TENANT); + assertTrue(catalog.isGrantable(catalog.find("contact|settings").get()), "plugin permissions are grantable"); + assertTrue(catalog.isDeclared("contact|dashboard")); + // the kernel baseline is still intact alongside the plugin's + assertTrue(catalog.isDeclared("EDIT_PAGES")); + } + + @Test + void aReservedDefaultRoleIsAHardFail() { + assertThrows(IllegalStateException.class, () -> contributions(plugin("evil", """ + permissions: + - { id: x, realm: tenant, label: l, defaultRoles: [ADMIN] } + """)), "a plugin may not default a permission to the wildcard admin tier"); + } + + @Test + void anUnknownOrCrossRealmDefaultRoleIsIgnoredNotFatal() { + // SYSTEM_OPERATOR is an application role; on a TENANT permission it is cross-realm — ignored, not fatal. + PermissionCatalog catalog = new PermissionCatalog(contributions(plugin("forms", """ + permissions: + - { id: edit, realm: tenant, label: l, defaultRoles: [SYSTEM_OPERATOR, MADE_UP] } + """))); + assertTrue(catalog.isDeclared("forms|edit"), "the permission still merges; bad default roles are ignored"); + } + + @Test + void aCollidingKeyFailsStartup() { + // Two declarations with the same id in one plugin namespace to the same key — caught at merge. + assertThrows(IllegalStateException.class, () -> new PermissionCatalog(contributions(plugin("dup", """ + permissions: + - { id: settings, realm: tenant, label: a } + - { id: settings, realm: tenant, label: b } + """)))); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/QuarantinedSiteFilterTest.java b/runway-app/src/test/java/mx/quest/runway/authz/QuarantinedSiteFilterTest.java new file mode 100644 index 0000000..b6af670 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/QuarantinedSiteFilterTest.java @@ -0,0 +1,101 @@ +package mx.quest.runway.authz; +import mx.quest.runway.platform.TestPlatformSettings; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import jakarta.servlet.ServletException; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +/** The quarantine filter: hold a quarantined tenancy's admin surface (503), pass its public pages and the app realm. */ +class QuarantinedSiteFilterTest { + + private record Wiring(QuarantinedSiteFilter filter, SiteResolver siteResolver) {} + + private static Wiring wire(Path tmp) throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + RoleStore roles = new RoleStore(layout, yaml); + SiteStore sites = new SiteStore(layout, yaml); + sites.save(new Site("acme", "Acme", null, Locale.ENGLISH, null, null, null)); + sites.save(new Site("beta", "Beta", null, Locale.ENGLISH, null, null, null)); + // acme's role store is tampered (inherits a non-existent role) → quarantined at startup; beta is fine. + yaml.write(layout.siteDir("acme").resolve("roles.yml"), + new RoleFile(List.of(new Role("a", Realm.TENANT, Set.of(), Set.of("ghost"))))); + roles.saveSiteRoles("beta", List.of(new Role("editor", Realm.TENANT, Set.of("EDIT_PAGES"), Set.of()))); + + AuthzStoreIntegrity integrity = new AuthzStoreIntegrity(roles, sites); + integrity.validateOnStartup(); + SiteResolver siteResolver = new SiteResolver(sites, TestPlatformSettings.empty()); + return new Wiring(new QuarantinedSiteFilter(siteResolver, integrity), siteResolver); + } + + private static MockFilterChain run(Wiring w, String boundSiteId, String uri, + MockHttpServletResponse response) throws ServletException, IOException { + MockFilterChain chain = new MockFilterChain(); + try { + if (boundSiteId != null) { + w.siteResolver().bind(new Site(boundSiteId, boundSiteId, null, Locale.ENGLISH, null, null, null)); + } + MockHttpServletRequest request = new MockHttpServletRequest("GET", uri); + request.setRequestURI(uri); + w.filter().doFilter(request, response, chain); + } finally { + w.siteResolver().clear(); + } + return chain; + } + + @Test + void aQuarantinedTenancysAdminSurfaceIsHeld(@TempDir Path tmp) throws Exception { + Wiring w = wire(tmp); + MockHttpServletResponse home = new MockHttpServletResponse(); + assertNull(run(w, "acme", "/__admin", home).getRequest(), "the chain must not be reached"); + assertEquals(503, home.getStatus()); + + MockHttpServletResponse sub = new MockHttpServletResponse(); + assertNull(run(w, "acme", "/__admin/users", sub).getRequest(), "a sub-path of the admin surface is held too"); + assertEquals(503, sub.getStatus()); + } + + @Test + void aQuarantinedTenancysPublicPagesStillServe(@TempDir Path tmp) throws Exception { + Wiring w = wire(tmp); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockFilterChain chain = run(w, "acme", "/about", response); + assertNotNull(chain.getRequest(), "public pages do not consult authorization, so they pass"); + } + + @Test + void aHealthyTenancyAdminSurfacePasses(@TempDir Path tmp) throws Exception { + Wiring w = wire(tmp); + MockFilterChain chain = run(w, "beta", "/__admin", new MockHttpServletResponse()); + assertNotNull(chain.getRequest()); + } + + @Test + void noBoundSitePasses(@TempDir Path tmp) throws Exception { + Wiring w = wire(tmp); + MockFilterChain chain = run(w, null, "/__admin", new MockHttpServletResponse()); + assertNotNull(chain.getRequest()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/RoleDeltaTest.java b/runway-app/src/test/java/mx/quest/runway/authz/RoleDeltaTest.java new file mode 100644 index 0000000..4171ab9 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/RoleDeltaTest.java @@ -0,0 +1,191 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.plugin.LoadedPlugin; +import mx.quest.runway.plugin.PluginDescriptor; +import mx.quest.runway.plugin.PluginPermissionDecl; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwaySecurityProperties; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.security.access.AccessDeniedException; + +/** + * The role-permission deltas: a plugin permission defaults to a seed role, and a scope can grant it + * to other roles or revoke it from the default — stored as deltas so a plugin default change propagates where + * not overridden. Covers both the {@code mayAccess} fold and the bounded-grant admin ops. (Plugin defaults may + * only target the OPERATOR seed role; the wildcard tier ADMIN passes everything by short-circuit, so a custom + * role is used for the "ordinary non-default" cases.) + */ +class RoleDeltaTest { + + private static final String WIDGETS = "demo|widgets"; // a tenant permission defaulting to OPERATOR + + private record World(AuthorizationService authz, AuthorizationAdminService admin, RoleStore roles, + GrantStore grants, PermissionCatalog catalog) {} + + private static World world(Path tmp) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + RoleStore roles = new RoleStore(layout, yaml); + GrantStore grants = new GrantStore(layout, yaml); + RunwaySecurityProperties security = new RunwaySecurityProperties(); + security.setAppMasterId("app-master"); + + PluginDescriptor descriptor = new PluginDescriptor("demo", "Demo", "1.0.0", null, null, null, + null, null, + List.of(new PluginPermissionDecl("widgets", Realm.TENANT, "demo.widgets", List.of(Roles.OPERATOR))), + List.of(), List.of(), java.util.Map.of(), List.of(), List.of(), null); + PermissionCatalog catalog = new PermissionCatalog( + new PluginPermissionContributions(List.of(new LoadedPlugin(descriptor, tmp)))); + + AuthorizationService authz = new AuthorizationService(roles, grants, catalog, security); + mx.quest.runway.security.UserStore users = new mx.quest.runway.security.UserStore(yaml); + mx.quest.runway.security.AppUserStore appUsers = + new mx.quest.runway.security.AppUserStore(layout, users, security); + mx.quest.runway.security.SiteUserStore siteUsers = + new mx.quest.runway.security.SiteUserStore(layout, users); + AuthorizationAdminService admin = + new AuthorizationAdminService(roles, grants, catalog, authz, security, appUsers, siteUsers); + return new World(authz, admin, roles, grants, catalog); + } + + private static RunwayUserDetails user(String id, boolean master, List sites, String... roles) { + return new RunwayUserDetails(new User(id, id, "$h", "", "", true, master, Realm.TENANT, Set.of(roles), sites)); + } + + private Permission widgets(World world) { + return world.catalog().find(WIDGETS).orElseThrow(); + } + + @Test + void aDeclaredDefaultGrantsThePermissionToThatRole(@TempDir Path tmp) { + World world = world(tmp); + world.roles().saveSiteRoles("acme", List.of(new Role("viewer", Realm.TENANT, Set.of(), Set.of()))); + assertTrue(world.authz().mayAccess(user("op", false, List.of(), Roles.OPERATOR), widgets(world), "acme"), + "OPERATOR holds it by default"); + assertFalse(world.authz().mayAccess(user("v", false, List.of(), "viewer"), widgets(world), "acme"), + "a custom role is not a default holder"); + } + + @Test + void aRoleRevokeDeltaRemovesADefault(@TempDir Path tmp) { + World world = world(tmp); + world.grants().saveSiteGrants("acme", GrantFile.empty().withRoleRevoke(Roles.OPERATOR, WIDGETS)); + assertFalse(world.authz().mayAccess(user("op", false, List.of(), Roles.OPERATOR), widgets(world), "acme"), + "the revoke delta removed the default"); + } + + @Test + void aRoleGrantDeltaAddsToANonDefaultRole(@TempDir Path tmp) { + World world = world(tmp); + world.roles().saveSiteRoles("acme", List.of(new Role("viewer", Realm.TENANT, Set.of(), Set.of()))); + world.grants().saveSiteGrants("acme", GrantFile.empty().withRoleGrant("viewer", WIDGETS)); + assertTrue(world.authz().mayAccess(user("v", false, List.of(), "viewer"), widgets(world), "acme"), + "the grant delta added it to the custom role"); + } + + @Test + void theDeltaFoldRespectsCustomRoleInheritance(@TempDir Path tmp) { + World world = world(tmp); + // 'lead' inherits 'viewer'; a grant delta on 'viewer' must reach a 'lead' user through the closure. + world.roles().saveSiteRoles("acme", List.of( + new Role("viewer", Realm.TENANT, Set.of(), Set.of()), + new Role("lead", Realm.TENANT, Set.of(), Set.of("viewer")))); + world.grants().saveSiteGrants("acme", GrantFile.empty().withRoleGrant("viewer", WIDGETS)); + assertTrue(world.authz().mayAccess(user("sub", false, List.of(), "lead"), widgets(world), "acme"), + "the delta flows through the role-name closure"); + } + + @Test + void adminGrantToRoleAndRevokeFromRoleAreDeltaCorrect(@TempDir Path tmp) { + World world = world(tmp); + world.roles().saveSiteRoles("acme", List.of(new Role("viewer", Realm.TENANT, Set.of(), Set.of()))); + RunwayUserDetails boss = user("boss", true, List.of("acme"), Roles.SUPERADMIN); // tenant master of acme + + world.admin().grantToRole(boss, "acme", "viewer", widgets(world)); // non-default role → grant delta + assertTrue(world.authz().mayAccess(user("v", false, List.of(), "viewer"), widgets(world), "acme")); + + world.admin().revokeFromRole(boss, "acme", Roles.OPERATOR, widgets(world)); // default → revoke delta + assertFalse(world.authz().mayAccess(user("op", false, List.of(), Roles.OPERATOR), widgets(world), "acme")); + } + + @Test + void aPermissionStoredOnTheRoleInTheRolesFileCanBeRevokedAndRegranted(@TempDir Path tmp) { + World world = world(tmp); + // A key typed into the roles file (the console never writes it there) — until 1.0.0 it could not be revoked. + world.roles().saveSiteRoles("acme", List.of(new Role("viewer", Realm.TENANT, Set.of(WIDGETS), Set.of()), + new Role("lead", Realm.TENANT, Set.of(), Set.of("viewer")))); + RunwayUserDetails boss = user("boss", true, List.of("acme"), Roles.SUPERADMIN); + RunwayUserDetails viewer = user("v", false, List.of(), "viewer"); + assertTrue(world.authz().mayAccess(viewer, widgets(world), "acme"), "stored on the role"); + assertTrue(world.authz().effectiveRolePermissionKeys(Realm.TENANT, "acme", "viewer").contains(WIDGETS), + "the matrix shows it ticked"); + + world.admin().revokeFromRole(boss, "acme", "viewer", widgets(world)); + assertFalse(world.authz().mayAccess(viewer, widgets(world), "acme"), "the console revoke takes it away"); + assertFalse(world.authz().mayAccess(user("l", false, List.of(), "lead"), widgets(world), "acme"), + "from a role inheriting it too"); + assertFalse(world.authz().effectiveRolePermissionKeys(Realm.TENANT, "acme", "viewer").contains(WIDGETS), + "and the matrix shows it unticked"); + + world.admin().grantToRole(boss, "acme", "viewer", widgets(world)); + assertTrue(world.authz().mayAccess(viewer, widgets(world), "acme"), "granting it again clears the revoke"); + assertTrue(world.grants().siteGrants("acme").roleRevokesOf("viewer").isEmpty(), "no stale revoke is left"); + } + + @Test + void aRevokeWinsOverAGrantOfTheSameKeyOnTheSameRole(@TempDir Path tmp) { + World world = world(tmp); + world.roles().saveSiteRoles("acme", List.of(new Role("viewer", Realm.TENANT, Set.of(), Set.of()))); + // A hand-edited grant file naming WIDGETS in BOTH deltas of 'viewer' must resolve fail-closed (denied). + world.grants().saveSiteGrants("acme", GrantFile.empty() + .withRoleGrant("viewer", WIDGETS).withRoleRevoke("viewer", WIDGETS)); + assertFalse(world.authz().mayAccess(user("v", false, List.of(), "viewer"), widgets(world), "acme"), + "deny (revoke) wins over grant on the same role"); + } + + @Test + void aCrossRealmPermissionOrReservedRoleIsRejected(@TempDir Path tmp) { + World world = world(tmp); + RunwayUserDetails boss = user("boss", true, List.of("acme"), Roles.SUPERADMIN); // tenant master of acme + // A tenant admin must not write an APPLICATION permission key into the tenant grant store. + assertThrows(IllegalArgumentException.class, + () -> world.admin().grantPermission(boss, "acme", "sub", new Permission("VIEW_APP_DASHBOARD", Realm.APPLICATION))); + // ...nor the OTHER realm's reserved (wildcard) role key. + assertThrows(IllegalArgumentException.class, + () -> world.admin().assignRole(boss, "acme", "sub", Roles.SYSTEM_ADMIN)); + } + + @Test + void roleDeltasAreGatedAndValidated(@TempDir Path tmp) { + World world = world(tmp); + RunwayUserDetails plain = user("op", false, List.of(), Roles.OPERATOR); // not a master/wildcard + assertThrows(AccessDeniedException.class, + () -> world.admin().grantToRole(plain, "acme", "viewer", widgets(world)), + "only administrators may manage role deltas"); + + RunwayUserDetails boss = user("boss", true, List.of("acme"), Roles.SUPERADMIN); + assertThrows(IllegalArgumentException.class, + () -> world.admin().grantToRole(boss, "acme", Roles.SUPERADMIN, widgets(world)), + "a delta on an admin tier is inert and rejected"); + assertThrows(IllegalArgumentException.class, + () -> world.admin().grantToRole(boss, "acme", "viewer", + new Permission("MANAGE_TENANCIES", Realm.TENANT)), + "a master/wildcard-only permission may never sit on a role"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/RoleGraphTest.java b/runway-app/src/test/java/mx/quest/runway/authz/RoleGraphTest.java new file mode 100644 index 0000000..7bfd14d --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/RoleGraphTest.java @@ -0,0 +1,77 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Set; +import mx.quest.runway.security.Roles; +import mx.quest.runway.spi.model.Realm; +import org.junit.jupiter.api.Test; + +/** The DAG resolver: transitive downward closure, and fail-closed validation of the seal/refs/cycles. */ +class RoleGraphTest { + + private static Role role(String name, Set perms, String... inherits) { + return new Role(name, Realm.TENANT, perms, Set.of(inherits)); + } + + @Test + void effectivePermissionsAreTheTransitiveDownwardUnion() { + RoleGraph graph = RoleGraph.of(List.of( + role("editor", Set.of("EDIT_PAGES")), + role("publisher", Set.of("APPROVE_PAGES"), "editor"), + role("lead", Set.of("CONFIGURE_SITE"), "publisher"))); + + assertEquals(Set.of("EDIT_PAGES"), graph.effectivePermissionKeys("editor")); + assertEquals(Set.of("EDIT_PAGES", "APPROVE_PAGES"), graph.effectivePermissionKeys("publisher")); + assertEquals(Set.of("EDIT_PAGES", "APPROVE_PAGES", "CONFIGURE_SITE"), graph.effectivePermissionKeys("lead")); + } + + @Test + void diamondInheritanceUnionsWithoutDoubleCounting() { + RoleGraph graph = RoleGraph.of(List.of( + role("base", Set.of("EDIT_PAGES")), + role("left", Set.of("MANAGE_USERS"), "base"), + role("right", Set.of("MANAGE_DOCUMENTS"), "base"), + role("top", Set.of(), "left", "right"))); + assertEquals(Set.of("EDIT_PAGES", "MANAGE_USERS", "MANAGE_DOCUMENTS"), graph.effectivePermissionKeys("top")); + } + + @Test + void anUnknownRoleGrantsNothing() { + assertTrue(RoleGraph.of(List.of()).effectivePermissionKeys("nope").isEmpty()); + } + + @Test + void duplicateNamesAreRejected() { + assertThrows(IllegalStateException.class, () -> RoleGraph.of(List.of( + role("dup", Set.of("EDIT_PAGES")), role("dup", Set.of("MANAGE_USERS"))))); + } + + @Test + void theReservedChainIsSealed() { + // A custom role may neither BE a reserved key nor INHERIT one. + assertThrows(IllegalStateException.class, () -> RoleGraph.of(List.of( + new Role(Roles.ADMIN, Realm.TENANT, Set.of(), Set.of())))); + assertThrows(IllegalStateException.class, () -> RoleGraph.of(List.of( + role("sneaky", Set.of(), Roles.ADMIN)))); + assertThrows(IllegalStateException.class, () -> RoleGraph.of(List.of( + new Role("appSneaky", Realm.APPLICATION, Set.of(), Set.of(Roles.SYSTEM_SUPERADMIN))))); + } + + @Test + void inheritingAnUnknownRoleIsRejected() { + assertThrows(IllegalStateException.class, () -> RoleGraph.of(List.of( + role("orphan", Set.of(), "ghost")))); + } + + @Test + void cyclesAreRejected() { + assertThrows(IllegalStateException.class, () -> RoleGraph.of(List.of( + role("a", Set.of(), "b"), role("b", Set.of(), "a")))); + assertThrows(IllegalStateException.class, () -> RoleGraph.of(List.of( + role("self", Set.of(), "self")))); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/authz/RoleStoreTest.java b/runway-app/src/test/java/mx/quest/runway/authz/RoleStoreTest.java new file mode 100644 index 0000000..959f565 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/authz/RoleStoreTest.java @@ -0,0 +1,76 @@ +package mx.quest.runway.authz; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Role persistence: round-trips, per-tenancy isolation, validate-on-save, and fail-closed-on-load. */ +class RoleStoreTest { + + private static RoleStore store(Path tmp, YamlStore yaml) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + return new RoleStore(StorageLayout.from(props), yaml); + } + + private static Role tenantRole(String name, String perm, String... inherits) { + return new Role(name, Realm.TENANT, Set.of(perm), Set.of(inherits)); + } + + @Test + void appRolesRoundTripThroughAGraph(@TempDir Path tmp) { + RoleStore store = store(tmp, new YamlStore()); + store.saveAppRoles(List.of( + new Role("auditor", Realm.APPLICATION, Set.of("VIEW_AUDIT"), Set.of()), + new Role("ops", Realm.APPLICATION, Set.of("VIEW_BANDWIDTH"), Set.of("auditor")))); + + RoleGraph graph = store.appRoles(); + assertEquals(Set.of("VIEW_BANDWIDTH", "VIEW_AUDIT"), graph.effectivePermissionKeys("ops")); + } + + @Test + void siteRolesAreIsolatedPerTenancy(@TempDir Path tmp) { + RoleStore store = store(tmp, new YamlStore()); + store.saveSiteRoles("acme", List.of(tenantRole("editor", "EDIT_PAGES"))); + store.saveSiteRoles("beta", List.of(tenantRole("reviewer", "APPROVE_PAGES"))); + + assertTrue(store.siteRoles("acme").hasRole("editor")); + assertTrue(store.siteRoles("acme").effectivePermissionKeys("reviewer").isEmpty(), "beta's role is invisible to acme"); + assertTrue(store.siteRoles("beta").hasRole("reviewer")); + } + + @Test + void saveRejectsAnInvalidGraph(@TempDir Path tmp) { + RoleStore store = store(tmp, new YamlStore()); + assertThrows(IllegalStateException.class, () -> store.saveSiteRoles("acme", + List.of(tenantRole("a", "EDIT_PAGES", "b"), tenantRole("b", "MANAGE_USERS", "a")))); // cycle + } + + @Test + void aHandEditedInvalidFileFailsClosedOnLoad(@TempDir Path tmp) throws IOException { + YamlStore yaml = new YamlStore(); + RoleStore store = store(tmp, yaml); + // Write a cyclic file directly, bypassing the save-time validation (simulating a tamper). + Path file = StorageLayout.from(propsFor(tmp)).siteDir("acme").resolve("roles.yml"); + yaml.write(file, new RoleFile(List.of(tenantRole("x", "EDIT_PAGES", "y"), tenantRole("y", "MANAGE_USERS", "x")))); + + assertThrows(IllegalStateException.class, () -> store.siteRoles("acme")); + } + + private static StorageProperties propsFor(Path tmp) { + StorageProperties props = new StorageProperties(); + props.setExternal(tmp); + return props; + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/BackupFormatVersionTest.java b/runway-app/src/test/java/mx/quest/runway/backup/BackupFormatVersionTest.java new file mode 100644 index 0000000..671c589 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/BackupFormatVersionTest.java @@ -0,0 +1,233 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.Yaml; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * The backup archive's {@code formatVersion}: written as 1, absent reads as 1 (every archive made before + * the field existed), anything up to the supported version restores, and a newer one is refused before the live + * site is touched — on restore, stored restore and create-site-from-backup alike. + */ +class BackupFormatVersionTest { + + /** A manifest exactly as 0.5.0-beta13 wrote it — before {@code formatVersion} existed. */ + private static final String PRE_FIELD_MANIFEST = """ + siteId: "demo" + spiVersion: "0.3.4" + createdAt: "2026-10-01T10:00:00Z" + participants: [] + purpose: "RESTORE" + """; + + @TempDir + Path external; + private StorageLayout layout; + private SiteStore sites; + private BackupService svc; + private Path siteDir; + + @BeforeEach + void setUp() throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + props.setBackups(external.resolve("backups")); + layout = StorageLayout.from(props); + sites = new SiteStore(layout, new YamlStore()); + svc = new BackupService(layout, sites, new BackupParticipantRegistry(List.of()), event -> { }); + siteDir = layout.siteDir("demo"); + write(siteDir.resolve("site.yml"), "id: demo\nname: Demo\n"); + write(siteDir.resolve("templates/home.html"), "LIVE"); + } + + private static void write(Path file, String content) throws IOException { + Files.createDirectories(file.getParent()); + Files.writeString(file, content, StandardCharsets.UTF_8); + } + + private String home() throws IOException { + return Files.readString(siteDir.resolve("templates/home.html"), StandardCharsets.UTF_8); + } + + /** A hand-built archive: the given manifest (first or last) plus a minimal site carrying {@code marker}. */ + private static byte[] archive(String manifest, boolean manifestLast, String marker) throws IOException { + Map entries = new LinkedHashMap<>(); + if (!manifestLast) { + entries.put("manifest.yml", manifest); + } + entries.put("site/site.yml", "id: demo\nname: Demo\n"); + entries.put("site/templates/home.html", marker); + if (manifestLast) { + entries.put("manifest.yml", manifest); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(out)) { + for (Map.Entry e : entries.entrySet()) { + zip.putNextEntry(new ZipEntry(e.getKey())); + zip.write(e.getValue().getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + } + return out.toByteArray(); + } + + private static String manifestOf(byte[] archive) throws IOException { + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive))) { + ZipEntry e; + while ((e = zip.getNextEntry()) != null) { + if (e.getName().equals("manifest.yml")) { + return new String(zip.readAllBytes(), StandardCharsets.UTF_8); + } + } + } + throw new AssertionError("no manifest.yml"); + } + + private void assertUntouched() throws IOException { + assertEquals("LIVE", home(), "the live site is untouched"); + assertFalse(Files.exists(layout.sites().resolve(".restore-work").resolve("demo")), "scratch cleaned up"); + } + + // --- writing ------------------------------------------------------------------------------------------------- + + @Test + void everyNewArchiveDeclaresTheSupportedFormat() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + svc.backup("demo", out); + + String manifest = manifestOf(out.toByteArray()); + assertTrue(manifest.contains("formatVersion: 1"), manifest); + BackupManifest parsed = Yaml.read(new ByteArrayInputStream(manifest.getBytes(StandardCharsets.UTF_8)), + BackupManifest.class); + assertEquals(BackupManifest.SUPPORTED_FORMAT_VERSION, parsed.formatVersion()); + assertEquals(1, BackupManifest.SUPPORTED_FORMAT_VERSION); + } + + @Test + void aTransferArchiveDeclaresItToo() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + svc.backup("demo", out, BackupService.BackupPurpose.TRANSFER); + + assertTrue(manifestOf(out.toByteArray()).contains("formatVersion: 1")); + } + + // --- reading: absent and supported --------------------------------------------------------------------------- + + @Test + void anAbsentFieldReadsAsFormatOne() { + assertEquals(1, Yaml.read(new ByteArrayInputStream(PRE_FIELD_MANIFEST.getBytes(StandardCharsets.UTF_8)), + BackupManifest.class).formatVersion()); + assertEquals(1, new BackupManifest("s", "0.1.0", "t", List.of()).formatVersion()); + assertEquals(1, new BackupManifest("s", "0.1.0", "t", List.of(), "RESTORE").formatVersion()); + assertEquals(1, new BackupManifest("s", "0.1.0", "t", List.of(), "RESTORE", null).formatVersion()); + } + + /** The cross-version promise in its first form: an archive written before the field existed still restores. */ + @Test + void anArchiveWrittenBeforeTheFieldExistedRestores() throws IOException { + svc.restore("demo", new ByteArrayInputStream(archive(PRE_FIELD_MANIFEST, false, "FROM_BETA13"))); + + assertEquals("FROM_BETA13", home()); + } + + @Test + void anExplicitFormatOneRestores() throws IOException { + svc.restore("demo", new ByteArrayInputStream(archive(PRE_FIELD_MANIFEST + "formatVersion: 1\n", false, + "V1"))); + + assertEquals("V1", home()); + } + + /** Additive manifest keys are not a format bump: an older reader ignores what it does not know. */ + @Test + void unknownManifestKeysAreIgnored() throws IOException { + svc.restore("demo", new ByteArrayInputStream(archive( + PRE_FIELD_MANIFEST + "formatVersion: 1\nwrittenBy: \"1.3.0\"\nchecksums: {a: b}\n", false, "V1X"))); + + assertEquals("V1X", home()); + } + + // --- reading: newer ------------------------------------------------------------------------------------------ + + @Test + void aNewerFormatIsRefusedAndTheSiteIsUntouched() throws IOException { + byte[] future = archive(PRE_FIELD_MANIFEST + "formatVersion: 2\n", false, "FROM_THE_FUTURE"); + + UnsupportedBackupFormatException refused = assertThrows(UnsupportedBackupFormatException.class, + () -> svc.restore("demo", new ByteArrayInputStream(future))); + + assertEquals(2, refused.found()); + assertEquals(1, refused.supported()); + assertInstanceOf(IOException.class, refused, "callers handling 'not a valid backup' still handle it"); + assertUntouched(); + } + + /** Refused however the archive is ordered — the check does not depend on the manifest coming first. */ + @Test + void aNewerFormatIsRefusedWhenTheManifestComesLast() throws IOException { + byte[] future = archive(PRE_FIELD_MANIFEST + "formatVersion: 5\n", true, "FROM_THE_FUTURE"); + + assertThrows(UnsupportedBackupFormatException.class, + () -> svc.restore("demo", new ByteArrayInputStream(future))); + assertUntouched(); + } + + @Test + void aStoredRestoreOfANewerFormatIsRefused() throws IOException { + String name = svc.create("demo"); + Files.write(external.resolve("backups").resolve("demo").resolve(name), + archive(PRE_FIELD_MANIFEST + "formatVersion: 2\n", false, "FROM_THE_FUTURE")); + + assertThrows(UnsupportedBackupFormatException.class, () -> svc.restoreStored("demo", name)); + assertUntouched(); + } + + @Test + void creatingASiteFromANewerFormatIsRefusedAndNothingIsCreated() throws IOException { + byte[] future = archive(PRE_FIELD_MANIFEST + "formatVersion: 2\n", false, "FROM_THE_FUTURE"); + + assertThrows(UnsupportedBackupFormatException.class, + () -> svc.createFromBackup("clone", "Clone", List.of("clone.test"), new ByteArrayInputStream(future))); + + assertFalse(sites.exists("clone"), "no site was created"); + assertFalse(Files.exists(layout.siteDir("clone")), "no folder was left behind"); + assertFalse(Files.exists(layout.sites().resolve(".restore-work").resolve("clone")), "scratch cleaned up"); + } + + // --- reading: nonsense --------------------------------------------------------------------------------------- + + @Test + void aFormatBelowOneIsNotAValidBackup() throws IOException { + byte[] bogus = archive(PRE_FIELD_MANIFEST + "formatVersion: 0\n", false, "BOGUS"); + + IOException refused = assertThrows(IOException.class, + () -> svc.restore("demo", new ByteArrayInputStream(bogus))); + + assertFalse(refused instanceof UnsupportedBackupFormatException, "0 is not 'newer', it is invalid"); + assertTrue(refused.getMessage().contains("not a valid Runway site backup"), refused.getMessage()); + assertUntouched(); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/BackupParticipantRegistryTest.java b/runway-app/src/test/java/mx/quest/runway/backup/BackupParticipantRegistryTest.java new file mode 100644 index 0000000..5b7f615 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/BackupParticipantRegistryTest.java @@ -0,0 +1,49 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import mx.quest.runway.spi.BackupParticipant; +import mx.quest.runway.spi.model.BackupReader; +import mx.quest.runway.spi.model.BackupWriter; +import mx.quest.runway.spi.model.SiteRef; +import org.junit.jupiter.api.Test; + +/** The registry collects participants by archive-namespace key (fail-fast on a duplicate) and finds by key. */ +class BackupParticipantRegistryTest { + + private static BackupParticipant participant(String key) { + return new BackupParticipant() { + @Override + public String key() { + return key; + } + + @Override + public void export(BackupWriter out, SiteRef site) { + // no-op for the test + } + + @Override + public void importInto(BackupReader in, SiteRef site) { + // no-op for the test + } + }; + } + + @Test + void aDuplicateKeyFailsFast() { + assertThrows(IllegalStateException.class, + () -> new BackupParticipantRegistry(List.of(participant("dup"), participant("dup")))); + } + + @Test + void collectsAndFindsByKey() { + BackupParticipantRegistry registry = new BackupParticipantRegistry(List.of(participant("a"), participant("z"))); + assertEquals(2, registry.all().size()); + assertTrue(registry.find("a").isPresent()); + assertTrue(registry.find("missing").isEmpty()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/BackupRestoreRecoveryTest.java b/runway-app/src/test/java/mx/quest/runway/backup/BackupRestoreRecoveryTest.java new file mode 100644 index 0000000..12eb93d --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/BackupRestoreRecoveryTest.java @@ -0,0 +1,79 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * BH — the startup crash-recovery sweep: an interrupted restore (site swapped out to {@code .restore-work//old} + * but the staged copy never swapped in) is rolled forward; a work dir left beside a live site is merely cleared. + */ +class BackupRestoreRecoveryTest { + + @TempDir + Path external; + private StorageLayout layout; + private BackupRestoreRecovery recovery; + + @BeforeEach + void setUp() { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + layout = StorageLayout.from(props); + recovery = new BackupRestoreRecovery(layout); + } + + private Path workOld(String siteId) { + return layout.sites().resolve(BackupService.WORK_DIR).resolve(siteId).resolve("old"); + } + + @Test + void anInterruptedRestoreIsRolledForwardOnStartup() throws IOException { + // A crash between (siteDir -> old) and (staging -> siteDir): the site is gone, its only copy is `old`. + Path old = workOld("demo"); + Files.createDirectories(old); + Files.writeString(old.resolve("site.yml"), "id: demo\n", StandardCharsets.UTF_8); + assertFalse(Files.exists(layout.siteDir("demo")), "precondition: the live site is absent"); + + recovery.recover(); + + assertEquals("id: demo\n", Files.readString(layout.siteDir("demo").resolve("site.yml"), StandardCharsets.UTF_8), + "the site is rolled forward from the preserved copy"); + assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")), + "the scratch work dir is cleared"); + } + + @Test + void leftoverScratchBesideALiveSiteIsClearedWithoutOverwritingIt() throws IOException { + // The live site exists AND a stale work dir lingers (the swap completed, cleanup did not). + Path siteDir = layout.siteDir("demo"); + Files.createDirectories(siteDir); + Files.writeString(siteDir.resolve("site.yml"), "id: demo\nname: LIVE\n", StandardCharsets.UTF_8); + Path old = workOld("demo"); + Files.createDirectories(old); + Files.writeString(old.resolve("site.yml"), "id: demo\nname: STALE\n", StandardCharsets.UTF_8); + + recovery.recover(); + + assertEquals("id: demo\nname: LIVE\n", Files.readString(siteDir.resolve("site.yml"), StandardCharsets.UTF_8), + "the live site is never overwritten by leftover scratch"); + assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR).resolve("demo")), + "the scratch work dir is cleared"); + } + + @Test + void noWorkDirIsANoOp() { + recovery.recover(); // must not throw when sites/.restore-work does not exist + assertFalse(Files.exists(layout.sites().resolve(BackupService.WORK_DIR))); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/BackupRetentionTest.java b/runway-app/src/test/java/mx/quest/runway/backup/BackupRetentionTest.java new file mode 100644 index 0000000..821c859 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/BackupRetentionTest.java @@ -0,0 +1,103 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import mx.quest.runway.backup.BackupService.StoredBackup; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Stored-backup retention: a new backup prunes the site's older ones per the count/age policy. */ +class BackupRetentionTest { + + @TempDir + Path external; + private StorageLayout layout; + private Path backupsDir; + + @BeforeEach + void setUp() throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + props.setBackups(external.resolve("backups")); + layout = StorageLayout.from(props); + Path siteDir = layout.siteDir("demo"); + Files.createDirectories(siteDir.resolve("templates")); + Files.writeString(siteDir.resolve("site.yml"), "id: demo\nname: Demo\n", StandardCharsets.UTF_8); + Files.writeString(siteDir.resolve("templates/_master.html"), "MASTER", StandardCharsets.UTF_8); + backupsDir = layout.backups().resolve("demo"); + Files.createDirectories(backupsDir); + } + + private BackupService serviceWith(int maxCount, int maxAgeDays) { + SiteStore sites = new SiteStore(layout, new YamlStore()); + BackupProperties props = new BackupProperties(); + props.getRetention().setMaxCount(maxCount); + props.getRetention().setMaxAgeDays(maxAgeDays); + return new BackupService(layout, sites, new BackupParticipantRegistry(List.of()), event -> { }, props); + } + + /** Seeds a stored backup file with a fixed lexical stamp and last-modified time. */ + private void seed(String stamp, Instant modified) throws IOException { + Path f = backupsDir.resolve("backup-" + stamp + ".zip"); + Files.writeString(f, "OLD", StandardCharsets.UTF_8); + Files.setLastModifiedTime(f, FileTime.from(modified)); + } + + @Test + void countBasedRetentionKeepsOnlyTheNewestN() throws IOException { + for (int i = 1; i <= 5; i++) { + seed("20260101-00000" + i + "-000", Instant.now()); // older lexical stamps than the fresh one + } + BackupService svc = serviceWith(3, 0); + + String fresh = svc.create("demo"); // writes a 2026-07-ish stamp, then prunes + + List kept = svc.list("demo"); + assertEquals(3, kept.size(), "count retention should cap at maxCount"); + assertTrue(kept.stream().anyMatch(b -> b.name().equals(fresh)), "the just-created backup is never pruned"); + assertFalse(kept.stream().anyMatch(b -> b.name().equals("backup-20260101-000001-000.zip")), + "the oldest backup should be pruned"); + } + + @Test + void ageBasedRetentionDropsBackupsOlderThanMaxAge() throws IOException { + seed("20260101-000001-000", Instant.now().minus(10, ChronoUnit.DAYS)); // stale + seed("20260101-000002-000", Instant.now()); // recent + BackupService svc = serviceWith(0, 3); // age-only: keep <= 3 days + + svc.create("demo"); + + List kept = svc.list("demo"); + assertFalse(kept.stream().anyMatch(b -> b.name().equals("backup-20260101-000001-000.zip")), + "a backup older than maxAgeDays should be pruned"); + assertTrue(kept.stream().anyMatch(b -> b.name().equals("backup-20260101-000002-000.zip")), + "a recent backup should be kept"); + } + + @Test + void retentionOffLeavesEveryBackupInPlace() throws IOException { + for (int i = 1; i <= 4; i++) { + seed("20260101-00000" + i + "-000", Instant.now().minus(100, ChronoUnit.DAYS)); + } + BackupService svc = serviceWith(0, 0); // both dimensions off + + svc.create("demo"); + + assertEquals(5, svc.list("demo").size(), "with retention off nothing is pruned"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/BackupServiceTest.java b/runway-app/src/test/java/mx/quest/runway/backup/BackupServiceTest.java new file mode 100644 index 0000000..3440e21 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/BackupServiceTest.java @@ -0,0 +1,620 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.time.Instant; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; +import java.util.Locale; +import mx.quest.runway.backup.BackupService.StoredBackup; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.BackupParticipant; +import mx.quest.runway.spi.model.BackupReader; +import mx.quest.runway.spi.model.BackupWriter; +import mx.quest.runway.spi.model.SiteRef; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** The backup/restore engine: a complete round-trip, participant data, zip-slip safety, stored backups. */ +class BackupServiceTest { + + /** A participant that round-trips a blob of out-of-folder data through the archive. */ + private static final class FakeParticipant implements BackupParticipant { + String exported = "PLUGIN_STATE_V1"; + String imported; + + @Override + public String key() { + return "search"; + } + + @Override + public void export(BackupWriter out, SiteRef site) throws IOException { + try (OutputStream o = out.put("index.dat")) { + o.write(exported.getBytes(StandardCharsets.UTF_8)); + } + } + + @Override + public void importInto(BackupReader in, SiteRef site) throws IOException { + if (in.has("index.dat")) { + try (InputStream i = in.open("index.dat")) { + imported = new String(i.readAllBytes(), StandardCharsets.UTF_8); + } + } + } + } + + @TempDir + Path external; + private StorageLayout layout; + private Path siteDir; + private FakeParticipant fake; + private BackupService svc; + + @BeforeEach + void setUp() throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + props.setBackups(external.resolve("backups")); // keep stored backups in the temp tree, not the module dir + layout = StorageLayout.from(props); + SiteStore sites = new SiteStore(layout, new YamlStore()); + fake = new FakeParticipant(); + svc = new BackupService(layout, sites, new BackupParticipantRegistry(List.of(fake)), event -> { }); + siteDir = layout.siteDir("demo"); + write(siteDir.resolve("site.yml"), "id: demo\nname: Demo\n"); + write(siteDir.resolve("templates/_master.html"), "MASTER_V1"); + write(siteDir.resolve("users.yml"), "USERS_V1"); + } + + private static void write(Path file, String content) throws IOException { + Files.createDirectories(file.getParent()); + Files.writeString(file, content, StandardCharsets.UTF_8); + } + + private static String read(Path file) throws IOException { + return Files.readString(file, StandardCharsets.UTF_8); + } + + /** A service over the same layout whose per-entry decompression cap is {@code cap} bytes (zip-bomb tests). */ + private BackupService withEntryCap(long cap) { + BackupProperties props = new BackupProperties(); + props.setMaxEntryBytes(cap); + return new BackupService(layout, new SiteStore(layout, new YamlStore()), + new BackupParticipantRegistry(List.of(fake)), event -> { }, props); + } + + @Test + void backupThenRestoreRoundTripsTheWholeSiteAndParticipantData() throws IOException { + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); + + // Simulate a mistake: mangle a file, delete another, lose the plugin state. + write(siteDir.resolve("templates/_master.html"), "MASTER_BROKEN"); + Files.delete(siteDir.resolve("users.yml")); + fake.imported = null; + + svc.restore("demo", new ByteArrayInputStream(archive.toByteArray())); + + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "content restored"); + assertEquals("USERS_V1", read(siteDir.resolve("users.yml")), "a deleted file is restored"); + assertEquals("id: demo\nname: Demo\n", read(siteDir.resolve("site.yml")), "the site record travels too"); + assertEquals("PLUGIN_STATE_V1", fake.imported, "the participant's out-of-folder data is restored"); + } + + @Test + void theArchiveHasAManifestSiteTreeAndPluginData() throws IOException { + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); + boolean manifest = false, siteFile = false, pluginData = false; + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive.toByteArray()))) { + ZipEntry e; + while ((e = zip.getNextEntry()) != null) { + if (e.getName().equals("manifest.yml")) manifest = true; + if (e.getName().equals("site/templates/_master.html")) siteFile = true; + if (e.getName().equals("plugin-data/search/index.dat")) pluginData = true; + } + } + assertTrue(manifest, "manifest.yml present"); + assertTrue(siteFile, "site tree under site/"); + assertTrue(pluginData, "participant data under plugin-data//"); + } + + @Test + void aZipSlipEntryIsRejectedAndTheSiteSurvives() throws IOException { + ByteArrayOutputStream evil = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(evil)) { + z.putNextEntry(new ZipEntry("manifest.yml")); + z.write("siteId: demo".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/../../evil.txt")); // traversal + z.write("PWNED".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + } + assertThrows(RuntimeException.class, + () -> svc.restore("demo", new ByteArrayInputStream(evil.toByteArray()))); + assertFalse(Files.exists(external.resolve("evil.txt")), "the traversal file was never written"); + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the original site is untouched"); + } + + @Test + void storedBackupsAreCreatedListedDownloadedAndDeletedSafely() throws IOException { + String name = svc.create("demo"); + assertTrue(name.startsWith("backup-") && name.endsWith(".zip")); + + List list = svc.list("demo"); + assertEquals(1, list.size()); + assertEquals(name, list.get(0).name()); + assertTrue(list.get(0).sizeBytes() > 0); + assertTrue(svc.file("demo", name).isPresent()); + + // Traversal-safe: a malicious name never resolves. + assertTrue(svc.file("demo", "../../etc/passwd").isEmpty()); + assertFalse(svc.delete("demo", "../evil.zip")); + + assertTrue(svc.delete("demo", name)); + assertTrue(svc.list("demo").isEmpty()); + } + + @Test + void anArchiveWithoutManifestOrSiteContentIsRejectedAndTheSiteSurvives() throws IOException { + ByteArrayOutputStream bogus = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(bogus)) { + z.putNextEntry(new ZipEntry("readme.txt")); // not a manifest, not site/, not plugin-data/ + z.write("this is not a runway backup".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + } + IOException ex = assertThrows(IOException.class, + () -> svc.restore("demo", new ByteArrayInputStream(bogus.toByteArray()))); + assertTrue(ex.getMessage().contains("valid Runway"), "rejected as not a Runway backup"); + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the site is untouched"); + assertTrue(Files.exists(siteDir.resolve("users.yml")), "no file was removed"); + assertFalse(Files.exists(layout.sites().resolve(".restore-work").resolve("demo")), "scratch cleaned up"); + } + + @Test + void anArchiveMissingSiteYmlIsRejectedAndNothingLeaksIntoTheSite() throws IOException { + ByteArrayOutputStream noRecord = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(noRecord)) { + z.putNextEntry(new ZipEntry("manifest.yml")); + z.write(("siteId: demo\nspiVersion: \"0.2.0\"\ncreatedAt: \"2026-01-01T00:00:00Z\"\nparticipants: []\n") + .getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/templates/orphan.html")); // site content, but no site.yml record + z.write("ORPHAN".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + } + assertThrows(IOException.class, + () -> svc.restore("demo", new ByteArrayInputStream(noRecord.toByteArray()))); + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the site is untouched"); + assertFalse(Files.exists(siteDir.resolve("templates/orphan.html")), "no staged file reached the live site"); + } + + @Test + void restoreRejectsAnOversizePluginDataEntryAndTheSiteSurvives() throws IOException { + // The heap-exhaustion vector: a plugin-data entry read into memory. Tiny compressed, inflates past the cap. + ByteArrayOutputStream bomb = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(bomb)) { + z.putNextEntry(new ZipEntry("manifest.yml")); + z.write("siteId: demo\nparticipants: []\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/site.yml")); + z.write("id: demo\nname: Demo\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("plugin-data/search/huge.dat")); + z.write(new byte[64 * 1024]); // well past the 1 KiB cap below + z.closeEntry(); + } + IOException ex = assertThrows(IOException.class, + () -> withEntryCap(1024).restore("demo", new ByteArrayInputStream(bomb.toByteArray()))); + assertTrue(ex.getMessage().contains("per-entry limit"), "rejected by the per-entry cap"); + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the live site is untouched"); + assertFalse(Files.exists(layout.sites().resolve(".restore-work").resolve("demo")), "scratch cleaned up"); + } + + @Test + void restoreRejectsAnOversizeSiteFileAndTheSiteSurvives() throws IOException { + // The disk-fill vector: a site/ entry streamed to staging. The attacker controls the entry name, so the + // guard must bound this path too, not only plugin-data. + ByteArrayOutputStream bomb = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(bomb)) { + z.putNextEntry(new ZipEntry("manifest.yml")); + z.write("siteId: demo\nparticipants: []\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/huge.bin")); + z.write(new byte[64 * 1024]); // a single site entry over the cap + z.closeEntry(); + } + assertThrows(IOException.class, + () -> withEntryCap(1024).restore("demo", new ByteArrayInputStream(bomb.toByteArray()))); + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the live site is untouched"); + assertFalse(Files.exists(siteDir.resolve("huge.bin")), "the oversize entry never reached the live site"); + assertFalse(Files.exists(layout.sites().resolve(".restore-work").resolve("demo")), "scratch cleaned up"); + } + + @Test + void restoreRejectsAnOversizeUnrecognizedEntryAndTheSiteSurvives() throws IOException { + // An entry named under neither site/ nor plugin-data/ was previously never read, so the next + // getNextEntry() inflated it whole while skipping — an unbounded zip-bomb past validation. It must be + // bound-drained and refused by the same per-entry cap. + ByteArrayOutputStream bomb = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(bomb)) { + z.putNextEntry(new ZipEntry("manifest.yml")); + z.write("siteId: demo\nparticipants: []\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/site.yml")); + z.write("id: demo\nname: Demo\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("bomb.dat")); // top-level, matches no prefix + z.write(new byte[64 * 1024]); // past the 1 KiB cap below + z.closeEntry(); + } + IOException ex = assertThrows(IOException.class, + () -> withEntryCap(1024).restore("demo", new ByteArrayInputStream(bomb.toByteArray()))); + assertTrue(ex.getMessage().contains("per-entry limit"), "the unrecognized entry is bound-drained by the cap"); + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the live site is untouched"); + assertFalse(Files.exists(layout.sites().resolve(".restore-work").resolve("demo")), "scratch cleaned up"); + } + + @Test + void restoreExtractsASymlinkLikeEntryAsARegularFileNotAFollowedLink() throws IOException { + // A backup entry that names an out-of-tree target must be materialized as an ordinary file, never a + // symlink the platform would later follow out of the site folder. ZipInputStream never creates links — + // this pins that guarantee so a future extraction rewrite can't regress it. + ByteArrayOutputStream evil = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(evil)) { + z.putNextEntry(new ZipEntry("manifest.yml")); + z.write("siteId: demo\nparticipants: []\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/site.yml")); + z.write("id: demo\nname: Demo\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/passwd-link")); + z.write("/etc/passwd".getBytes(StandardCharsets.UTF_8)); // the classic symlink payload + z.closeEntry(); + } + svc.restore("demo", new ByteArrayInputStream(evil.toByteArray())); + + Path extracted = siteDir.resolve("passwd-link"); + assertFalse(Files.isSymbolicLink(extracted), "the restore never creates a symlink from an archive entry"); + assertTrue(Files.isRegularFile(extracted, java.nio.file.LinkOption.NOFOLLOW_LINKS), + "the entry became a regular file"); + assertEquals("/etc/passwd", read(extracted), "…holding the literal bytes, harmless"); + } + + @Test + void restoreRefusesWhenTheWorkRootIsRedirectedBySymlink(@TempDir Path escape) throws IOException { + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); // a valid backup of the live site + + // Simulate a local attacker who redirected the restore-work root at a symlink to an out-of-tree dir + // (the TOCTOU window between the work-dir delete and re-create). Extraction must never follow it. + Path workRoot = layout.sites().resolve(BackupService.WORK_DIR); + try { + Files.createSymbolicLink(workRoot, escape); + } catch (UnsupportedOperationException | IOException noSymlinks) { + org.junit.jupiter.api.Assumptions.abort("filesystem does not support symlinks"); + } + + assertThrows(IOException.class, + () -> svc.restore("demo", new ByteArrayInputStream(archive.toByteArray())), + "a symlink-redirected work root is refused before any entry is extracted"); + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the live site is untouched"); + assertFalse(Files.exists(escape.resolve("demo").resolve("staging").resolve("site")), + "no backup content escaped into the symlink target"); + } + + @Test + void aNonPositiveCapFallsBackToTheDefaultInsteadOfRejectingEveryEntry() throws IOException { + // A misconfigured cap of 0 must NOT reject every entry (which would break all restores) — it falls back + // to the 256 MiB default, so a normal small backup still restores. + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + try (ZipOutputStream z = new ZipOutputStream(archive)) { + z.putNextEntry(new ZipEntry("manifest.yml")); + z.write("siteId: demo\nparticipants: []\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/site.yml")); + z.write("id: demo\nname: Demo\n".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + z.putNextEntry(new ZipEntry("site/templates/_master.html")); + z.write("RESTORED".getBytes(StandardCharsets.UTF_8)); + z.closeEntry(); + } + withEntryCap(0).restore("demo", new ByteArrayInputStream(archive.toByteArray())); + assertEquals("RESTORED", read(siteDir.resolve("templates/_master.html")), + "a 0 cap behaves as the default, not reject-all"); + } + + @Test + void aSymlinkInsideTheSiteFolderIsNotArchived() throws IOException { + Path secret = external.resolve("outside-secret.txt"); + Files.writeString(secret, "TOP_SECRET", StandardCharsets.UTF_8); + Path link = siteDir.resolve("templates/leak.html"); + try { + Files.createSymbolicLink(link, secret); + } catch (UnsupportedOperationException | IOException unsupported) { + return; // filesystem without symlink support — nothing to prove here + } + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive.toByteArray()))) { + ZipEntry e; + while ((e = zip.getNextEntry()) != null) { + assertFalse(e.getName().endsWith("leak.html"), "a symlink must never be followed into a backup"); + } + } + } + + @Test + void createFromBackupClonesTheContentUnderANewIdentity() throws IOException { + SiteStore store = new SiteStore(layout, new YamlStore()); + store.save(new Site("src", "Source", List.of("src.test"), Locale.ENGLISH, + List.of(Locale.ENGLISH), "https://src.test", SiteStatus.ACTIVE)); + write(layout.siteDir("src").resolve("templates/home.html"), "SRC_CONTENT"); + + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("src", archive); + + Site created = svc.createFromBackup("clone", "Cloned", List.of("clone.test"), + new ByteArrayInputStream(archive.toByteArray())); + + assertEquals("clone", created.id()); + assertEquals("Cloned", created.name()); + assertEquals(List.of("clone.test"), created.hosts()); + assertEquals(Locale.ENGLISH, created.defaultLocale(), "locale carried over from the backup"); + assertEquals("SRC_CONTENT", read(layout.siteDir("clone").resolve("templates/home.html")), "content cloned"); + // site.yml was rewritten to the new id (a fresh reader sees 'clone', not 'src'). + assertEquals("clone", new SiteStore(layout, new YamlStore()).find("clone").orElseThrow().id()); + // The source site is untouched. + assertTrue(Files.isRegularFile(layout.siteDir("src").resolve("site.yml"))); + } + + @Test + void createFromBackupRollsBackAnInvalidBackupLeavingNoOrphan() throws IOException { + // A site.yml that is a regular file (passes the archive check) but does not deserialize to a Site + // (no defaultLocale) — the failure happens AFTER the swap, so the half-created folder must be undone. + write(layout.siteDir("broken").resolve("site.yml"), "id: broken\nname: Broken\n"); + write(layout.siteDir("broken").resolve("templates/home.html"), "X"); + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("broken", archive); + + assertThrows(RuntimeException.class, () -> svc.createFromBackup("fresh", "F", List.of(), + new ByteArrayInputStream(archive.toByteArray()))); + assertFalse(new SiteStore(layout, new YamlStore()).exists("fresh"), "no orphan site remains after rollback"); + assertFalse(Files.exists(layout.siteDir("fresh")), "the half-created folder was removed"); + } + + @Test + void createFromBackupRefusesAHostAnotherSiteAnswersOnBeforeStagingAnything() throws IOException { + SiteStore store = new SiteStore(layout, new YamlStore()); + store.save(new Site("src", "Source", List.of("src.test"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("src", archive); + + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, + () -> svc.createFromBackup("clone", "C", List.of("SRC.test"), + new ByteArrayInputStream(archive.toByteArray()))); + assertTrue(ex.getMessage().contains("src"), ex.getMessage()); + assertFalse(Files.exists(layout.siteDir("clone")), "nothing was staged"); + assertThrows(IllegalArgumentException.class, () -> svc.createFromBackup("clone", "C", + List.of("bad host"), new ByteArrayInputStream(archive.toByteArray())), "a malformed host too"); + } + + @Test + void aRestoreDropsOnlyTheHostsAnotherSiteWasGivenSinceTheBackup() throws IOException { + SiteStore store = new SiteStore(layout, new YamlStore()); + store.save(new Site("a", "A", List.of("a.test", "moved.test"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("a", archive); + + // After the backup, moved.test leaves site a for site b. + store.save(store.find("a").orElseThrow().withHosts(List.of("a.test"))); + store.save(new Site("b", "B", List.of("moved.test"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + + svc.restore("a", new ByteArrayInputStream(archive.toByteArray())); + + SiteStore fresh = new SiteStore(layout, new YamlStore()); + assertEquals(List.of("a.test"), fresh.find("a").orElseThrow().hosts(), "the host b answers on is dropped"); + assertEquals(List.of("moved.test"), fresh.find("b").orElseThrow().hosts(), "b keeps it"); + } + + @Test + void createFromBackupRejectsAnExistingId() throws IOException { + new SiteStore(layout, new YamlStore()).save(new Site("src", "Source", List.of(), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("src", archive); + // 'demo' already exists (seeded in setUp) — creating over it must be refused. + assertThrows(IllegalStateException.class, () -> svc.createFromBackup("demo", "X", List.of(), + new ByteArrayInputStream(archive.toByteArray()))); + } + + @Test + void transientLogsAndStatsAreExcludedFromTheBackup() throws IOException { + write(siteDir.resolve("logs/access-2026-07-02.log"), "SECRET-TRAFFIC"); + write(siteDir.resolve("stats/bandwidth.csv"), "1,2,3"); + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); + + boolean sawContent = false; + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive.toByteArray()))) { + ZipEntry e; + while ((e = zip.getNextEntry()) != null) { + String name = e.getName(); + assertFalse(name.contains("/logs/") || name.contains("/stats/"), + "transient logs/stats must never ride the content backup: " + name); + sawContent |= name.endsWith("site.yml"); + } + } + assertTrue(sawContent, "real site content is still archived"); + } + + // ---- a restore must not make every page look edited today ------------------------------------ + + /** + * A restored file keeps its original modification time. + * + *

A page's {@code } in the sitemap derives from its mtime, so a restore that stamped + * everything "now" told every search engine the whole site had just been rewritten — falsifying the one + * signal a sitemap exists to give, through an operation that changed no content at all. It also made a + * restored site look freshly edited in the console's own listings. + * + *

The mtime is set a year back rather than merely "different", so the assertion cannot pass by + * accident on a fast machine where "now" and "then" land in the same second, and the tolerance covers the + * two-second granularity a ZIP timestamp can have. + */ + @Test + void aRestoredFileKeepsItsOriginalModificationTime() throws IOException { + Path master = siteDir.resolve("templates/_master.html"); + FileTime original = FileTime.from(Instant.parse("2025-03-04T10:15:30Z")); + Files.setLastModifiedTime(master, original); + + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); + write(master, "MASTER_BROKEN"); // touches the file, stamping it "now" + svc.restore("demo", new ByteArrayInputStream(archive.toByteArray())); + + long drift = Math.abs(Files.getLastModifiedTime(master).toMillis() - original.toMillis()); + assertEquals("MASTER_V1", read(master), "content restored"); + assertTrue(drift <= 2000L, "restored mtime drifted by " + drift + " ms — a restore is not an edit"); + } + + /** + * The times must be right at the moment the site becomes visible, not fixed up afterwards. + * + *

Restoring and then correcting would leave a window in which the site is live and advertising itself + * as freshly rewritten — short, but a crawler mid-fetch does not know that. Checked by asserting the + * whole restored tree, so no file is left behind by a path that writes outside the staged copy. + */ + @Test + void everyRestoredFileKeepsItsTimeNotJustTheOneWeLookedAt() throws IOException { + FileTime original = FileTime.from(Instant.parse("2025-03-04T10:15:30Z")); + for (Path file : List.of(siteDir.resolve("site.yml"), siteDir.resolve("templates/_master.html"), + siteDir.resolve("users.yml"))) { + Files.setLastModifiedTime(file, original); + } + + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); + Files.delete(siteDir.resolve("users.yml")); + svc.restore("demo", new ByteArrayInputStream(archive.toByteArray())); + + try (var walk = Files.walk(siteDir)) { + for (Path file : walk.filter(Files::isRegularFile).toList()) { + long drift = Math.abs(Files.getLastModifiedTime(file).toMillis() - original.toMillis()); + assertTrue(drift <= 2000L, file + " came back stamped now (drift " + drift + " ms)"); + } + } + } + + /** + * An archive whose entry times are absent or implausible still restores. + * + *

Every archive written before this change carries the time the backup ran rather than the + * file's own, and one produced by another tool may carry the DOS epoch or nothing usable at all. A + * cosmetic freshness signal is not worth an operator's data recovery, so the restore proceeds and the + * file takes whatever time the archive offers. + * + *

Built by rewriting a REAL archive's entry times rather than hand-assembling one, so the manifest and + * layout stay exactly what the restore path expects and the test isolates the timestamp variable alone. + */ + @Test + void anArchiveWithImplausibleEntryTimesStillRestores() throws IOException { + ByteArrayOutputStream original = new ByteArrayOutputStream(); + svc.backup("demo", original); + + ByteArrayOutputStream retimed = new ByteArrayOutputStream(); + try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(original.toByteArray())); + ZipOutputStream out = new ZipOutputStream(retimed)) { + ZipEntry entry; + while ((entry = in.getNextEntry()) != null) { + ZipEntry copy = new ZipEntry(entry.getName()); + copy.setTime(0L); // the DOS epoch — as far from plausible as a ZIP allows + out.putNextEntry(copy); + in.transferTo(out); + out.closeEntry(); + } + } + + write(siteDir.resolve("templates/_master.html"), "MASTER_BROKEN"); + svc.restore("demo", new ByteArrayInputStream(retimed.toByteArray())); + + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), + "the data recovery is what matters; the timestamp is a bonus"); + } + + // --- an export failure fails the backup and names the participant; an import failure is contained -- + + private static BackupParticipant failing(boolean onExport, RuntimeException failure) { + return new BackupParticipant() { + @Override + public String key() { + return "broken"; + } + + @Override + public void export(BackupWriter out, SiteRef site) { + if (onExport) { + throw failure; + } + } + + @Override + public void importInto(BackupReader in, SiteRef site) { + throw failure; + } + }; + } + + @Test + void aParticipantExportFailureFailsTheWholeBackupAndNamesTheParticipant() { + BackupService broken = new BackupService(layout, new SiteStore(layout, new YamlStore()), + new BackupParticipantRegistry(List.of(fake, failing(true, new IllegalStateException("disk gone")))), + event -> { }); + IOException failure = org.junit.jupiter.api.Assertions.assertThrows(IOException.class, + () -> broken.backup("demo", new ByteArrayOutputStream())); + assertTrue(failure.getMessage().contains("participant 'broken'"), failure.getMessage()); + assertTrue(failure.getMessage().contains("disk gone"), failure.getMessage()); + } + + @Test + void aParticipantImportFailureIsContainedAndTheOthersStillImport() throws IOException { + ByteArrayOutputStream archive = new ByteArrayOutputStream(); + svc.backup("demo", archive); + mx.quest.runway.plugin.ContributionGuard guard = mx.quest.runway.plugin.ContributionGuard.standalone(); + BackupService mixed = new BackupService(layout, new SiteStore(layout, new YamlStore()), + new BackupParticipantRegistry(List.of(failing(false, new IllegalStateException("bad import")), fake), + guard), event -> { }); + fake.imported = null; + write(siteDir.resolve("templates/_master.html"), "MASTER_BROKEN"); + + mixed.restore("demo", new ByteArrayInputStream(archive.toByteArray())); + + assertEquals("MASTER_V1", read(siteDir.resolve("templates/_master.html")), "the site files are restored"); + assertEquals("PLUGIN_STATE_V1", fake.imported, "the next participant still imports"); + assertEquals(1, guard.health("kernel").failures(), "the failure is recorded under the containment policy"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/DemoExportRestoreTest.java b/runway-app/src/test/java/mx/quest/runway/backup/DemoExportRestoreTest.java new file mode 100644 index 0000000..2bcd2cd --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/DemoExportRestoreTest.java @@ -0,0 +1,282 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Stream; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIf; +import org.junit.jupiter.api.io.TempDir; + +/** + * Restores the real published demo-site exports through the real {@link BackupService}. + * + *

Why this exists

+ * The retired demo sites were packaged as downloadable site backups, with the archive format built from + * observation of a genuine console-produced backup. The packaging was verified structurally, but no restore + * could be run without application-superadmin credentials. That left exactly one unverified claim, and it is the one + * that matters most to + * whoever downloads the file: does it actually restore? + * + *

Structural inspection cannot answer that. Only feeding the bytes to the real restore path can. + * + *

This test also independently re-checks the sanitisation claims against the shipped + * bytes, because "we removed the secrets" is precisely the kind of assertion that should not be taken on + * trust when the artifact is about to be published publicly — and a scanner used on them had once + * silently checked nothing and reported clean. + * + *

Conditional by design

+ * The exports live outside the repository (they are large binaries). Their directory is named by the + * {@code runway.demo-exports} system property, and this skips when it is unset or holds no export rather + * than failing. A skipped test is honest; a test that cannot run and says + * nothing is not, so the condition is named and the reason is visible in the report. + */ +class DemoExportRestoreTest { + + /** The directory holding the published exports, from {@code -Drunway.demo-exports=}; null when unset. */ + private static final Path EXPORTS = pathProperty("runway.demo-exports"); + + /** + * A host the exports must never point back at (the exporting installation's own domain), from + * {@code -Drunway.demo-exports.forbidden-host=}; null when unset, and the check is then skipped. + */ + private static final String FORBIDDEN_HOST = stringProperty("runway.demo-exports.forbidden-host"); + + private static String stringProperty(String name) { + String value = System.getProperty(name); + return value == null || value.isBlank() ? null : value.trim(); + } + + private static Path pathProperty(String name) { + String value = stringProperty(name); + return value == null ? null : Path.of(value); + } + + static boolean exportsPresent() { + return EXPORTS != null && hasExports(EXPORTS); + } + + /** + * Whether {@code dir} holds at least one published export. + * + *

Extracted from {@link #exportsPresent()} so the GATE itself can be tested against a temporary + * directory. The previous "guard the guard" test compared the {@code EXPORTS} constant to a copy of its + * own literal, which fails only if someone edits one and not the other — it could not detect the case its + * own javadoc named. + */ + static boolean hasExports(Path dir) { + if (!Files.isDirectory(dir)) { + return false; + } + try (Stream files = Files.list(dir)) { + return files.anyMatch(p -> p.getFileName().toString().endsWith(".zip")); + } catch (IOException unreadable) { + return false; + } + } + + private static List listExports() { + if (EXPORTS == null || !Files.isDirectory(EXPORTS)) { + return List.of(); + } + try (Stream files = Files.list(EXPORTS)) { + return files.filter(p -> p.getFileName().toString().endsWith(".zip")).sorted().toList(); + } catch (IOException e) { + return List.of(); + } + } + + /** A service over a throwaway external tree, with the target site pre-created (restore is a swap). */ + private record Fixture(BackupService service, StorageLayout layout) { + } + + private static Fixture fixture(Path external, String siteId) throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + props.setBackups(external.resolve("backups")); + StorageLayout layout = StorageLayout.from(props); + Path siteDir = layout.siteDir(siteId); + Files.createDirectories(siteDir); + // Restore is a destructive swap over an existing site, so stand up a minimal one to swap. + Files.writeString(siteDir.resolve("site.yml"), "id: " + siteId + "\nname: Placeholder\n", + StandardCharsets.UTF_8); + BackupService service = new BackupService(layout, new SiteStore(layout, new YamlStore()), + new BackupParticipantRegistry(List.of()), event -> { }); + return new Fixture(service, layout); + } + + private static String siteIdOf(Path zip) { + // runway-demo--.zip + String name = zip.getFileName().toString(); + return name.replaceFirst("^runway-demo-", "").replaceFirst("-\\d{8}-\\d{6}Z\\.zip$", ""); + } + + /** + * The claim the packaging could not verify: each published export restores through the real service and lands + * a renderable site — a master template, a routable home page, and its own {@code site.yml}. + */ + @Test + @EnabledIf("exportsPresent") + void everyPublishedExportRestoresIntoARenderableSite(@TempDir Path external) throws IOException { + for (Path zip : listExports()) { + String siteId = siteIdOf(zip); + Path root = external.resolve(siteId); + Fixture f = fixture(root, siteId); + + try (InputStream in = Files.newInputStream(zip)) { + f.service().restore(siteId, in); // the real path — throws if the archive is not valid + } + + Path site = f.layout().siteDir(siteId); + assertTrue(Files.isRegularFile(site.resolve("site.yml")), siteId + ": site.yml restored"); + assertTrue(Files.isRegularFile(site.resolve("templates/_master.html")), + siteId + ": a master template restored — without it the site cannot render"); + assertTrue(Files.isRegularFile(site.resolve("templates/index.meta.yml")), + siteId + ": a routable home page restored"); + assertFalse(Files.readString(site.resolve("site.yml"), StandardCharsets.UTF_8).contains("Placeholder"), + siteId + ": the restore actually replaced the pre-existing site, rather than merging into it"); + } + } + + /** + * Re-verifies the exports' sanitisation against the shipped bytes. + * + *

Not distrust — the same discipline applied to the scanner that checked them. These artifacts are about to be + * published publicly, and the cost of being wrong is a leaked live credential, so the claim is worth + * confirming from a second implementation. + */ + @Test + @EnabledIf("exportsPresent") + void noPublishedExportCarriesASecretOrOurOwnHostnames(@TempDir Path external) throws IOException { + for (Path zip : listExports()) { + String siteId = siteIdOf(zip); + Path root = external.resolve(siteId); + Fixture f = fixture(root, siteId); + try (InputStream in = Files.newInputStream(zip)) { + f.service().restore(siteId, in); + } + Path site = f.layout().siteDir(siteId); + + try (Stream files = Files.walk(site)) { + for (Path file : files.filter(Files::isRegularFile).toList()) { + String body = readTextOrEmpty(file); + String where = siteId + ":" + site.relativize(file); + assertFalse(body.contains("ENC("), where + " carries an encrypted-secret marker"); + if (FORBIDDEN_HOST != null) { + assertFalse(body.contains(FORBIDDEN_HOST), where + " points back at " + FORBIDDEN_HOST); + } + } + } + + // The protection config must be present but neutered — absent would silently re-enable defaults. + Path protection = site.resolve("plugins/protection.yml"); + if (Files.isRegularFile(protection)) { + for (String line : Files.readAllLines(protection)) { + assertFalse(carriesPopulatedKey(line), + siteId + ": a populated credential survived sanitisation: " + line.trim()); + } + } + + // Hostnames must be neutral, or a downloader's install answers on the exporting installation's domain. + String siteYml = Files.readString(site.resolve("site.yml"), StandardCharsets.UTF_8); + assertTrue(siteYml.contains("example.com") || !siteYml.contains("hosts"), + siteId + ": hosts were not neutralised: " + siteYml); + } + } + + /** Logs/stats are traffic data and must never travel in a published artifact. */ + @Test + @EnabledIf("exportsPresent") + void noPublishedExportCarriesTrafficData(@TempDir Path external) throws IOException { + for (Path zip : listExports()) { + String siteId = siteIdOf(zip); + Path root = external.resolve(siteId); + Fixture f = fixture(root, siteId); + try (InputStream in = Files.newInputStream(zip)) { + f.service().restore(siteId, in); + } + Path site = f.layout().siteDir(siteId); + for (String dir : List.of("logs", "stats")) { + Path d = site.resolve(dir); + assertFalse(Files.isDirectory(d) && !isEmptyDir(d), siteId + ": " + dir + "/ travelled in the export"); + } + } + } + + private static boolean isEmptyDir(Path dir) throws IOException { + try (Stream s = Files.list(dir)) { + return s.findAny().isEmpty(); + } + } + + private static String readTextOrEmpty(Path file) { + try { + byte[] bytes = Files.readAllBytes(file); + for (byte b : bytes) { // skip binaries (fonts, images) — they carry no config + if (b == 0) { + return ""; + } + } + return new String(bytes, StandardCharsets.UTF_8); + } catch (IOException e) { + return ""; + } + } + + /** + * Whether a YAML line assigns a NON-EMPTY value to a credential field. + * + *

Written carefully because the naive version was wrong in the direction that matters: matching + * {@code siteKey:\s*\S} treats {@code siteKey: ""} as populated, because the opening quote is a + * non-space character. That produced a false accusation of a leaked credential against a correctly + * sanitised artifact — the failure mode of a security check that cries wolf, which ends with the check + * being ignored. + */ + static boolean carriesPopulatedKey(String line) { + String trimmed = line.trim(); + if (trimmed.startsWith("#")) { + return false; // prose may name the fields while explaining them + } + int colon = trimmed.indexOf(':'); + if (colon < 0) { + return false; + } + String key = trimmed.substring(0, colon).trim().toLowerCase(java.util.Locale.ROOT).replace("-", ""); + if (!key.equals("sitekey") && !key.equals("secretkey")) { + return false; + } + String value = trimmed.substring(colon + 1).trim(); + if (value.length() >= 2 && (value.startsWith("\"") || value.startsWith("'"))) { + value = value.substring(1, value.length() - 1); // strip the quotes before judging emptiness + } + return !value.isBlank(); + } + + /** + * The positive control: proves the credential check can actually produce a finding. + * + *

Added because a pre-publication scanner once spent its first hour checking + * nothing and reporting clean — an unbalanced {@code grep -E} pattern errored, and the shell read that as + * "not found". A security check that has never been seen to fail is indistinguishable from one that + * cannot fail. + */ + @Test + void theCredentialCheckCanProduceAFinding() { + assertTrue(carriesPopulatedKey(" siteKey: \"6LcSomeRealLookingKey\""), "must flag a populated key"); + assertTrue(carriesPopulatedKey(" secret-key: ENC(abc123)"), "must flag an encrypted secret"); + assertFalse(carriesPopulatedKey(" siteKey: \"\""), "an emptied key is sanitised, not a finding"); + assertFalse(carriesPopulatedKey(" secretKey: ''"), "…including single-quoted"); + assertFalse(carriesPopulatedKey(" siteKey:"), "…and a bare key with no value"); + assertFalse(carriesPopulatedKey("# set siteKey: your-key-here"), "prose explaining the field is not a leak"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/ScheduledAndOffsiteBackupTest.java b/runway-app/src/test/java/mx/quest/runway/backup/ScheduledAndOffsiteBackupTest.java new file mode 100644 index 0000000..ad3f4ee --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/ScheduledAndOffsiteBackupTest.java @@ -0,0 +1,115 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Off-host backup mirroring (+ its retention) and the scheduled all-sites runner. */ +class ScheduledAndOffsiteBackupTest { + + @TempDir + Path external; + @TempDir + Path offsite; + private StorageLayout layout; + private SiteStore sites; + + @BeforeEach + void setUp() throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + props.setBackups(external.resolve("backups")); + layout = StorageLayout.from(props); + sites = new SiteStore(layout, new YamlStore()); + seedSite("demo"); + } + + private void seedSite(String id) throws IOException { + Path siteDir = layout.siteDir(id); + Files.createDirectories(siteDir.resolve("templates")); + Files.writeString(siteDir.resolve("templates/_master.html"), "MASTER", StandardCharsets.UTF_8); + sites.save(new Site(id, id, List.of(id + ".test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null, + SiteStatus.ACTIVE)); + } + + private BackupService service(String offsiteDir, int maxCount) { + BackupProperties props = new BackupProperties(); + props.setOffsiteDir(offsiteDir); + props.getRetention().setMaxCount(maxCount); + return new BackupService(layout, sites, new BackupParticipantRegistry(List.of()), event -> { }, props); + } + + @Test + void aCreatedBackupIsMirroredOffHost() throws IOException { + BackupService svc = service(offsite.toString(), 0); + String name = svc.create("demo"); + + assertTrue(Files.exists(external.resolve("backups").resolve("demo").resolve(name)), "local copy exists"); + assertTrue(Files.exists(offsite.resolve("demo").resolve(name)), "off-host copy exists"); + } + + @Test + void offHostCopiesArePrunedByRetention() throws IOException { + // Seed three older off-host copies by hand, then create one under maxCount=2. + Path offDir = offsite.resolve("demo"); + Files.createDirectories(offDir); + for (int i = 1; i <= 3; i++) { + Files.writeString(offDir.resolve("backup-20260101-00000" + i + "-000.zip"), "OLD"); + } + BackupService svc = service(offsite.toString(), 2); + svc.create("demo"); + + long remaining; + try (var s = Files.list(offDir)) { + remaining = s.filter(p -> p.getFileName().toString().endsWith(".zip")).count(); + } + assertEquals(2, remaining, "off-host copies are capped at maxCount (newest kept)"); + } + + @Test + void anUnwritableOffHostTargetDoesNotFailTheLocalBackup() throws IOException { + // Point the off-host dir under an existing regular FILE, so createDirectories cannot succeed. + Path blocker = external.resolve("a-file"); + Files.writeString(blocker, "x"); + BackupService svc = service(blocker.resolve("nope").toString(), 0); + + String name = svc.create("demo"); // must not throw + assertTrue(Files.exists(external.resolve("backups").resolve("demo").resolve(name)), + "the local backup still succeeds when the off-host mirror fails"); + } + + @Test + void withNoOffHostConfiguredNothingIsMirrored() throws IOException { + BackupService svc = service("", 0); + svc.create("demo"); + assertTrue(Files.list(offsite).findAny().isEmpty(), "off-host dir untouched when unconfigured"); + } + + @Test + void theScheduledRunnerBacksUpEverySite() throws IOException { + seedSite("blog"); + BackupService svc = service("", 0); + ScheduledBackupRunner runner = new ScheduledBackupRunner(svc, sites); + + int ok = runner.runAll(); + + assertEquals(2, ok, "both sites were backed up"); + assertEquals(1, svc.list("demo").size()); + assertEquals(1, svc.list("blog").size()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/TransferExportTest.java b/runway-app/src/test/java/mx/quest/runway/backup/TransferExportTest.java new file mode 100644 index 0000000..ee81ea6 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/TransferExportTest.java @@ -0,0 +1,393 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import mx.quest.runway.plugin.LoadedPlugin; +import mx.quest.runway.plugin.PluginDescriptor; +import mx.quest.runway.plugin.PluginSettingDef; +import mx.quest.runway.plugin.RunningPlugins; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * The transfer archive: the same site with everything that must not leave the building taken out. + * + *

Why this exists

+ * A backup has to be complete or it is not a backup — sub-users and their password hashes, per-plugin + * credentials, the hostnames the site answers on. A hand-over has the opposite requirement, and until now the + * two were the same click: anyone who attached a site backup to a bug report, handed one to a + * contractor, or published one as an example was shipping live secrets and had no way to tell. + * + *

Verified against the archive BYTES rather than against the sanitiser's inputs. A sanitiser is trusted the + * moment it exists, so the only assertion worth making is the one a recipient could make: open the file, and + * look for the secret. + */ +class TransferExportTest { + + private static final String RECAPTCHA_SECRET = "ENC(AbCdEf0123456789)"; + private static final String RECAPTCHA_SITE_KEY = "6LcRealLookingSiteKey"; + + @TempDir + Path external; + private StorageLayout layout; + private Path siteDir; + private BackupService svc; + + @BeforeEach + void setUp() throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + props.setBackups(external.resolve("backups")); + layout = StorageLayout.from(props); + siteDir = layout.siteDir("acme"); + + write(siteDir.resolve("site.yml"), + "id: acme\nname: Acme\nhosts:\n - acme.example-real.test\n - www.acme.example-real.test\n" + + "baseUrl: https://acme.example-real.test\n"); + write(siteDir.resolve("templates/_master.html"), "MASTER"); + write(siteDir.resolve("templates/index.html"), "

public content

"); + write(siteDir.resolve("users.yml"), + "- username: editor\n passwordHash: $argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA\n"); + write(siteDir.resolve("permissions.yml"), "users:\n editor:\n grant: [EDIT_PAGES]\n"); + write(siteDir.resolve("bandwidth.csv"), "2026-08-01,12345\n"); + // The FLAT shape the generic per-site settings form writes (dotted top-level keys). + write(siteDir.resolve("plugins/someplugin.yml"), + "captcha.provider: recaptcha\ncaptcha.site-key: " + RECAPTCHA_SITE_KEY + "\n" + + "captcha.secret-key: " + RECAPTCHA_SECRET + "\nlogin.max-attempts: 5\n"); + // The NESTED shape the bundled protection plugin actually writes — copied from a real production + // export, not invented here. Getting this wrong is what made the first version of these tests + // vacuous: they only ever exercised the one layout the sanitiser happened to handle. + write(siteDir.resolve("plugins/protection.yml"), + "honeypotEnabled: true\ncaptcha:\n enabled: true\n provider: \"recaptcha-v2\"\n" + + " siteKey: \"" + RECAPTCHA_SITE_KEY + "\"\n" + + " secretKey: \"" + RECAPTCHA_SECRET + "\"\n scoreThreshold: 0.5\n"); + + svc = new BackupService(layout, new SiteStore(layout, new YamlStore()), + new BackupParticipantRegistry(List.of()), event -> { }, new BackupProperties(), + pluginDeclaring("someplugin", "captcha.secret-key", "captcha.site-key")); + } + + private static void write(Path file, String content) throws IOException { + Files.createDirectories(file.getParent()); + Files.writeString(file, content, StandardCharsets.UTF_8); + } + + /** + * A running-plugin set with ONE plugin declaring the given keys as secrets. + * + *

Note what is deliberately absent: no descriptor for {@code protection}. That mirrors the product — + * the bundled protection plugin declares no {@code siteSettings} block at all and persists its own nested + * record — so every assertion about {@code protection.yml} below is exercising the schema-less path, + * which is the one that leaked. + */ + private RunningPlugins pluginDeclaring(String pluginId, String... secretKeys) { + List siteSettings = java.util.Arrays.stream(secretKeys) + .map(key -> new PluginSettingDef(key, "secret", null, null, null)) + .toList(); + PluginDescriptor descriptor = new PluginDescriptor(pluginId, pluginId, "1.0.0", null, + true, false, List.of(), List.of(), List.of(), List.of(), siteSettings, Map.of(), + List.of(), List.of(), null); + LoadedPlugin plugin = new LoadedPlugin(descriptor, external.resolve("plugins/" + pluginId)); + return () -> List.of(plugin); + } + + /** Every entry of an archive, by name. */ + private static Map entries(byte[] archive) throws IOException { + Map out = new HashMap<>(); + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive))) { + ZipEntry entry; + while ((entry = zip.getNextEntry()) != null) { + out.put(entry.getName(), new String(zip.readAllBytes(), StandardCharsets.UTF_8)); + } + } + return out; + } + + private byte[] archive(BackupService.BackupPurpose purpose) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + svc.backup("acme", out, purpose); + return out.toByteArray(); + } + + /** + * The assertion a recipient could make: unpack the archive and search every file for the secret. + * + *

Over the decompressed entries, not the archive bytes. Scanning the raw {@code .zip} for a + * plaintext needle is a test that cannot fail: ZIP deflates its entries, so the secret is not literally + * present even when it is fully there. That version of this test passed with the sanitiser switched off — + * caught by disabling the sanitiser and seeing which tests noticed, which is the only reliable way to + * find a check that is quietly asserting nothing. + */ + @Test + void noSecretSurvivesAnywhereInATransferArchive() throws IOException { + Map files = entries(archive(BackupService.BackupPurpose.TRANSFER)); + + for (Map.Entry file : files.entrySet()) { + String where = file.getKey(); + assertFalse(file.getValue().contains(RECAPTCHA_SECRET), where + " carries the encrypted secret"); + assertFalse(file.getValue().contains("argon2id"), where + " carries a tenant password hash"); + } + assertFalse(files.isEmpty(), "an empty archive would pass every assertion above"); + + // The DECLARED-secret net, checked where it applies: the flat plugin declares its site key a secret, + // so that plugin's copy is blanked. The bundled protection plugin declares nothing and its site key + // is public by design, so it survives — see aPublicValueNamedKeyIsNotBlanked for why that is right, + // and the guide for what a recipient must therefore replace. + assertFalse(files.get("site/plugins/someplugin.yml").contains(RECAPTCHA_SITE_KEY), + "a DECLARED secret must be blanked whatever it is named"); + } + + /** …and the same search over an ordinary backup finds them, so the test above can actually fail. */ + @Test + void anOrdinaryBackupStillCarriesEverything() throws IOException { + Map files = entries(archive(BackupService.BackupPurpose.RESTORE)); + + assertTrue(files.get("site/plugins/protection.yml").contains(RECAPTCHA_SECRET), + "a backup that dropped this would not restore the site"); + assertTrue(files.get("site/plugins/someplugin.yml").contains(RECAPTCHA_SECRET), + "…in both config shapes"); + assertTrue(files.containsKey("site/users.yml"), "sub-users are part of the site"); + assertTrue(files.get("site/site.yml").contains("acme.example-real.test"), "so are its hostnames"); + } + + /** Accounts and grants are withheld: they are the recipient's biggest exposure and no use to them. */ + @Test + void aTransferArchiveOmitsAccountsGrantsAndTraffic() throws IOException { + Map files = entries(archive(BackupService.BackupPurpose.TRANSFER)); + + assertFalse(files.containsKey("site/users.yml")); + assertFalse(files.containsKey("site/permissions.yml")); + assertFalse(files.containsKey("site/bandwidth.csv"), "traffic history is the origin's business"); + } + + /** Content and presentation must survive, or the archive is not worth handing over. */ + @Test + void aTransferArchiveKeepsContentPresentationAndNonSecretSettings() throws IOException { + Map files = entries(archive(BackupService.BackupPurpose.TRANSFER)); + + assertEquals("

public content

", files.get("site/templates/index.html")); + assertEquals("MASTER", files.get("site/templates/_master.html")); + assertTrue(files.get("site/plugins/someplugin.yml").contains("login.max-attempts"), + "a non-secret setting is exactly what the recipient wants to inherit"); + assertTrue(files.get("site/plugins/protection.yml").contains("honeypotEnabled"), + "…and a nested plugin's non-secret settings survive too"); + } + + /** + * Secret keys are blanked, not deleted. + * + *

An absent key reads as a setting that does not exist; a blank one shows the recipient what has to be + * filled in before the feature works. + */ + @Test + void secretsAreBlankedRatherThanRemoved() throws IOException { + String flat = entries(archive(BackupService.BackupPurpose.TRANSFER)) + .get("site/plugins/someplugin.yml"); + + assertTrue(flat.contains("captcha.secret-key"), "the key stays so its absence is visible: " + flat); + assertTrue(flat.contains("captcha.site-key")); + } + + /** + * Hostnames are replaced with a reserved placeholder derived from the site id. + * + *

{@code example.com} is reserved for exactly this (RFC 2606), so a placeholder left in place by + * accident resolves nowhere rather than at somebody else's real domain — and deriving it from the id keeps + * two sites from the same installation from colliding when both are imported side by side. + */ + @Test + void hostnamesAreNeutralisedToAReservedPlaceholder() throws IOException { + String site = entries(archive(BackupService.BackupPurpose.TRANSFER)).get("site/site.yml"); + + assertFalse(site.contains("example-real.test"), "the origin's hostnames travelled: " + site); + assertTrue(site.contains("acme.example.com"), site); + assertTrue(site.contains("name: Acme") || site.contains("name: \"Acme\""), + "the site's own identity is not a secret: " + site); + } + + /** + * With no plugin schema available, an {@code ENC(...)} value is still blanked. + * + *

The safety net for the case the declaration cannot cover — the plugin is not installed here, or was + * renamed. An encrypted value is self-identifying, so a stored secret does not leave even with no schema + * at all. A sanitiser that is only as good as its inputs is not one you can hand someone. + */ + @Test + void anEncryptedValueIsBlankedEvenWithNoPluginSchema() throws IOException { + BackupService bare = new BackupService(layout, new SiteStore(layout, new YamlStore()), + new BackupParticipantRegistry(List.of()), event -> { }, new BackupProperties(), + (RunningPlugins) null); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bare.backup("acme", out, BackupService.BackupPurpose.TRANSFER); + + String flat = entries(out.toByteArray()).get("site/plugins/someplugin.yml"); + assertFalse(flat.contains(RECAPTCHA_SECRET), "an ENC(...) value must never travel: " + flat); + } + + /** The archive says which kind it is, so a restore (or a reader) is not left guessing. */ + @Test + void theManifestRecordsWhichKindOfArchiveThisIs() throws IOException { + assertTrue(entries(archive(BackupService.BackupPurpose.TRANSFER)).get("manifest.yml") + .contains("TRANSFER")); + assertTrue(entries(archive(BackupService.BackupPurpose.RESTORE)).get("manifest.yml") + .contains("RESTORE")); + } + + /** An unmarked archive reads as complete — never as sanitised, which would be the dangerous default. */ + @Test + void anArchiveWithNoPurposeReadsAsAFullBackup() { + BackupManifest old = new BackupManifest("acme", "0.3.4", "2026-01-01T00:00:00Z", List.of()); + + assertFalse(old.isTransfer(), "an archive from before the distinction existed is a full backup"); + assertEquals("RESTORE", old.purpose()); + } + + /** A transfer archive still restores — it is the ordinary format, just with less in it. */ + @Test + void aTransferArchiveRestoresIntoARenderableSite() throws IOException { + byte[] transfer = archive(BackupService.BackupPurpose.TRANSFER); + write(siteDir.resolve("templates/index.html"), "CLOBBERED"); + + svc.restore("acme", new ByteArrayInputStream(transfer)); + + assertEquals("

public content

", + Files.readString(siteDir.resolve("templates/index.html"), StandardCharsets.UTF_8)); + assertFalse(Files.exists(siteDir.resolve("users.yml")), + "the accounts were never in the archive, so the restore has none to put back"); + } + + // ---- the nested shape: the one the bundled protection plugin actually writes -------------------- + + /** + * The defect these tests were written to prevent and did not: a plugin that stores NESTED config, with + * no declared schema, had its secret copied into the transfer archive verbatim. + * + *

{@code protection} is not a hypothetical — it is the bundled, always-installed plugin, it declares + * no {@code siteSettings} block at all, and it persists {@code captcha:} → {@code secretKey: ENC(...)} + * one level down. The original sanitiser walked only top-level entries, so it saw {@code honeypotEnabled} + * (a Boolean) and {@code captcha} (a Map), matched neither, and returned "nothing to change". + * + *

The fixture above is the shape taken from a real production export, not one invented for the test. + * That is the whole lesson: the first version of this suite passed because its fixture was written by the + * same hand, and in the same shape, as the code it was checking. + */ + @Test + void aNestedPluginConfigHasItsSecretBlankedToo() throws IOException { + String protection = entries(archive(BackupService.BackupPurpose.TRANSFER)) + .get("site/plugins/protection.yml"); + + assertFalse(protection.contains(RECAPTCHA_SECRET), + "the bundled plugin's encrypted CAPTCHA secret travelled: " + protection); + assertTrue(protection.contains("secretKey"), "the key stays so the recipient sees what to fill in"); + assertTrue(protection.contains("honeypotEnabled: true"), "non-secret settings still travel"); + } + + /** + * A secret stored in PLAINTEXT, in a plugin that declares nothing, is still caught. + * + *

Neither the declaration net nor the {@code ENC(} net can see this one, so it is covered by the key + * NAME. The word list is short and unambiguous on purpose — see the next test for the other half. + */ + @Test + void aPlaintextSecretInAnUndeclaredPluginIsCaughtByItsName() throws IOException { + write(siteDir.resolve("plugins/mailer.yml"), + "smtp:\n host: mail.example-real.test\n username: postmaster\n" + + " password: hunter2-in-the-clear\n apiToken: tok_live_abcdef\n"); + + String mailer = entries(archive(BackupService.BackupPurpose.TRANSFER)).get("site/plugins/mailer.yml"); + + assertFalse(mailer.contains("hunter2-in-the-clear"), mailer); + assertFalse(mailer.contains("tok_live_abcdef"), mailer); + assertTrue(mailer.contains("postmaster"), "a username is not a credential and must survive"); + assertTrue(mailer.contains("mail.example-real.test"), "…nor is a hostname inside a plugin's config"); + } + + /** + * A public value whose name merely contains "key" is NOT blanked. + * + *

The other half of the name heuristic, and the reason {@code key} is not in the word list: a + * reCAPTCHA site key is public by design — it is embedded in the page markup — and blanking a + * working setting is its own kind of harm. A sanitiser that silently breaks the recipient's site is not + * one anybody keeps using. + */ + @Test + void aPublicValueNamedKeyIsNotBlanked() throws IOException { + String protection = entries(archive(BackupService.BackupPurpose.TRANSFER)) + .get("site/plugins/protection.yml"); + + assertTrue(protection.contains(RECAPTCHA_SITE_KEY), + "siteKey is public (it ships in the page); blanking it would break the recipient for nothing: " + + protection); + } + + /** A secret nested inside a LIST of maps is reached as well. */ + @Test + void aSecretInsideAListOfMapsIsAlsoBlanked() throws IOException { + write(siteDir.resolve("plugins/webhooks.yml"), + "endpoints:\n - name: billing\n url: https://example-real.test/hook\n" + + " secret: whsec_do_not_ship\n - name: audit\n url: https://example-real.test/a\n"); + + String hooks = entries(archive(BackupService.BackupPurpose.TRANSFER)).get("site/plugins/webhooks.yml"); + + assertFalse(hooks.contains("whsec_do_not_ship"), hooks); + assertTrue(hooks.contains("billing"), "the rest of the entry survives"); + } + + /** + * A transfer copy carried {@code templates/.pending//review.yml} — the + * submitter's and returner's account names (often email addresses) and the reviewer's note — although it drops + * {@code users.yml}. The whole pending subtree (unpublished drafts too) now stays home, and the manifest says + * so; a full backup keeps all of it, so a restore brings the review queue back. + */ + @Test + void aTransferCopyLeavesOutPendingEditorialWorkAndSaysSo() throws IOException { + write(siteDir.resolve("templates/.pending/about/review.yml"), + "state: RETURNED\nsubmittedBy: \"ed@example.org\"\nreturnedBy: \"boss@example.org\"\n" + + "note: \"Not before the merger is announced\"\n"); + write(siteDir.resolve("templates/.pending/about/about.html"), "

UNPUBLISHED merger draft

"); + write(siteDir.resolve("templates/.pending/about/about.meta.yml"), "title: About\n"); + write(siteDir.resolve("templates/pending-notes.html"), "

a live page whose NAME starts like it

"); + + Map transfer = entries(archive(BackupService.BackupPurpose.TRANSFER)); + for (Map.Entry file : transfer.entrySet()) { + assertFalse(file.getKey().contains(".pending"), "carried " + file.getKey()); + assertFalse(file.getValue().contains("ed@example.org") || file.getValue().contains("boss@example.org") + || file.getValue().contains("merger"), file.getKey() + " carries pending work"); + } + assertTrue(transfer.containsKey("site/templates/pending-notes.html"), "only the .pending subtree is left out"); + assertTrue(transfer.containsKey("site/templates/index.html"), "published content still travels"); + assertTrue(transfer.get("manifest.yml").contains("templates/.pending/"), transfer.get("manifest.yml")); + assertEquals(List.of("templates/.pending/"), svc.transferOmissions("acme"), + "the backup screen lists it before the copy is made"); + + Map full = entries(archive(BackupService.BackupPurpose.RESTORE)); + assertTrue(full.get("site/templates/.pending/about/review.yml").contains("ed@example.org"), + "a full backup keeps the review queue"); + assertTrue(full.containsKey("site/templates/.pending/about/about.html")); + assertFalse(full.get("manifest.yml").contains(".pending"), "nothing is omitted from a full backup"); + } + + @Test + void withNoPendingWorkNothingExtraIsListed() throws IOException { + assertEquals(List.of(), svc.transferOmissions("acme")); + assertFalse(entries(archive(BackupService.BackupPurpose.TRANSFER)).get("manifest.yml").contains(".pending")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/TransferPersonalDataTest.java b/runway-app/src/test/java/mx/quest/runway/backup/TransferPersonalDataTest.java new file mode 100644 index 0000000..319759e --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/TransferPersonalDataTest.java @@ -0,0 +1,255 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import mx.quest.runway.plugin.LoadedPlugin; +import mx.quest.runway.plugin.PluginDescriptor; +import mx.quest.runway.plugin.PluginSiteData; +import mx.quest.runway.plugin.RunningPlugins; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.BackupParticipant; +import mx.quest.runway.spi.model.BackupReader; +import mx.quest.runway.spi.model.BackupWriter; +import mx.quest.runway.spi.model.SiteRef; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.Yaml; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * A transfer copy leaves out the personal data plugins keep in the site folder — every + * path a loaded plugin declares under {@code siteData.personal}, and the whole folder of a plugin that is not loaded + * (fail-safe: without its descriptor nobody can tell what is personal) — and its manifest names what it left out. + * A full backup keeps everything, and a participant's export failure still fails it. + * + *

Asserted on the archive entries a recipient would unpack, as the other transfer tests are. + */ +class TransferPersonalDataTest { + + @TempDir + Path external; + private StorageLayout layout; + private Path siteDir; + + @BeforeEach + void setUp() throws IOException { + StorageProperties props = new StorageProperties(); + props.setExternal(external); + props.setBackups(external.resolve("backups")); + layout = StorageLayout.from(props); + siteDir = layout.siteDir("acme"); + write("site.yml", "id: acme\nname: Acme\n"); + write("templates/index.html", "

content

"); + write("plugins/contact.yml", "recipient: owner@acme.test\n"); + write("plugins/contact/submissions.tsv", "1\tAna\tana@x.test\tHello\n"); + write("plugins/contact/templates/form.txt", "not personal"); + write("plugins/search.yml", "recordNoResults: true\n"); + write("plugins/search/no-results.tsv", "secret search term\n"); + write("plugins/search/cache/a.bin", "derived"); + write("plugins/demo/notes/one.yml", "a note"); + write("plugins/demo/notes/deep/two.yml", "another"); + write("plugins/demo/keep.txt", "keep"); + write("plugins/retired/data.tsv", "a plugin that is no longer installed kept visitor data here\n"); + write("plugins/stray.txt", "a file directly in plugins/"); + } + + private void write(String rel, String content) throws IOException { + Path file = siteDir.resolve(rel); + Files.createDirectories(file.getParent()); + Files.writeString(file, content, StandardCharsets.UTF_8); + } + + private static LoadedPlugin plugin(Path installDir, String id, String... personal) { + PluginDescriptor descriptor = new PluginDescriptor(id, id, "1.0.0", null, true, false, List.of(), List.of(), + List.of(), List.of(), List.of(), Map.of(), List.of(), List.of(), null, List.of(), null, + new PluginSiteData(List.of(personal))); + return new LoadedPlugin(descriptor, installDir.resolve(id)); + } + + private BackupService service(RunningPlugins running, List participants) { + return new BackupService(layout, new SiteStore(layout, new YamlStore()), + new BackupParticipantRegistry(participants), event -> { }, new BackupProperties(), running); + } + + private RunningPlugins loaded() { + Path plugins = external.resolve("plugins"); + return () -> List.of(plugin(plugins, "contact", "submissions.tsv"), + plugin(plugins, "search", "no-results.tsv"), + plugin(plugins, "demo", "notes/")); + } + + private static Map entries(byte[] archive) throws IOException { + Map out = new HashMap<>(); + try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(archive))) { + ZipEntry entry; + while ((entry = zip.getNextEntry()) != null) { + out.put(entry.getName(), new String(zip.readAllBytes(), StandardCharsets.UTF_8)); + } + } + return out; + } + + private static byte[] archive(BackupService svc, BackupService.BackupPurpose purpose) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + svc.backup("acme", out, purpose); + return out.toByteArray(); + } + + private static BackupManifest manifest(Map entries) { + return Yaml.read(new ByteArrayInputStream(entries.get("manifest.yml").getBytes(StandardCharsets.UTF_8)), + BackupManifest.class); + } + + @Test + void aTransferCopyLeavesOutDeclaredPersonalPathsAndUnloadedPluginFolders() throws IOException { + Map entries = entries(archive(service(loaded(), List.of()), + BackupService.BackupPurpose.TRANSFER)); + assertFalse(entries.containsKey("site/plugins/contact/submissions.tsv"), "a declared personal file"); + assertFalse(entries.containsKey("site/plugins/search/no-results.tsv")); + assertFalse(entries.containsKey("site/plugins/demo/notes/one.yml"), "a declared folder, recursively"); + assertFalse(entries.containsKey("site/plugins/demo/notes/deep/two.yml")); + assertFalse(entries.containsKey("site/plugins/retired/data.tsv"), "an unloaded plugin's whole folder"); + assertTrue(entries.containsKey("site/plugins/contact/templates/form.txt"), "undeclared files travel"); + assertTrue(entries.containsKey("site/plugins/search/cache/a.bin")); + assertTrue(entries.containsKey("site/plugins/demo/keep.txt")); + assertTrue(entries.containsKey("site/plugins/contact.yml"), "settings files keep the secret-blanking rule"); + assertTrue(entries.containsKey("site/plugins/stray.txt")); + assertTrue(entries.containsKey("site/templates/index.html")); + for (String text : entries.values()) { + assertFalse(text.contains("ana@x.test") || text.contains("secret search term") + || text.contains("kept visitor data"), "no personal value survives anywhere"); + } + assertEquals(List.of("plugins/contact/submissions.tsv", "plugins/demo/notes/", "plugins/retired/", + "plugins/search/no-results.tsv"), manifest(entries).omitted(), "the manifest says what was left out"); + } + + @Test + void withNoLoadedPluginsEveryPluginFolderIsLeftOut() throws IOException { + Map entries = entries(archive(service(null, List.of()), BackupService.BackupPurpose.TRANSFER)); + assertTrue(entries.keySet().stream().noneMatch(name -> name.matches("site/plugins/[^/]+/.*")), entries.keySet() + .toString()); + assertTrue(entries.containsKey("site/plugins/contact.yml")); + assertEquals(List.of("plugins/contact/", "plugins/demo/", "plugins/retired/", "plugins/search/"), + manifest(entries).omitted()); + } + + @Test + void aFullBackupKeepsEverythingAndOmitsNothing() throws IOException { + Map entries = entries(archive(service(loaded(), List.of()), + BackupService.BackupPurpose.RESTORE)); + assertEquals("1\tAna\tana@x.test\tHello\n", entries.get("site/plugins/contact/submissions.tsv")); + assertTrue(entries.containsKey("site/plugins/search/no-results.tsv")); + assertTrue(entries.containsKey("site/plugins/demo/notes/deep/two.yml")); + assertTrue(entries.containsKey("site/plugins/retired/data.tsv")); + assertEquals(List.of(), manifest(entries).omitted()); + } + + @Test + void theBackupScreenPreviewMatchesWhatTheCopyOmits() throws IOException { + BackupService svc = service(loaded(), List.of()); + Map entries = entries(archive(svc, BackupService.BackupPurpose.TRANSFER)); + assertEquals(manifest(entries).omitted(), svc.transferOmissions("acme")); + assertThrows(IllegalArgumentException.class, () -> svc.transferOmissions("../acme")); + assertEquals(List.of(), svc.transferOmissions("nosuchsite")); + } + + @Test + void aTransferCopyRestoresAndTheOmittedFilesAreSimplyAbsent() throws IOException { + BackupService svc = service(loaded(), List.of()); + byte[] transfer = archive(svc, BackupService.BackupPurpose.TRANSFER); + svc.restore("acme", new ByteArrayInputStream(transfer)); + assertFalse(Files.exists(siteDir.resolve("plugins/contact/submissions.tsv"))); + assertTrue(Files.exists(siteDir.resolve("plugins/contact/templates/form.txt"))); + assertTrue(Files.exists(siteDir.resolve("templates/index.html"))); + } + + @Test + void anOlderManifestWithoutTheKeyReadsAsNothingOmitted() { + BackupManifest old = Yaml.read(new ByteArrayInputStream( + "siteId: acme\nspiVersion: 0.4.0\ncreatedAt: x\npurpose: TRANSFER\n".getBytes(StandardCharsets.UTF_8)), + BackupManifest.class); + assertEquals(List.of(), old.omitted()); + assertEquals(1, old.formatVersion(), "an additive key: the format version is unchanged"); + } + + @Test + void aParticipantExportFailureStillFailsTheFullBackup() { + BackupParticipant broken = new BackupParticipant() { + @Override + public String key() { + return "broken"; + } + + @Override + public void export(BackupWriter writer, SiteRef site) throws IOException { + throw new IOException("disk on fire"); + } + + @Override + public void importInto(BackupReader reader, SiteRef site) { + } + }; + BackupService svc = service(loaded(), List.of(broken)); + IOException failure = assertThrows(IOException.class, + () -> archive(svc, BackupService.BackupPurpose.RESTORE)); + assertTrue(failure.getMessage().contains("broken"), failure.getMessage()); + } + + // --- the declaration itself ---------------------------------------------------------------------------- + + @Test + void personalPathsAreMatchedExactlyOrAsAFolderPrefix() { + PluginSiteData data = new PluginSiteData(List.of("submissions.tsv", "archive/", " ", "logs/x.tsv")); + assertEquals(List.of("submissions.tsv", "archive/", "logs/x.tsv"), data.personal(), "blank entries dropped"); + assertTrue(data.isPersonal("submissions.tsv")); + assertFalse(data.isPersonal("submissions.tsv.bak"), "a file declaration is exact"); + assertFalse(data.isPersonal("old/submissions.tsv")); + assertTrue(data.isPersonal("archive/2026/a.tsv")); + assertFalse(data.isPersonal("archive"), "a folder declaration covers what is under it"); + assertFalse(data.isPersonal("archived/a.tsv")); + assertEquals("plugins/contact/submissions.tsv", BackupService.personalDataOmission( + "plugins/contact/submissions.tsv", Map.of("contact", data))); + assertEquals(null, BackupService.personalDataOmission("plugins/contact.yml", Map.of())); + assertEquals("plugins/x/", BackupService.personalDataOmission("plugins/x/a", Map.of())); + } + + @Test + void aMalformedDeclarationBlocksThePluginWithAReason() { + for (String bad : List.of("/etc/passwd", "../users.yml", "a/../b", "a\\b", "/", "a//b", "./x")) { + PluginDescriptor descriptor = PluginDescriptor.read(new ByteArrayInputStream( + ("id: contact\nversion: 2.0.0\nsiteData:\n personal:\n - \"" + bad.replace("\\", "\\\\") + + "\"\n").getBytes(StandardCharsets.UTF_8))); + IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, descriptor::validate, bad); + assertTrue(failure.getMessage().contains("siteData.personal"), failure.getMessage()); + } + } + + @Test + void theDescriptorReadsTheDeclarationAndAnOlderDescriptorHasNone() { + PluginDescriptor declared = PluginDescriptor.read(new ByteArrayInputStream( + "id: contact\nversion: 2.0.0\nsiteData:\n personal: [submissions.tsv, uploads/]\n" + .getBytes(StandardCharsets.UTF_8))); + declared.validate(); + assertEquals(List.of("submissions.tsv", "uploads/"), declared.siteData().personal()); + PluginDescriptor older = PluginDescriptor.read(new ByteArrayInputStream( + "id: contact\nversion: 1.1.2\n".getBytes(StandardCharsets.UTF_8))); + assertEquals(List.of(), older.siteData().personal()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/backup/ZipBackupEntryNameTest.java b/runway-app/src/test/java/mx/quest/runway/backup/ZipBackupEntryNameTest.java new file mode 100644 index 0000000..dbfcd25 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/backup/ZipBackupEntryNameTest.java @@ -0,0 +1,52 @@ +package mx.quest.runway.backup; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipOutputStream; +import org.junit.jupiter.api.Test; + +/** A participant can neither write nor look up an entry outside its own namespace. */ +class ZipBackupEntryNameTest { + + private static final List UNSAFE = List.of("", " ", "../users.yml", "a/../../b", "/etc/passwd", + "a\\b", "C:evil", "a//b", "./a", "a/.", "dir/", "nul\0byte"); + + @Test + void plainRelativeNamesAreAccepted() { + for (String ok : List.of("notes.yml", "a/b/c.txt", "x.y.z", "..hidden-but-not-dotdot", "a-b_c")) { + assertEquals(ok, ZipBackup.requireSafeEntry(ok)); + } + } + + @Test + void unsafeNamesAreRefusedOnWrite() throws Exception { + try (ZipOutputStream zip = new ZipOutputStream(new ByteArrayOutputStream())) { + ZipBackup.Writer writer = new ZipBackup.Writer(zip, "demo"); + for (String bad : UNSAFE) { + assertThrows(IllegalArgumentException.class, () -> writer.put(bad), "must refuse '" + bad + "'"); + } + assertThrows(IllegalArgumentException.class, () -> writer.put(null)); + try (OutputStream out = writer.put("fine.txt")) { + out.write(1); + } + } + } + + @Test + void unsafeNamesAreRefusedOnRead() throws Exception { + ZipBackup.Reader reader = new ZipBackup.Reader(Map.of("fine.txt", new byte[] {1})); + for (String bad : UNSAFE) { + assertThrows(IllegalArgumentException.class, () -> reader.has(bad), "has('" + bad + "')"); + assertThrows(IllegalArgumentException.class, () -> reader.open(bad), "open('" + bad + "')"); + } + assertTrue(reader.has("fine.txt")); + assertFalse(reader.has("other.txt")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthLimitFilterTest.java b/runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthLimitFilterTest.java new file mode 100644 index 0000000..005552f --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthLimitFilterTest.java @@ -0,0 +1,79 @@ +package mx.quest.runway.bandwidth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import jakarta.servlet.FilterChain; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStatus; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +/** BandwidthLimitFilter: 503s an over-quota site's public traffic while exempting the console/app realms. */ +class BandwidthLimitFilterTest { + + private final SiteResolver resolver = mock(SiteResolver.class); + private final BandwidthService bandwidth = mock(BandwidthService.class); + private final BandwidthLimitFilter filter = new BandwidthLimitFilter(resolver, bandwidth); + + private static final Site ACME = new Site("acme", "Acme", List.of("localhost"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE); + + private FilterChain runFor(String uri, boolean over, MockHttpServletResponse response) throws Exception { + when(resolver.current()).thenReturn(Optional.of(ACME)); + when(bandwidth.isOverQuota("acme")).thenReturn(over); + MockHttpServletRequest request = new MockHttpServletRequest("GET", uri); + request.setRequestURI(uri); + FilterChain chain = mock(FilterChain.class); + filter.doFilter(request, response, chain); + return chain; + } + + @Test + void anOverQuotaSitesPublicTrafficGets503() throws Exception { + MockHttpServletResponse res = new MockHttpServletResponse(); + FilterChain chain = runFor("/about", true, res); + assertEquals(503, res.getStatus()); + assertTrue(res.getContentAsString().toLowerCase().contains("bandwidth")); + assertEquals("3600", res.getHeader("Retry-After")); + verify(chain, never()).doFilter(any(), any()); + } + + @Test + void theConsoleAndAppRealmsAreExemptEvenWhenOverQuota() throws Exception { + for (String uri : List.of("/__admin", "/__admin/bandwidth", "/login", "/__assets/runway.svg", "/__app/x")) { + MockHttpServletResponse res = new MockHttpServletResponse(); + FilterChain chain = runFor(uri, true, res); + verify(chain).doFilter(any(), any()); + assertEquals(200, res.getStatus(), uri + " must pass through"); + } + } + + @Test + void aSiteUnderQuotaPassesThrough() throws Exception { + MockHttpServletResponse res = new MockHttpServletResponse(); + FilterChain chain = runFor("/about", false, res); + verify(chain).doFilter(any(), any()); + } + + @Test + void anUnconfiguredHostWithNoSitePassesThrough() throws Exception { + when(resolver.current()).thenReturn(Optional.empty()); + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/about"); + request.setRequestURI("/about"); + MockHttpServletResponse res = new MockHttpServletResponse(); + FilterChain chain = mock(FilterChain.class); + filter.doFilter(request, res, chain); + verify(chain).doFilter(any(), any()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthServiceTest.java b/runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthServiceTest.java new file mode 100644 index 0000000..e5f36a2 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/bandwidth/BandwidthServiceTest.java @@ -0,0 +1,128 @@ +package mx.quest.runway.bandwidth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import mx.quest.runway.bandwidth.BandwidthService.BandwidthReport; +import mx.quest.runway.bandwidth.BandwidthService.SiteBandwidth; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** The metering engine: record→report, human sizes, CSV snapshot/reload, per-site aggregate. */ +class BandwidthServiceTest { + + @TempDir + Path external; + private StorageLayout layout; + private BandwidthProperties props; + + @BeforeEach + void setUp() { + StorageProperties sp = new StorageProperties(); + sp.setExternal(external); + layout = StorageLayout.from(sp); + props = new BandwidthProperties(); + } + + @Test + void recordThenReportShowsTheBytes() { + BandwidthService svc = new BandwidthService(layout, props); + svc.record("acme", 100, 2000); + svc.record("acme", 50, 500); + + BandwidthReport report = svc.report("acme", 30); + assertEquals(2500, report.out24h()); + assertEquals(150, report.in24h()); + assertEquals(2500, report.daily().get(29).bytesOut(), "today is the last daily point"); + } + + @Test + void humanReadableSizes() { + assertEquals("0 B", Bytes.human(0)); + assertEquals("512 B", Bytes.human(512)); + assertEquals("1.5 KB", Bytes.human(1536)); + assertEquals("2.0 MB", Bytes.human(2L * 1024 * 1024)); + } + + @Test + void snapshotThenReloadRestoresTheCounters() { + BandwidthService writer = new BandwidthService(layout, props); + writer.record("acme", 10, 4096); + writer.snapshotAll(); + assertTrue(Files.isRegularFile(layout.siteDir("acme").resolve("stats").resolve("bandwidth.csv")), + "counters snapshotted to CSV"); + + BandwidthService reloaded = new BandwidthService(layout, props); + reloaded.reloadAll(); + assertEquals(4096, reloaded.report("acme", 30).out24h(), "reloaded from the CSV at startup"); + } + + @Test + void aggregateRanksSitesByTraffic() { + BandwidthService svc = new BandwidthService(layout, props); + svc.record("small", 0, 100); + svc.record("big", 0, 9000); + + List agg = svc.aggregate(); + assertEquals(2, agg.size()); + assertEquals("big", agg.get(0).siteId(), "busiest site first"); + assertEquals(9000, agg.get(0).bytesOut()); + } + + @Test + void meteringOffRecordsNothing() { + props.setEnabled(false); + BandwidthService svc = new BandwidthService(layout, props); + svc.record("acme", 100, 2000); + assertEquals(0, svc.report("acme", 30).out24h()); + } + + @Test + void overQuotaIsComputedFromTheOutboundThirtyDayTotal() { + props.getQuota().setDefaultMonthlyBytes(1000); + BandwidthService svc = new BandwidthService(layout, props); + svc.record("acme", 0, 1500); // over the 1000-byte cap + svc.record("blog", 0, 500); // under + svc.recomputeOverQuota(); + assertTrue(svc.isOverQuota("acme")); + assertFalse(svc.isOverQuota("blog")); + } + + @Test + void aPerSiteQuotaOverridesTheDefault() { + props.getQuota().setDefaultMonthlyBytes(0); // default: unlimited + props.getQuota().getPerSite().put("acme", 100L); // acme capped at 100 bytes + BandwidthService svc = new BandwidthService(layout, props); + svc.record("acme", 0, 200); + svc.record("blog", 0, 1_000_000); // huge but uncapped + svc.recomputeOverQuota(); + assertTrue(svc.isOverQuota("acme")); + assertFalse(svc.isOverQuota("blog"), "an uncapped site is never over quota"); + } + + @Test + void withMeteringOffNoCapIsEnforced() { + props.getQuota().setDefaultMonthlyBytes(100); + BandwidthService svc = new BandwidthService(layout, props); + svc.record("acme", 0, 200); + svc.recomputeOverQuota(); + assertTrue(svc.isOverQuota("acme")); + props.setEnabled(false); // as after a restart with runway.bandwidth.enabled=false over the saved totals + assertFalse(svc.isOverQuota("acme"), "nothing is counted, so a cap could never lift: no metering, no cap"); + } + + @Test + void withNoQuotaConfiguredNoSiteIsEverOver() { + BandwidthService svc = new BandwidthService(layout, props); + svc.record("acme", 0, 999_999_999); + svc.recomputeOverQuota(); + assertFalse(svc.isOverQuota("acme")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/bandwidth/CountingResponseWrapperTest.java b/runway-app/src/test/java/mx/quest/runway/bandwidth/CountingResponseWrapperTest.java new file mode 100644 index 0000000..e086d09 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/bandwidth/CountingResponseWrapperTest.java @@ -0,0 +1,27 @@ +package mx.quest.runway.bandwidth; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletResponse; + +/** The counting wrapper tallies exactly the bytes written, through both the stream and the writer. */ +class CountingResponseWrapperTest { + + @Test + void countsBytesWrittenToTheOutputStream() throws Exception { + CountingResponseWrapper wrapper = new CountingResponseWrapper(new MockHttpServletResponse()); + wrapper.getOutputStream().write("hello world".getBytes(StandardCharsets.UTF_8)); // 11 bytes + wrapper.getOutputStream().write('!'); + assertEquals(12, wrapper.bytesWritten()); + } + + @Test + void countsBytesWrittenThroughTheWriter() throws Exception { + CountingResponseWrapper wrapper = new CountingResponseWrapper(new MockHttpServletResponse()); + wrapper.getWriter().write("abcde"); // 5 ASCII bytes + wrapper.flushBuffer(); + assertEquals(5, wrapper.bytesWritten()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/cluster/ClusterActiveModeGatingTest.java b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterActiveModeGatingTest.java new file mode 100644 index 0000000..7bc5fa6 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterActiveModeGatingTest.java @@ -0,0 +1,42 @@ +package mx.quest.runway.cluster; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.hazelcast.core.HazelcastInstance; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.session.SessionRepository; + +/** + * Proves the second gate on {@link ClusterConfig}: even with the master switch ON + * ({@code runway.cluster.enabled=true}), the cluster layer stays absent in WIZARD mode (no + * {@code app-master-id} pinned). Clustering is meaningless before first-run setup, so the + * {@code @Conditional(ActiveModeCondition.class)} gate keeps Hazelcast and the session repository out until the + * platform is ACTIVE. {@link ClusterEnabledActiveTest} is the complementary proof that they DO appear once + * ACTIVE. + */ +@SpringBootTest(properties = { + "runway.cluster.enabled=true", + "runway.cluster.embedded.discovery=tcp-ip" + // deliberately NO runway.security.app-master-id -> WIZARD mode +}) +class ClusterActiveModeGatingTest { + + @Autowired + private ApplicationContext context; + + @Test + void clusterEnabledButInWizardModeStillWiresNothing() { + assertEquals(0, context.getBeanNamesForType(ClusterConfig.class).length, + "ClusterConfig must stay out in WIZARD mode even with enabled=true"); + assertEquals(0, context.getBeanNamesForType(HazelcastInstance.class).length, + "no HazelcastInstance before the platform is ACTIVE"); + assertEquals(0, context.getBeanNamesForType(SessionRepository.class).length, + "no SessionRepository before the platform is ACTIVE"); + assertTrue(!context.containsBean("springSessionRepositoryFilter"), + "no Spring Session filter before the platform is ACTIVE"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/cluster/ClusterDisabledByDefaultTest.java b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterDisabledByDefaultTest.java new file mode 100644 index 0000000..51fda56 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterDisabledByDefaultTest.java @@ -0,0 +1,69 @@ +package mx.quest.runway.cluster; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.hazelcast.core.HazelcastInstance; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.session.SessionRepository; +import org.springframework.web.filter.DelegatingFilterProxy; + +/** + * Proves the load-bearing default: with clustering off (the shipped default — {@code runway.cluster.enabled} + * unset), none of the cluster layer is wired. No {@link HazelcastInstance}, no {@link SessionRepository}, + * and — because {@code @EnableSpringHttpSession} lives on the (absent) {@code ClusterConfig} — no + * {@code springSessionRepositoryFilter} either. The application is byte-for-byte today's single-node footprint, + * using the container's own {@code HttpSession}. This is the guarantee that opt-in clustering costs a + * non-clustered deployment nothing. + * + *

Boots in WIZARD mode (no {@code app-master-id}); that is irrelevant here since the master switch alone + * keeps everything absent — {@link ClusterActiveModeGatingTest} covers the ACTIVE-mode gate separately. + */ +@SpringBootTest +class ClusterDisabledByDefaultTest { + + @Autowired + private ApplicationContext context; + + @Test + void noHazelcastInstanceBeanExists() { + assertTrue(context.getBeanNamesForType(HazelcastInstance.class).length == 0, + "a HazelcastInstance must not be wired when clustering is off"); + } + + @Test + void noSpringSessionRepositoryBeanExists() { + assertTrue(context.getBeanNamesForType(SessionRepository.class).length == 0, + "a SessionRepository must not be wired when clustering is off — the container HttpSession is used"); + } + + @Test + void theClusterConfigurationItselfIsAbsent() { + assertEquals(0, context.getBeanNamesForType(ClusterConfig.class).length, + "ClusterConfig is class-level @ConditionalOnProperty-gated and must not be registered"); + } + + @Test + void theClusterEventRelayIsAbsent() { + // The relay is gated the same way as ClusterConfig; with clustering off it must not exist, so a local + // PageChangedEvent (and its siblings) drive purely local eviction and nothing is ever broadcast. + assertEquals(0, context.getBeanNamesForType(ClusterEventRelay.class).length, + "ClusterEventRelay must not be wired when clustering is off — events stay local"); + } + + @Test + void noSpringSessionRepositoryFilterIsRegistered() { + // @EnableSpringHttpSession registers a bean literally named "springSessionRepositoryFilter"; its absence + // proves the container's default session management is still in force. + assertFalse(context.containsBean("springSessionRepositoryFilter"), + "the Spring Session filter must be absent so the container HttpSession is used"); + // And no Spring-Session DelegatingFilterProxy sneaked in under another name. + boolean anySessionFilter = context.getBeansOfType(DelegatingFilterProxy.class).keySet().stream() + .anyMatch(name -> name.toLowerCase().contains("session")); + assertFalse(anySessionFilter, "no Spring Session delegating filter proxy should be registered"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEnabledActiveTest.java b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEnabledActiveTest.java new file mode 100644 index 0000000..4548b82 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEnabledActiveTest.java @@ -0,0 +1,93 @@ +package mx.quest.runway.cluster; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.hazelcast.core.HazelcastInstance; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.session.MapSession; +import org.springframework.session.SessionRepository; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +/** + * The positive counterpart to the two gating tests: with clustering enabled AND the platform ACTIVE (an + * {@code app-master-id} pinned), {@link ClusterConfig} activates and wires a real embedded {@link + * HazelcastInstance}, the hand-rolled {@link SessionRepository}, and the {@code springSessionRepositoryFilter} + * from {@code @EnableSpringHttpSession}. It boots a genuine single-member Hazelcast grid inside the test JVM (an + * isolated cluster name; {@code port-auto-increment} so it never clashes) and confirms the sessions map is live + * and its {@code max-idle-seconds} was sourced from the configured session TTL. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) +class ClusterEnabledActiveTest { + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-cluster-active"); + YamlStore yaml = new YamlStore(); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode("Cluster-Active-7"); + new UserStore(yaml).save(external.resolve("app-users.yml"), + new User("app-master", "root", hash, "Root", "", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + registry.add("runway.storage.external", external::toString); + registry.add("runway.security.app-master-id", () -> "app-master"); // -> ACTIVE mode + + // Clustering ON, but on an ISOLATED single-member grid so the test never joins a real cluster and + // never fights for a fixed port. + registry.add("runway.cluster.enabled", () -> "true"); + registry.add("runway.cluster.cluster-name", () -> "rw-active-test-" + System.nanoTime()); + registry.add("runway.cluster.topology", () -> "embedded"); + registry.add("runway.cluster.embedded.discovery", () -> "tcp-ip"); + registry.add("runway.cluster.embedded.port", () -> "16801"); + registry.add("runway.cluster.embedded.port-auto-increment", () -> "true"); + registry.add("runway.cluster.session-ttl", () -> "20m"); + } + + @Autowired + private ApplicationContext context; + @Autowired + private HazelcastInstance hazelcast; + @Autowired + private SessionRepository sessionRepository; + + @Test + void theClusterBeansAreWiredAndTheSessionMapIsLive() { + assertEquals(1, context.getBeanNamesForType(ClusterConfig.class).length, "ClusterConfig should activate"); + assertEquals(1, context.getBeanNamesForType(ClusterEventRelay.class).length, + "ClusterEventRelay should activate alongside ClusterConfig when enabled+active"); + assertNotNull(hazelcast, "a HazelcastInstance must be wired"); + assertNotNull(sessionRepository, "the hand-rolled session repository must be wired"); + assertTrue(context.containsBean("springSessionRepositoryFilter"), + "@EnableSpringHttpSession must register the Spring Session filter when active"); + + // The repository round-trips a session through the real embedded grid. + MapSession created = sessionRepository.createSession(); + assertEquals(java.time.Duration.ofMinutes(20), created.getMaxInactiveInterval(), + "createSession stamps the configured session-ttl"); + created.setAttribute("hello", "world"); + sessionRepository.save(created); + MapSession found = sessionRepository.findById(created.getId()); + assertNotNull(found); + assertEquals("world", found.getAttribute("hello")); + + // The sessions map's idle-eviction was sourced from the configured TTL (20m = 1200s). + assertEquals(1200, hazelcast.getConfig().getMapConfig("runway.sessions").getMaxIdleSeconds(), + "sessions map max-idle-seconds must equal the configured TTL in seconds"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTest.java b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTest.java new file mode 100644 index 0000000..2c24721 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTest.java @@ -0,0 +1,295 @@ +package mx.quest.runway.cluster; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.hazelcast.cluster.Endpoint; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.topic.ITopic; +import java.util.UUID; +import mx.quest.runway.content.ContentChangedEvent; +import mx.quest.runway.page.PageChangedEvent; +import mx.quest.runway.plugin.SitePluginConfigChangedEvent; +import mx.quest.runway.site.SiteChangedEvent; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.context.ApplicationEventPublisher; + +/** + * The receive/publish paths of {@link ClusterEventRelay}, driven with a mocked Hazelcast topic and + * {@link ApplicationEventPublisher} — no live grid. Covers Runway's four + * relayed event types ({@link SiteChangedEvent}, {@link SitePluginConfigChangedEvent}, {@link PageChangedEvent}, + * {@link ContentChangedEvent}): a local event is published to the topic tagged with the local node id; a message + * from another node is replayed as the equivalent local event; a self-origin message is dropped; and a replayed + * (received) event is NOT rebroadcast back to the topic (the echo-loop guard). + */ +class ClusterEventRelayTest { + + private final UUID LOCAL = UUID.randomUUID(); + private final UUID OTHER = UUID.randomUUID(); + + @SuppressWarnings("unchecked") + private final ITopic topic = (ITopic) mock(ITopic.class); + private HazelcastInstance hz; + private ApplicationEventPublisher events; + private ClusterEventRelay relay; + + @BeforeEach + void setup() { + hz = mock(HazelcastInstance.class); + Endpoint endpoint = mock(Endpoint.class); + when(endpoint.getUuid()).thenReturn(LOCAL); + when(hz.getLocalEndpoint()).thenReturn(endpoint); + RunwayClusterProperties props = new RunwayClusterProperties(); // default topic name "runway.events" + doReturn(topic).when(hz).getTopic(props.getEventsTopicName()); + when(topic.addMessageListener(any())).thenReturn(UUID.randomUUID()); + events = mock(ApplicationEventPublisher.class); + relay = new ClusterEventRelay(hz, events, props); + relay.subscribe(); + } + + // --- publish-on-local-event --------------------------------------------------------------------------- + + @Test + void localPageChangeIsPublishedToTopicWithOriginId() { + relay.onPageChanged(new PageChangedEvent("demo", "about")); + ClusterEventEnvelope env = capturePublished(); + assertThat(env.getKind()).isEqualTo(ClusterEventEnvelope.Kind.PAGE_CHANGED); + assertThat(env.getSiteId()).isEqualTo("demo"); + assertThat(env.getSlug()).isEqualTo("about"); + assertThat(env.getOriginNodeId()).isEqualTo(LOCAL.toString()); + } + + @Test + void localSiteChangeCarriesKindNameAndTemplateId() { + relay.onSiteChanged(new SiteChangedEvent("demo", SiteChangedEvent.Kind.CREATED, "blog")); + ClusterEventEnvelope env = capturePublished(); + assertThat(env.getKind()).isEqualTo(ClusterEventEnvelope.Kind.SITE_CHANGED); + assertThat(env.getSiteId()).isEqualTo("demo"); + assertThat(env.getSiteChangedKind()).isEqualTo("CREATED"); + assertThat(env.getTemplateId()).isEqualTo("blog"); + assertThat(env.getOriginNodeId()).isEqualTo(LOCAL.toString()); + } + + @Test + void localSitePluginConfigChangeCarriesPluginId() { + relay.onSitePluginConfigChanged(new SitePluginConfigChangedEvent("demo", "search")); + ClusterEventEnvelope env = capturePublished(); + assertThat(env.getKind()).isEqualTo(ClusterEventEnvelope.Kind.SITE_PLUGIN_CONFIG_CHANGED); + assertThat(env.getSiteId()).isEqualTo("demo"); + assertThat(env.getPluginId()).isEqualTo("search"); + assertThat(env.getSlug()).isNull(); + } + + @Test + void localContentChangeCarriesSourceKeyAndContentId() { + relay.onContentChanged(new ContentChangedEvent("demo", "blog", "my-post")); + ClusterEventEnvelope env = capturePublished(); + assertThat(env.getKind()).isEqualTo(ClusterEventEnvelope.Kind.CONTENT_CHANGED); + assertThat(env.getSiteId()).isEqualTo("demo"); + assertThat(env.getSourceKey()).isEqualTo("blog"); + assertThat(env.getContentId()).isEqualTo("my-post"); + assertThat(env.getOriginNodeId()).isEqualTo(LOCAL.toString()); + } + + @Test + void localWholeCorpusContentChangeCarriesNullContentId() { + relay.onContentChanged(new ContentChangedEvent("demo", "blog", null)); // null id = whole corpus + ClusterEventEnvelope env = capturePublished(); + assertThat(env.getKind()).isEqualTo(ClusterEventEnvelope.Kind.CONTENT_CHANGED); + assertThat(env.getContentId()).isNull(); + } + + // --- re-fire-on-remote-message ------------------------------------------------------------------------ + + @Test + void topicMessageFromOtherNodeFiresLocalPageEvent() { + relay.handleClusterMessage(ClusterEventEnvelope.pageChanged("demo", "about", OTHER.toString())); + ArgumentCaptor cap = ArgumentCaptor.forClass(PageChangedEvent.class); + verify(events).publishEvent(cap.capture()); + assertThat(cap.getValue().siteId()).isEqualTo("demo"); + assertThat(cap.getValue().slug()).isEqualTo("about"); + } + + @Test + void topicMessageFromOtherNodeReconstructsSiteChangedWithKind() { + relay.handleClusterMessage( + ClusterEventEnvelope.siteChanged("demo", "RESTORED", null, OTHER.toString())); + ArgumentCaptor cap = ArgumentCaptor.forClass(SiteChangedEvent.class); + verify(events).publishEvent(cap.capture()); + assertThat(cap.getValue().siteId()).isEqualTo("demo"); + assertThat(cap.getValue().kind()).isEqualTo(SiteChangedEvent.Kind.RESTORED); + } + + @Test + void topicMessageFromOtherNodeReconstructsSitePluginConfigChanged() { + relay.handleClusterMessage( + ClusterEventEnvelope.sitePluginConfigChanged("demo", "search", OTHER.toString())); + ArgumentCaptor cap = + ArgumentCaptor.forClass(SitePluginConfigChangedEvent.class); + verify(events).publishEvent(cap.capture()); + assertThat(cap.getValue().siteId()).isEqualTo("demo"); + assertThat(cap.getValue().pluginId()).isEqualTo("search"); + } + + @Test + void topicMessageFromOtherNodeReconstructsContentChanged() { + relay.handleClusterMessage( + ClusterEventEnvelope.contentChanged("demo", "blog", "my-post", OTHER.toString())); + ArgumentCaptor cap = ArgumentCaptor.forClass(ContentChangedEvent.class); + verify(events).publishEvent(cap.capture()); + assertThat(cap.getValue().siteId()).isEqualTo("demo"); + assertThat(cap.getValue().sourceKey()).isEqualTo("blog"); + assertThat(cap.getValue().id()).isEqualTo("my-post"); + } + + // --- echo guard --------------------------------------------------------------------------------------- + + @Test + void topicMessageFromSelfIsDropped() { + relay.handleClusterMessage(ClusterEventEnvelope.pageChanged("demo", "x", LOCAL.toString())); + verify(events, never()).publishEvent(any(Object.class)); + } + + @Test + void aReceivedEventIsNotRebroadcastBackToTheTopic() { + // Wire the publisher to actually call the relay's own listeners back (as Spring would), so the + // thread-local guard is what must stop the re-publish — not merely the absence of a real context. + doAnswer(inv -> { + Object e = inv.getArgument(0); + if (e instanceof PageChangedEvent pce) { + relay.onPageChanged(pce); + } else if (e instanceof SiteChangedEvent sce) { + relay.onSiteChanged(sce); + } else if (e instanceof SitePluginConfigChangedEvent spe) { + relay.onSitePluginConfigChanged(spe); + } else if (e instanceof ContentChangedEvent cce) { + relay.onContentChanged(cce); + } + return null; + }).when(events).publishEvent(any(Object.class)); + + relay.handleClusterMessage(ClusterEventEnvelope.pageChanged("demo", "about", OTHER.toString())); + + // The relay replayed the event locally exactly once and published NOTHING back to the topic + // (which would loop forever across the two nodes). + verify(events).publishEvent(any(PageChangedEvent.class)); + verify(topic, never()).publish(any(ClusterEventEnvelope.class)); + } + + @Test + void aReceivedContentEventIsNotRebroadcastBackToTheTopic() { + // Same loop-guard, exercised through the NEW content listener: the replayed local event reaches + // relay.onContentChanged (as Spring would deliver it) and must not go back out to the topic. + doAnswer(inv -> { + Object e = inv.getArgument(0); + if (e instanceof ContentChangedEvent cce) { + relay.onContentChanged(cce); + } + return null; + }).when(events).publishEvent(any(Object.class)); + + relay.handleClusterMessage(ClusterEventEnvelope.contentChanged("demo", "blog", "my-post", OTHER.toString())); + + verify(events).publishEvent(any(ContentChangedEvent.class)); + verify(topic, never()).publish(any(ClusterEventEnvelope.class)); + } + + @Test + void aMalformedSiteChangedKindIsDroppedNotThrown() { + // A newer node could broadcast a SiteChangedEvent.Kind this node doesn't know; the relay must swallow + // the reconstruction failure rather than break the topic listener. + relay.handleClusterMessage( + ClusterEventEnvelope.siteChanged("demo", "NOT_A_REAL_KIND", null, OTHER.toString())); + verify(events, never()).publishEvent(any(Object.class)); + } + + @Test + void aContentChangedEnvelopeSurvivesJavaSerializationRoundTrip() throws Exception { + // The wire form: Hazelcast's default serializer is Java serialization of the JavaBean. Round-trip the + // new kind (including the null-contentId whole-corpus form) to pin the serialization compatibility. + for (String contentId : new String[] {"my-post", null}) { + ClusterEventEnvelope out = ClusterEventEnvelope.contentChanged("demo", "blog", contentId, "node-1"); + java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream(); + try (java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(bytes)) { + oos.writeObject(out); + } + ClusterEventEnvelope in; + try (java.io.ObjectInputStream ois = + new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes.toByteArray()))) { + in = (ClusterEventEnvelope) ois.readObject(); + } + assertThat(in.getKind()).isEqualTo(ClusterEventEnvelope.Kind.CONTENT_CHANGED); + assertThat(in.getSiteId()).isEqualTo("demo"); + assertThat(in.getSourceKey()).isEqualTo("blog"); + assertThat(in.getContentId()).isEqualTo(contentId); + assertThat(in.getOriginNodeId()).isEqualTo("node-1"); + } + } + + // --- fromBackup and the replay mark ----------------------------------------------- + + @Test + void aBackupImportCarriesFromBackupBothWays() { + relay.onSiteChanged(SiteChangedEvent.createdFromBackup("demo")); + ClusterEventEnvelope env = capturePublished(); + assertThat(env.getFromBackup()).isTrue(); + + relay.handleClusterMessage(ClusterEventEnvelope.siteChanged("demo", "CREATED", null, true, OTHER.toString())); + ArgumentCaptor cap = ArgumentCaptor.forClass(SiteChangedEvent.class); + verify(events).publishEvent(cap.capture()); + assertThat(cap.getValue().fromBackup()).as("a peer's birth-time seeders stand down too").isTrue(); + } + + @Test + void anEnvelopeFromANodeWithoutFromBackupReadsAsFalse() { + ClusterEventEnvelope old = ClusterEventEnvelope.siteChanged("demo", "CREATED", null, OTHER.toString()); + old.setFromBackup(null); // what a node that predates the field puts on the wire + relay.handleClusterMessage(old); + ArgumentCaptor cap = ArgumentCaptor.forClass(SiteChangedEvent.class); + verify(events).publishEvent(cap.capture()); + assertThat(cap.getValue().fromBackup()).isFalse(); + } + + @Test + void aReplayIsMarkedForItsListenersAndTheMarkIsCleared() { + java.util.List marked = new java.util.ArrayList<>(); + doAnswer(inv -> { + marked.add(mx.quest.runway.event.ClusterReplay.active()); + return null; + }).when(events).publishEvent(any(Object.class)); + relay.handleClusterMessage(ClusterEventEnvelope.pageChanged("demo", "about", OTHER.toString())); + assertThat(marked).containsExactly(true); + assertThat(mx.quest.runway.event.ClusterReplay.active()).isFalse(); + + // also after a malformed envelope, whose replay throws + relay.handleClusterMessage(ClusterEventEnvelope.siteChanged("demo", "NOT_A_KIND", null, OTHER.toString())); + assertThat(mx.quest.runway.event.ClusterReplay.active()).isFalse(); + } + + @Test + void theFromBackupFieldSurvivesJavaSerialization() throws Exception { + ClusterEventEnvelope out = ClusterEventEnvelope.siteChanged("demo", "CREATED", null, true, "node-1"); + java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream(); + try (java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(bytes)) { + oos.writeObject(out); + } + try (java.io.ObjectInputStream ois = + new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes.toByteArray()))) { + assertThat(((ClusterEventEnvelope) ois.readObject()).getFromBackup()).isTrue(); + } + } + + private ClusterEventEnvelope capturePublished() { + ArgumentCaptor cap = ArgumentCaptor.forClass(ClusterEventEnvelope.class); + verify(topic).publish(cap.capture()); + return cap.getValue(); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTwoNodeTest.java b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTwoNodeTest.java new file mode 100644 index 0000000..3d6a8cb --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/cluster/ClusterEventRelayTwoNodeTest.java @@ -0,0 +1,233 @@ +package mx.quest.runway.cluster; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.hazelcast.config.Config; +import com.hazelcast.config.JoinConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import mx.quest.runway.page.PageChangedEvent; +import mx.quest.runway.site.SiteChangedEvent; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationEventPublisher; + +/** + * The end-to-end proof of the cluster cache relay: a cache-invalidation event raised on one node is delivered, over a + * real two-member embedded Hazelcast grid, as the equivalent local event on the other node — so a + * page edit or a site change on node A evicts the matching cache on node B. This is the cross-node counterpart + * to {@code HazelcastSessionRepositoryTest}, and it exercises the whole relay path (envelope serialization → + * ITopic → subscriber → local re-publish) that the Mockito {@link ClusterEventRelayTest} can only stub. + * + *

Each node gets its own {@link ClusterEventRelay} sharing the one topic. A recording + * {@link ApplicationEventPublisher} on each node captures what the relay re-fires locally, standing in for the + * real kernel listeners (which is where the actual eviction would run). The assertions: + * + *

    + *
  • a {@link SiteChangedEvent} raised on A appears as a reconstructed local {@link SiteChangedEvent} on B + * (same site + kind), and does NOT re-appear on A (the origin drops its own echo);
  • + *
  • a {@link PageChangedEvent} raised on A appears as a local {@link PageChangedEvent} on B — the fine-grained + * page invalidation that was once purely local.
  • + *
+ * + *

Two in-JVM members over loopback tcp-ip on an isolated (nanotime-suffixed) cluster name; no network beyond + * loopback, no external broker — safe offline. + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class ClusterEventRelayTwoNodeTest { + + private static final int PORT_A = 15901; + private static final int PORT_B = 15902; + private static final String TOPIC = "runway.events"; + + private HazelcastInstance nodeA; + private HazelcastInstance nodeB; + private RecordingPublisher publisherA; + private RecordingPublisher publisherB; + private ClusterEventRelay relayA; + private ClusterEventRelay relayB; + + @BeforeAll + void startTwoMemberClusterWithRelays() { + String cluster = "rw-relay-test-" + System.nanoTime(); + nodeA = member(cluster, PORT_A); + nodeB = member(cluster, PORT_B); + Awaitility.await().atMost(30, TimeUnit.SECONDS) + .until(() -> nodeA.getCluster().getMembers().size() == 2 + && nodeB.getCluster().getMembers().size() == 2); + + RunwayClusterProperties props = new RunwayClusterProperties(); // default topic "runway.events" + publisherA = new RecordingPublisher(); + publisherB = new RecordingPublisher(); + relayA = new ClusterEventRelay(nodeA, publisherA, props); + relayB = new ClusterEventRelay(nodeB, publisherB, props); + relayA.subscribe(); + relayB.subscribe(); + } + + private static HazelcastInstance member(String clusterName, int port) { + Config config = new Config().setClusterName(clusterName); + config.setProperty("hazelcast.phone.home.enabled", "false"); + JoinConfig join = config.getNetworkConfig() + .setPort(port).setPortAutoIncrement(false) + .getJoin(); + join.getAutoDetectionConfig().setEnabled(false); + join.getMulticastConfig().setEnabled(false); + join.getTcpIpConfig().setEnabled(true) + .setMembers(List.of("127.0.0.1:" + PORT_A, "127.0.0.1:" + PORT_B)); + return Hazelcast.newHazelcastInstance(config); + } + + @AfterAll + void stopCluster() { + if (relayA != null) { + relayA.unsubscribe(); + } + if (relayB != null) { + relayB.unsubscribe(); + } + if (nodeA != null) { + nodeA.shutdown(); + } + if (nodeB != null) { + nodeB.shutdown(); + } + } + + @Test + void aSiteChangeOnNodeAIsReDeliveredAsALocalEventOnNodeBOnly() { + publisherA.events.clear(); + publisherB.events.clear(); + + // Node A raises a local site change — its relay broadcasts it to the topic. + relayA.onSiteChanged(new SiteChangedEvent("demo", SiteChangedEvent.Kind.RESTORED, null)); + + // Node B's relay receives it and re-fires an equivalent local SiteChangedEvent (which is where B's + // caches would evict). + Awaitility.await().atMost(15, TimeUnit.SECONDS).until(() -> !publisherB.of(SiteChangedEvent.class).isEmpty()); + List onB = publisherB.of(SiteChangedEvent.class); + assertEquals(1, onB.size(), "node B re-fires exactly one local SiteChangedEvent"); + assertEquals("demo", onB.get(0).siteId()); + assertEquals(SiteChangedEvent.Kind.RESTORED, onB.get(0).kind()); + + // Node A must NOT re-fire its own event locally (it drops the self-echo Hazelcast delivers back). + assertTrue(publisherA.of(SiteChangedEvent.class).isEmpty(), + "the origin node drops its own echo — no local re-fire on A"); + } + + @Test + void aPageChangeOnNodeAReachesNodeBAsALocalPageEvent() { + publisherA.events.clear(); + publisherB.events.clear(); + + relayA.onPageChanged(new PageChangedEvent("demo", "about")); + + Awaitility.await().atMost(15, TimeUnit.SECONDS).until(() -> !publisherB.of(PageChangedEvent.class).isEmpty()); + List onB = publisherB.of(PageChangedEvent.class); + assertEquals(1, onB.size(), "node B re-fires exactly one local PageChangedEvent"); + assertEquals("demo", onB.get(0).siteId()); + assertEquals("about", onB.get(0).slug()); + assertTrue(publisherA.of(PageChangedEvent.class).isEmpty(), "no self-echo re-fire on the origin node"); + } + + /** + * A peer's replay evicts its plugin-settings cache, carries {@code fromBackup}, and reaches the + * peer's SPI listeners as {@code local == false} — while the listener already reads the new settings. Node B's + * publisher forwards each replayed event to the real kernel listeners it stands in for, in their order. + */ + @Test + void aPeerReplayEvictsSettingsAndReachesListenersAsNotLocal() throws Exception { + java.nio.file.Path external = java.nio.file.Files.createTempDirectory("runway-k3-peer"); + mx.quest.runway.storage.StorageProperties storage = new mx.quest.runway.storage.StorageProperties(); + storage.setExternal(external); + mx.quest.runway.storage.StorageLayout layout = mx.quest.runway.storage.StorageLayout.from(storage); + java.nio.file.Path file = java.nio.file.Files.createDirectories(layout.siteDir("demo").resolve("plugins")) + .resolve("search.yml"); + java.nio.file.Files.writeString(file, "mode: old\n"); + mx.quest.runway.plugin.SitePluginConfigService configB = new mx.quest.runway.plugin.SitePluginConfigService( + layout, org.mockito.Mockito.mock(mx.quest.runway.crypto.SecretCipher.class), event -> { }); + assertEquals("old", configB.config("demo", "search").get("mode"), "node B has the value cached"); + + List seenOnB = new CopyOnWriteArrayList<>(); + mx.quest.runway.spi.service.SiteEventListener listener = new mx.quest.runway.spi.service.SiteEventListener() { + @Override + public void onSettingsChanged(mx.quest.runway.spi.model.SettingsChange change) { + seenOnB.add(change); + seenOnB.add(configB.config("demo", "search").get("mode")); // what a plugin re-reads here + } + + @Override + public void onSiteLifecycle(mx.quest.runway.spi.model.SiteLifecycleEvent event) { + seenOnB.add(event); + } + }; + mx.quest.runway.event.SpiEventBridge bridgeB = new mx.quest.runway.event.SpiEventBridge(() -> List.of(listener), + () -> new mx.quest.runway.content.ContentCatalog(new mx.quest.runway.content.ContentSourceRegistry( + List.of())), id -> java.util.Optional.empty(), + mx.quest.runway.plugin.ContributionGuard.standalone(), + contribution -> java.util.Optional.of("search"), id -> 0, () -> null); + bridgeB.collect(); + publisherB.forward = event -> { + if (event instanceof mx.quest.runway.plugin.SitePluginConfigChangedEvent e) { + configB.onConfigChanged(e); // KernelEventOrder.STORES + bridgeB.onSitePluginConfigChanged(e); // KernelEventOrder.PLUGIN_DISPATCH + } else if (event instanceof SiteChangedEvent e) { + bridgeB.onSiteChanged(e); + } + }; + try { + // Node A saved (shared storage) and announced the change. + java.nio.file.Files.writeString(file, "mode: new\n"); + relayA.onSitePluginConfigChanged(new mx.quest.runway.plugin.SitePluginConfigChangedEvent("demo", + "search")); + relayA.onSiteChanged(SiteChangedEvent.createdFromBackup("demo")); + Awaitility.await().atMost(15, TimeUnit.SECONDS).until(() -> seenOnB.size() >= 3); + + mx.quest.runway.spi.model.SettingsChange change = (mx.quest.runway.spi.model.SettingsChange) seenOnB.get(0); + assertEquals("search", change.pluginId()); + assertFalse(change.local(), "a replayed change is not local: side effects stay on the origin node"); + assertEquals("new", seenOnB.get(1), "the peer's settings cache was evicted before the listener ran"); + mx.quest.runway.spi.model.SiteLifecycleEvent created = + (mx.quest.runway.spi.model.SiteLifecycleEvent) seenOnB.get(2); + assertTrue(created.fromBackup(), "fromBackup crosses the cluster (review m14a)"); + assertFalse(created.local()); + } finally { + publisherB.forward = null; + } + } + + /** Captures every object the relay re-publishes locally, so the test can inspect the cross-node deliveries. */ + private static final class RecordingPublisher implements ApplicationEventPublisher { + private final List events = new CopyOnWriteArrayList<>(); + /** Optionally hands each replayed event on (to the kernel listeners a test stands in for). */ + volatile java.util.function.Consumer forward; + + @Override + public void publishEvent(Object event) { + events.add(event); + java.util.function.Consumer next = forward; + if (next != null) { + next.accept(event); + } + } + + @Override + public void publishEvent(ApplicationEvent event) { + publishEvent((Object) event); + } + + @SuppressWarnings("unchecked") + List of(Class type) { + return events.stream().filter(type::isInstance).map(e -> (T) e).toList(); + } + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/cluster/HazelcastSessionRepositoryTest.java b/runway-app/src/test/java/mx/quest/runway/cluster/HazelcastSessionRepositoryTest.java new file mode 100644 index 0000000..862a5f1 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/cluster/HazelcastSessionRepositoryTest.java @@ -0,0 +1,173 @@ +package mx.quest.runway.cluster; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.hazelcast.config.Config; +import com.hazelcast.config.JoinConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.map.IMap; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.spi.model.Realm; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextImpl; +import org.springframework.session.MapSession; +import org.springframework.session.SessionRepository; + +/** + * Drives the hand-rolled {@link HazelcastSessionRepository} against a real, two-member embedded + * Hazelcast cluster to prove the whole clustered-session promise end to end: + * + *
    + *
  • a session (with a serialized Spring-Security principal attribute) saved through node A is visible on + * node B — the point of clustering;
  • + *
  • the repository's {@code createSession} / {@code save} / {@code findById} / {@code deleteById} contract, + * its defensive copies, its session-id rotation on save, and its expiry handling all behave.
  • + *
+ * + *

Two in-JVM members joined over loopback tcp-ip on an isolated (nanotime-suffixed) cluster name; the map's + * entries round-trip through Hazelcast's default Java serializer, exercising the same path a real deployment + * uses. No network beyond loopback, no external broker — safe offline. + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class HazelcastSessionRepositoryTest { + + private static final int PORT_A = 15801; + private static final int PORT_B = 15802; + private static final String MAP = "runway.sessions"; + private static final Duration TTL = Duration.ofMinutes(30); + + private HazelcastInstance nodeA; + private HazelcastInstance nodeB; + private SessionRepository repoA; + private SessionRepository repoB; + + @BeforeAll + void startTwoMemberCluster() { + String cluster = "rw-session-test-" + System.nanoTime(); + nodeA = member(cluster, PORT_A); + nodeB = member(cluster, PORT_B); + // Wait until both members actually see each other, so a save on one is guaranteed visible on the other. + Awaitility.await().atMost(30, TimeUnit.SECONDS) + .until(() -> nodeA.getCluster().getMembers().size() == 2 + && nodeB.getCluster().getMembers().size() == 2); + IMap mapA = nodeA.getMap(MAP); + IMap mapB = nodeB.getMap(MAP); + repoA = new HazelcastSessionRepository(mapA, TTL); + repoB = new HazelcastSessionRepository(mapB, TTL); + } + + private static HazelcastInstance member(String clusterName, int port) { + Config config = new Config().setClusterName(clusterName); + // Keep the test quiet/offline: no phone-home, no auto-detection, explicit loopback members only. + config.setProperty("hazelcast.phone.home.enabled", "false"); + JoinConfig join = config.getNetworkConfig() + .setPort(port).setPortAutoIncrement(false) + .getJoin(); + join.getAutoDetectionConfig().setEnabled(false); + join.getMulticastConfig().setEnabled(false); + join.getTcpIpConfig().setEnabled(true) + .setMembers(List.of("127.0.0.1:" + PORT_A, "127.0.0.1:" + PORT_B)); + return Hazelcast.newHazelcastInstance(config); + } + + @AfterAll + void stopCluster() { + if (nodeA != null) { + nodeA.shutdown(); + } + if (nodeB != null) { + nodeB.shutdown(); + } + } + + @Test + void aSessionSavedOnOneNodeIsReadableWithItsPrincipalOnAnother() { + MapSession session = repoA.createSession(); + assertEquals(TTL, session.getMaxInactiveInterval(), "createSession stamps the configured TTL"); + + // Store the exact attribute a logged-in request would: a SecurityContext with a RunwayUserDetails + // principal. This is what forces the whole identity graph across the wire. + User user = new User("app-master", "root", "hash", "Root", "", true, true, Realm.APPLICATION, + java.util.Set.of(Roles.SYSTEM_SUPERADMIN), List.of("*")); + RunwayUserDetails principal = new RunwayUserDetails(user); + SecurityContextImpl securityContext = new SecurityContextImpl( + UsernamePasswordAuthenticationToken.authenticated(principal, "hash", principal.getAuthorities())); + session.setAttribute("SPRING_SECURITY_CONTEXT::acme", securityContext); + String id = session.getId(); + repoA.save(session); + + // Read it back through the OTHER node's repository — the cross-node visibility that is the whole point. + MapSession fromB = repoB.findById(id); + assertNotNull(fromB, "a session saved on node A must be found on node B"); + SecurityContextImpl restored = fromB.getAttribute("SPRING_SECURITY_CONTEXT::acme"); + assertNotNull(restored); + RunwayUserDetails restoredPrincipal = (RunwayUserDetails) restored.getAuthentication().getPrincipal(); + assertEquals("app-master", restoredPrincipal.principalId()); + assertEquals(Realm.APPLICATION, restoredPrincipal.realm()); + assertTrue(restoredPrincipal.master()); + } + + @Test + void findReturnsADefensiveCopyNotTheStoredObject() { + MapSession session = repoA.createSession(); + session.setAttribute("k", "v1"); + repoA.save(session); + + MapSession first = repoA.findById(session.getId()); + assertNotSame(session, first, "findById returns a fresh copy, never the caller's object"); + // Mutating the returned copy must not change the stored entry until an explicit save. + first.setAttribute("k", "MUTATED"); + MapSession second = repoA.findById(session.getId()); + assertEquals("v1", second.getAttribute("k"), "an unsaved mutation must not leak into the store"); + } + + @Test + void saveUnderARotatedIdRemovesTheOldKey() { + MapSession session = repoA.createSession(); + String original = session.getId(); + repoA.save(session); + + String rotated = session.changeSessionId(); // Spring Security does this on login (fixation defense) + repoA.save(session); + + assertNull(repoB.findById(original), "the pre-rotation id must be gone cluster-wide"); + assertNotNull(repoB.findById(rotated), "the rotated id must be the live one"); + } + + @Test + void deleteRemovesTheSessionClusterWide() { + MapSession session = repoA.createSession(); + repoA.save(session); + assertNotNull(repoB.findById(session.getId())); + + repoB.deleteById(session.getId()); + assertNull(repoA.findById(session.getId()), "a delete on one node removes it everywhere"); + } + + @Test + void findTreatsAnExpiredSessionAsAbsentAndEvictsIt() { + MapSession session = repoA.createSession(); + session.setMaxInactiveInterval(Duration.ZERO); // already idle-expired + session.setLastAccessedTime(java.time.Instant.now().minusSeconds(60)); + repoA.save(session); + + assertNull(repoA.findById(session.getId()), "an expired session reads as null"); + // And it was actively evicted, not merely hidden: the raw map no longer holds it. + assertNull(nodeA.getMap(MAP).get(session.getId()), "the expired entry was deleted on read"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/cluster/SessionPrincipalSerializationTest.java b/runway-app/src/test/java/mx/quest/runway/cluster/SessionPrincipalSerializationTest.java new file mode 100644 index 0000000..62f78ab --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/cluster/SessionPrincipalSerializationTest.java @@ -0,0 +1,82 @@ +package mx.quest.runway.cluster; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.List; +import java.util.Set; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.RunwayUserDetails; +import mx.quest.runway.security.User; +import mx.quest.runway.spi.model.Realm; +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextImpl; + +/** + * The guard against a non-serializable field creeping into {@link User} or {@link RunwayUserDetails} and + * silently breaking clustered sessions. When {@code runway.cluster.enabled=true}, Spring Security's + * {@code SecurityContext} — with a {@link RunwayUserDetails} principal — is stored as an {@code HttpSession} + * attribute and serialized into the Hazelcast sessions {@code IMap}. If any field on the identity graph were + * not {@link java.io.Serializable}, the write would throw at runtime, on a node other than the author's, long + * after this change shipped. This test round-trips the exact object graph through plain Java serialization + * (the {@code IMap}'s default serializer) so such a regression fails at build time instead. + * + *

Pure unit test — no Spring, no Hazelcast — because Java serialization is precisely what the grid uses. + */ +class SessionPrincipalSerializationTest { + + @Test + void aSecurityContextWrappingRunwayUserDetailsRoundTripsThroughJavaSerialization() throws Exception { + User user = new User("app-master", "root", "$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA", "Root", + "root@example.test", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN, Roles.SYSTEM_ADMIN), List.of("*")); + RunwayUserDetails principal = new RunwayUserDetails(user); + UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.authenticated( + principal, principal.getPassword(), principal.getAuthorities()); + SecurityContextImpl context = new SecurityContextImpl(auth); + + SecurityContextImpl restored = roundTrip(context); + + // The whole graph survived — and it is a genuinely fresh copy, not the same reference. + assertNotSame(context, restored); + RunwayUserDetails restoredPrincipal = + assertInstanceOf(RunwayUserDetails.class, restored.getAuthentication().getPrincipal()); + + // Identity + realm + authorities survived the trip intact. + assertEquals("app-master", restoredPrincipal.principalId()); + assertEquals("root", restoredPrincipal.getUsername()); + assertEquals(Realm.APPLICATION, restoredPrincipal.realm()); + assertTrue(restoredPrincipal.master()); + assertTrue(restoredPrincipal.assignedTo("any-site")); // "*" assignment survived + assertEquals( + Set.of(Roles.AUTHORITY_PREFIX + Roles.SYSTEM_SUPERADMIN, Roles.AUTHORITY_PREFIX + Roles.SYSTEM_ADMIN), + restoredPrincipal.getAuthorities().stream().map(Object::toString) + .collect(java.util.stream.Collectors.toSet())); + } + + @Test + void theUserRecordAloneRoundTripsAndEqualsItself() throws Exception { + User user = new User("u1", "alice", "hash", "Alice", "", true, false, Realm.TENANT, + Set.of(Roles.ADMIN), List.of("acme")); + // The record's generated equals compares every component — a clean round-trip must equal the original. + assertEquals(user, roundTrip(user)); + } + + @SuppressWarnings("unchecked") + private static T roundTrip(T value) throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { + out.writeObject(value); + } + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + return (T) in.readObject(); + } + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AccountPasswordCheckLimitTest.java b/runway-app/src/test/java/mx/quest/runway/console/AccountPasswordCheckLimitTest.java new file mode 100644 index 0000000..e2d02ed --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AccountPasswordCheckLimitTest.java @@ -0,0 +1,342 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import mx.quest.runway.log.AppActivityLog; +import mx.quest.runway.security.AppUserStore; +import mx.quest.runway.security.LoginAttemptGate; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.SiteUserStore; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteContextFilter; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * The current-password check on the Account screen is limited, in both realms and on both forms: five wrong + * guesses in a row in one session drop that session's sign-in (the kernel's own floor, no plugin needed); every wrong + * guess is reported to the per-IP {@link LoginAttemptGate} and journaled; a locked IP is refused before any password + * is checked; a right password resets the count. A counting gate stands in for the protection plugin, so the test + * proves the forms reach the gate rather than inferring it from the absence of a lockout. + */ +@SpringBootTest +class AccountPasswordCheckLimitTest { + + private static final String PW = "Reverify-Limit-Secret-9"; + + /** A gate that counts what reaches it and locks on demand. */ + static final class CountingGate implements LoginAttemptGate { + final AtomicInteger failures = new AtomicInteger(); + final AtomicBoolean locked = new AtomicBoolean(); + + @Override + public boolean isLocked(String clientIp) { + return locked.get(); + } + + @Override + public void recordFailure(String clientIp) { + failures.incrementAndGet(); + } + + @Override + public void recordSuccess(String clientIp) { + } + } + + @TestConfiguration + static class Gate { + @Bean + @Primary + CountingGate countingGate() { + return new CountingGate(); + } + } + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-reverify"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + new SiteStore(layout, yaml).save(new Site("acme", "Acme", List.of("localhost"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + UserStore users = new UserStore(yaml); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + Path appFile = external.resolve("app-users.yml"); + users.save(appFile, new User("app-master", "root", hash, "Root", "", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + for (String op : new String[] {"op1", "op2", "op3", "op4", "op5"}) { + users.save(appFile, new User(op + "-id", op, hash, op, op + "@old.test", true, false, Realm.APPLICATION, + Set.of(Roles.SYSTEM_OPERATOR), List.of())); + } + users.save(layout.siteDir("acme").resolve("users.yml"), new User("ed1-id", "ed1", hash, "Ed", "", true, + false, Realm.TENANT, Set.of(Roles.OPERATOR), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteResolver siteResolver; + @Autowired + private AppUserStore appUsers; + @Autowired + private SiteUserStore siteUsers; + @Autowired + private AppActivityLog activity; + @Autowired + private CountingGate gate; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new SiteContextFilter(siteResolver)) + .apply(springSecurity()).build(); + gate.locked.set(false); + gate.failures.set(0); + } + + private static RequestPostProcessor localhost() { + return request -> { + request.setServerName("localhost"); + return request; + }; + } + + private MockHttpSession appLogin(String username) throws Exception { + MvcResult result = mvc.perform(formLogin("/app/login").user(username).password(PW)) + .andExpect(redirectedUrl("/__app")).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private MockHttpSession siteLogin(String username) throws Exception { + MvcResult result = mvc.perform(post("/login").with(localhost()).with(csrf()) + .param("username", username).param("password", PW)) + .andExpect(redirectedUrl("/__admin")).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private void wrongEmailGuess(MockHttpSession session, String user) throws Exception { + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", user).param("recoveryEmail", "attacker@evil.test") + .param("currentPassword", "guess")) + .andExpect(redirectedUrl("/__app/account")) + .andExpect(flash().attribute("error", "The current password is incorrect.")); + } + + private long journaled(String user) { + return activity.tail(200).stream() + .filter(line -> line.contains("account.password-check-failed") && line.contains(user)).count(); + } + + @Test + void fiveWrongGuessesOnTheEmailFormEndTheSession() throws Exception { + MockHttpSession session = appLogin("op1"); + for (int i = 1; i < AccountSupport.MAX_WRONG_PASSWORDS; i++) { + wrongEmailGuess(session, "op1"); + } + assertEquals(AccountSupport.MAX_WRONG_PASSWORDS - 1, gate.failures.get(), "each guess reached the IP gate"); + assertEquals(AccountSupport.MAX_WRONG_PASSWORDS - 1, journaled("op1"), "each guess is journaled"); + assertTrue(activity.tail(200).stream().filter(line -> line.contains("account.password-check-failed") + && line.contains("op1")).allMatch(line -> line.endsWith("\tip=127.0.0.1")), + "with the client's IP: " + activity.tail(200)); + + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op1").param("recoveryEmail", "attacker@evil.test") + .param("currentPassword", "guess")) + .andExpect(redirectedUrl("/app/login?reverify")); + mvc.perform(get("/__app").session(session)).andExpect(status().is3xxRedirection()); + // The spent session cannot try again, even with the right password. + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op1").param("recoveryEmail", "attacker@evil.test") + .param("currentPassword", PW)) + .andExpect(status().is3xxRedirection()); + assertEquals("op1@old.test", appUsers.findByPrincipalId("op1-id").orElseThrow().recoveryEmail()); + + String page = mvc.perform(get("/app/login").param("reverify", "")).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + assertTrue(page.contains("too many wrong passwords on your account page"), "the sign-in page says why"); + appLogin("op1"); // the owner signs in again as usual + } + + /** A session whose attributes may be read and written by several requests at once, as a server's session is. */ + static final class ConcurrentSession extends MockHttpSession { + private final java.util.concurrent.ConcurrentHashMap attrs = + new java.util.concurrent.ConcurrentHashMap<>(); + + ConcurrentSession(MockHttpSession from) { + for (String name : java.util.Collections.list(from.getAttributeNames())) { + attrs.put(name, from.getAttribute(name)); + } + } + + @Override + public Object getAttribute(String name) { + return attrs.get(name); + } + + @Override + public void setAttribute(String name, Object value) { + if (value == null) { + attrs.remove(name); + } else { + attrs.put(name, value); + } + } + + @Override + public void removeAttribute(String name) { + attrs.remove(name); + } + + @Override + public java.util.Enumeration getAttributeNames() { + return java.util.Collections.enumeration(new java.util.ArrayList<>(attrs.keySet())); + } + } + + /** + * The count was read and written back by each request, so eight guesses sent at the same moment + * were all checked (the documented floor is five). The count is now reserved before hashing. + */ + @Test + void guessesSentAtTheSameMomentAreHeldToTheLimit() throws Exception { + ConcurrentSession session = new ConcurrentSession(appLogin("op5")); + int burst = 8; + java.util.concurrent.ExecutorService pool = java.util.concurrent.Executors.newFixedThreadPool(burst); + java.util.concurrent.CountDownLatch go = new java.util.concurrent.CountDownLatch(1); + List> guesses = new java.util.ArrayList<>(); + try { + for (int i = 0; i < burst; i++) { + guesses.add(pool.submit(() -> { + go.await(); + return mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op5").param("recoveryEmail", "attacker@evil.test") + .param("currentPassword", "guess")).andReturn(); + })); + } + go.countDown(); + for (java.util.concurrent.Future guess : guesses) { + guess.get(60, java.util.concurrent.TimeUnit.SECONDS); + } + } finally { + pool.shutdownNow(); + } + assertTrue(gate.failures.get() <= AccountSupport.MAX_WRONG_PASSWORDS, + "at most five guesses were checked, not " + gate.failures.get()); + assertTrue(journaled("op5") <= AccountSupport.MAX_WRONG_PASSWORDS, "and journaled"); + mvc.perform(get("/__app").session(session)).andExpect(status().is3xxRedirection()); + assertEquals("op5@old.test", appUsers.findByPrincipalId("op5-id").orElseThrow().recoveryEmail()); + } + + @Test + void aRightPasswordResetsTheCount() throws Exception { + MockHttpSession session = appLogin("op2"); + for (int i = 1; i < AccountSupport.MAX_WRONG_PASSWORDS; i++) { + wrongEmailGuess(session, "op2"); + } + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op2").param("recoveryEmail", "op2@new.test") + .param("currentPassword", PW)) + .andExpect(flash().attribute("flash", "Your profile has been saved.")); + for (int i = 1; i < AccountSupport.MAX_WRONG_PASSWORDS; i++) { + wrongEmailGuess(session, "op2"); + } + mvc.perform(get("/__app").session(session)).andExpect(status().isOk()); + } + + @Test + void aBlankPasswordIsAPromptNotAGuess() throws Exception { + MockHttpSession session = appLogin("op3"); + for (int i = 0; i < AccountSupport.MAX_WRONG_PASSWORDS + 1; i++) { + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op3").param("recoveryEmail", "op3@new.test")) + .andExpect(flash().attribute("error", + "Enter your current password to change your recovery email.")); + } + assertEquals(0, gate.failures.get()); + mvc.perform(get("/__app").session(session)).andExpect(status().isOk()); + } + + @Test + void aLockedNetworkIsRefusedBeforeThePasswordIsChecked() throws Exception { + MockHttpSession session = appLogin("op4"); + gate.locked.set(true); + mvc.perform(post("/__app/account").session(session).with(csrf()) + .param("currentPassword", PW).param("newPassword", "Another-Secret-77") + .param("confirmPassword", "Another-Secret-77")) + .andExpect(redirectedUrl("/__app/account")) + .andExpect(flash().attribute("error", + "Too many failed sign-in attempts from your network. Wait a few minutes, then try again.")); + assertTrue(PasswordEncoders.argon2id(PasswordStrength.STANDARD) + .matches(PW, appUsers.findByPrincipalId("op4-id").orElseThrow().passwordHash()), + "not changed, even with the right password"); + } + + @Test + void theSitePasswordFormIsLimitedToo() throws Exception { + MockHttpSession session = siteLogin("ed1"); + for (int i = 1; i < AccountSupport.MAX_WRONG_PASSWORDS; i++) { + mvc.perform(post("/__admin/account").with(localhost()).session(session).with(csrf()) + .param("currentPassword", "guess").param("newPassword", "Taken-Over-55") + .param("confirmPassword", "Taken-Over-55")) + .andExpect(redirectedUrl("/__admin/account")) + .andExpect(flash().attribute("error", "The current password is incorrect.")); + } + mvc.perform(post("/__admin/account").with(localhost()).session(session).with(csrf()) + .param("currentPassword", "guess").param("newPassword", "Taken-Over-55") + .param("confirmPassword", "Taken-Over-55")) + .andExpect(redirectedUrl("/login?reverify")); + assertEquals(AccountSupport.MAX_WRONG_PASSWORDS, gate.failures.get()); + mvc.perform(get("/__admin").with(localhost()).session(session)).andExpect(status().is3xxRedirection()); + User ed = siteUsers.list("acme").stream().filter(u -> u.username().equals("ed1")).findFirst().orElseThrow(); + assertTrue(PasswordEncoders.argon2id(PasswordStrength.STANDARD).matches(PW, ed.passwordHash())); + String page = mvc.perform(get("/login").with(localhost()).param("reverify", "")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertTrue(page.contains("too many wrong passwords on your account page"), "the sign-in page says why"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AccountProfileTest.java b/runway-app/src/test/java/mx/quest/runway/console/AccountProfileTest.java new file mode 100644 index 0000000..626979c --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AccountProfileTest.java @@ -0,0 +1,201 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.security.AppUserStore; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.SiteUserStore; +import mx.quest.runway.security.TenantMasterStore; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteContextFilter; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * Your own profile on the Account screen, in both realms: the display name saves freely, the recovery email only + * with the current password (it is where a reset link goes), invalid input changes nothing, and only the signed-in + * user's own record is touched. Each test uses its own account, so the order never matters. + */ +@SpringBootTest +class AccountProfileTest { + + private static final String PW = "Profile-Edit-Secret-9"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-profile"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + new SiteStore(layout, yaml).save(new Site("acme", "Acme", List.of("localhost"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + UserStore users = new UserStore(yaml); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + Path appFile = external.resolve("app-users.yml"); + users.save(appFile, new User("app-master", "root", hash, "Root", "", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + for (String op : new String[] {"op1", "op2", "op3"}) { + users.save(appFile, new User(op + "-id", op, hash, op, op + "@old.test", true, false, Realm.APPLICATION, + Set.of(Roles.SYSTEM_OPERATOR), List.of())); + } + users.save(layout.siteDir("acme").resolve("users.yml"), new User("ed1-id", "ed1", hash, "Ed", "", true, + false, Realm.TENANT, Set.of(Roles.OPERATOR), List.of())); + users.save(external.resolve("site-users.yml"), new User("tm1-id", "tm1", hash, "TM1", "tm@old.test", true, + true, Realm.TENANT, Set.of(Roles.SUPERADMIN), List.of("acme"))); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteResolver siteResolver; + @Autowired + private AppUserStore appUsers; + @Autowired + private SiteUserStore siteUsers; + @Autowired + private TenantMasterStore masters; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new SiteContextFilter(siteResolver)) + .apply(springSecurity()).build(); + } + + private static RequestPostProcessor localhost() { + return request -> { + request.setServerName("localhost"); + return request; + }; + } + + private MockHttpSession appLogin(String username) throws Exception { + MvcResult result = mvc.perform(formLogin("/app/login").user(username).password(PW)) + .andExpect(redirectedUrl("/__app")).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private MockHttpSession siteLogin(String username) throws Exception { + MvcResult result = mvc.perform(post("/login").with(localhost()).with(csrf()) + .param("username", username).param("password", PW)) + .andExpect(redirectedUrl("/__admin")).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private User app(String id) { + return appUsers.findByPrincipalId(id).orElseThrow(); + } + + @Test + void anOperatorRenamesThemselvesWithoutTheirPassword() throws Exception { + MockHttpSession session = appLogin("op1"); + String html = mvc.perform(get("/__app/account").session(session)).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + assertTrue(html.contains("action=\"/__app/account/profile\""), "the profile form posts to its endpoint"); + assertTrue(html.contains("value=\"op1@old.test\""), "the recovery email is prefilled"); + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", " Olga Operator ").param("recoveryEmail", "op1@old.test")) + .andExpect(flash().attribute("flash", "Your profile has been saved.")); + assertEquals("Olga Operator", app("op1-id").displayName()); + assertEquals("op1@old.test", app("op1-id").recoveryEmail(), "the email is unchanged"); + mvc.perform(get("/__app").session(session)).andExpect(status().isOk()); // still signed in + } + + @Test + void changingTheRecoveryEmailNeedsTheCurrentPassword() throws Exception { + MockHttpSession session = appLogin("op2"); + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op2").param("recoveryEmail", "attacker@evil.test")) + .andExpect(flash().attribute("error", "Enter your current password to change your recovery email.")); + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op2").param("recoveryEmail", "attacker@evil.test") + .param("currentPassword", "wrong")) + .andExpect(flash().attributeExists("error")); + assertEquals("op2@old.test", app("op2-id").recoveryEmail(), "unchanged without the right password"); + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "op2").param("recoveryEmail", "op2@new.test") + .param("currentPassword", PW)) + .andExpect(flash().attribute("flash", "Your profile has been saved.")); + assertEquals("op2@new.test", app("op2-id").recoveryEmail()); + } + + @Test + void anInvalidEmailOrOverlongNameChangesNothing() throws Exception { + MockHttpSession session = appLogin("op3"); + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "New").param("recoveryEmail", "not an address") + .param("currentPassword", PW)) + .andExpect(flash().attributeExists("error")); + mvc.perform(post("/__app/account/profile").session(session).with(csrf()) + .param("displayName", "x".repeat(129)).param("recoveryEmail", "op3@old.test")) + .andExpect(flash().attributeExists("error")); + assertEquals("op3", app("op3-id").displayName()); + assertEquals("op3@old.test", app("op3-id").recoveryEmail()); + } + + @Test + void aSiteUserAndATenantSuperadminEditTheirOwnRecord() throws Exception { + MockHttpSession editor = siteLogin("ed1"); + mvc.perform(post("/__admin/account/profile").with(localhost()).session(editor).with(csrf()) + .param("displayName", "Edith").param("recoveryEmail", "ed@acme.test") + .param("currentPassword", PW)) + .andExpect(flash().attribute("flash", "Your profile has been saved.")); + User ed = siteUsers.list("acme").stream().filter(u -> u.username().equals("ed1")).findFirst().orElseThrow(); + assertEquals("Edith", ed.displayName()); + assertEquals("ed@acme.test", ed.recoveryEmail()); + + MockHttpSession master = siteLogin("tm1"); + mvc.perform(post("/__admin/account/profile").with(localhost()).session(master).with(csrf()) + .param("displayName", "Tina").param("recoveryEmail", "tm@old.test")) + .andExpect(flash().attribute("flash", "Your profile has been saved.")); + User tm = masters.findByUsername("tm1").orElseThrow(); + assertEquals("Tina", tm.displayName()); + assertEquals(List.of("acme"), tm.sites(), "the assignment is untouched"); + } + + @Test + void aProfileSaveWithoutCsrfIsRefused() throws Exception { + mvc.perform(post("/__app/account/profile").session(appLogin("root")).param("displayName", "X")) + .andExpect(status().isForbidden()); + assertEquals("Root", app("app-master").displayName()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AccountScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/AccountScreenTest.java new file mode 100644 index 0000000..450c6f3 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AccountScreenTest.java @@ -0,0 +1,125 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.security.AppUserStore; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** The application Account screen: change-your-own-password with current-verify + confirm rules. */ +@SpringBootTest +@org.junit.jupiter.api.TestMethodOrder(org.junit.jupiter.api.MethodOrderer.OrderAnnotation.class) +class AccountScreenTest { + + private static final String PASSWORD = "Account-Old-Secret-9"; + private static Path external; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + external = Files.createTempDirectory("runway-fe"); + seedMaster(); // the context validates the app identity at startup — the master must exist before boot + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + private static void seedMaster() { + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PASSWORD); + new UserStore(new YamlStore()).save(external.resolve("app-users.yml"), + new User("app-master", "admin", hash, "Admin", "a@x", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private AppUserStore appUsers; + @Autowired + private PasswordEncoder passwordEncoder; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + // Re-seed the master at the known password so each test starts from a clean credential (the store + // reads fresh from disk, so a prior test's change does not leak). + seedMaster(); + } + + private MockHttpSession login() throws Exception { + MvcResult result = mvc.perform(formLogin("/app/login").user("admin").password(PASSWORD)).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private String currentHash() { + return appUsers.findByPrincipalId("app-master").orElseThrow().passwordHash(); + } + + @Test + @org.junit.jupiter.api.Order(1) + void theAccountFormRenders() throws Exception { + mvc.perform(get("/__app/account").session(login())) + .andExpect(status().isOk()) + .andExpect(content().string(org.hamcrest.Matchers.containsString("name=\"currentPassword\""))); + } + + @Test + @org.junit.jupiter.api.Order(4) // last: it changes the login credential + void changingWithTheCorrectCurrentPasswordSucceeds() throws Exception { + mvc.perform(post("/__app/account").session(login()).with(csrf()) + .param("currentPassword", PASSWORD) + .param("newPassword", "Account-New-Secret-9").param("confirmPassword", "Account-New-Secret-9")) + .andExpect(status().is3xxRedirection()); + assertTrue(passwordEncoder.matches("Account-New-Secret-9", currentHash()), "the password was changed"); + } + + @Test + @org.junit.jupiter.api.Order(2) + void aWrongCurrentPasswordIsRejected() throws Exception { + mvc.perform(post("/__app/account").session(login()).with(csrf()) + .param("currentPassword", "not-the-password") + .param("newPassword", "whatever-9").param("confirmPassword", "whatever-9")) + .andExpect(status().is3xxRedirection()); + assertTrue(passwordEncoder.matches(PASSWORD, currentHash()), "the password is unchanged"); + assertFalse(passwordEncoder.matches("whatever-9", currentHash())); + } + + @Test + @org.junit.jupiter.api.Order(3) + void aMismatchedConfirmationIsRejected() throws Exception { + mvc.perform(post("/__app/account").session(login()).with(csrf()) + .param("currentPassword", PASSWORD) + .param("newPassword", "one-9").param("confirmPassword", "two-9")) + .andExpect(status().is3xxRedirection()); + assertTrue(passwordEncoder.matches(PASSWORD, currentHash()), "the password is unchanged on a mismatch"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AppAboutPageTest.java b/runway-app/src/test/java/mx/quest/runway/console/AppAboutPageTest.java new file mode 100644 index 0000000..a380548 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AppAboutPageTest.java @@ -0,0 +1,172 @@ +package mx.quest.runway.console; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import mx.quest.runway.platform.PlatformSettings; +import java.util.Set; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteContextFilter; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * The app-realm About Runway screen renders the effective configuration and runtime environment, is + * reachable to a signed-in operator, exposes both Settings-dropdown children, and — critically — never leaks a + * configured secret (the TLS keystore password or the master secret key). + */ +@SpringBootTest +class AppAboutPageTest { + + private static final String PW = "About-Page-7"; + private static final String TLS_PW = "TLSPW-must-not-leak-4242"; + private static final String SECRET_KEY = "vX9kQ2m-secret-key-must-not-leak-0123456789abcdef0123456789"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-about"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + new SiteStore(layout, yaml).save(new Site("acme", "Acme", List.of("localhost"), + Locale.ENGLISH, List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + UserStore users = new UserStore(yaml); + users.save(external.resolve("app-users.yml"), new User("app-master", "root", hash, "Root", "", true, + true, Realm.APPLICATION, Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + // Configure two real secrets so the "never leaks" assertions are meaningful. + registry.add("runway.security.secret-key", () -> SECRET_KEY); + registry.add("runway.tls.keystore-password", () -> TLS_PW); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteResolver siteResolver; + @Autowired + private RuntimeInfoService info; + @Autowired + private mx.quest.runway.platform.PlatformSettingsStore platform; + private MockMvc mvc; + + private MockMvc mvc() { + if (mvc == null) { + mvc = MockMvcBuilders.webAppContextSetup(context) + .addFilters(new SiteContextFilter(siteResolver)) + .apply(springSecurity()).build(); + } + return mvc; + } + + private MockHttpSession login() throws Exception { + MvcResult r = mvc().perform(formLogin("/app/login").user("root").password(PW)).andReturn(); + return (MockHttpSession) r.getRequest().getSession(false); + } + + @Test + void aboutRendersConfigAndRuntimeSections() throws Exception { + MockHttpSession session = login(); + mvc().perform(get("/__app/about").session(session).locale(Locale.ENGLISH)) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("About Runway"))) + .andExpect(content().string(Matchers.containsString("Effective configuration"))) + .andExpect(content().string(Matchers.containsString("Runtime environment"))) + .andExpect(content().string(Matchers.containsString("Spring Boot"))) // a bundled component + .andExpect(content().string(Matchers.containsString("Argon2id"))); // the password-hashing row + } + + @Test + void aboutNeverLeaksConfiguredSecrets() throws Exception { + MockHttpSession session = login(); + String body = mvc().perform(get("/__app/about").session(session).locale(Locale.ENGLISH)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertThat(body).doesNotContain(TLS_PW); + assertThat(body).doesNotContain(SECRET_KEY); + // Secret-adjacent state is shown only as a boolean; the key is configured, so it reads "configured". + assertThat(body).contains("configured"); + } + + @Test + void settingsDropdownExposesBothChildren() throws Exception { + MockHttpSession session = login(); + mvc().perform(get("/__app/about").session(session).locale(Locale.ENGLISH)) + .andExpect(content().string(Matchers.containsString("grp-settings"))) + .andExpect(content().string(Matchers.containsString("href=\"/__app/about\""))) + .andExpect(content().string(Matchers.containsString("href=\"/__app/settings\""))); + } + + @Test + void aboutRequiresAuthentication() throws Exception { + mvc().perform(get("/__app/about")).andExpect(status().is3xxRedirection()); + } + + @Test + void thePasswordRowShowsTheProfileInForceAndASavedChangeSeparately() { + PlatformSettings before = platform.get(); + try { + assertThat(info.passwordSummary()).isEqualTo("Argon2id · STANDARD"); + platform.update(previous -> before.withPasswordStrength("HIGH")); // saved now, in force only after a restart + assertThat(info.passwordSummary()) + .isEqualTo("Argon2id · STANDARD (HIGH is saved and applies after the next restart)"); + } finally { + platform.update(previous -> before); + } + } + + @Test + void aDataPathReachedThroughALinkShowsWhereItReallyIs(@org.junit.jupiter.api.io.TempDir Path tmp) + throws IOException { + Path real = Files.createDirectories(tmp.resolve("runway-data/external")); + Path link = Files.createSymbolicLink(tmp.resolve("external"), real); + assertThat(RuntimeInfoService.pathSummary(link)).isEqualTo(link + " → " + real.toRealPath()); + assertThat(RuntimeInfoService.pathSummary(real.toRealPath())).isEqualTo(real.toRealPath().toString()); + assertThat(RuntimeInfoService.pathSummary(tmp.resolve("missing"))).isEqualTo(tmp.resolve("missing").toString()); + } + + @Test + void runtimeInfoServiceSnapshotIsPopulated() { + assertThat(info.version()).isNotBlank(); + assertThat(info.runtime()).anyMatch(nv -> nv.name().equals("op.about.rt.java")); + assertThat(info.effectiveConfig()).anyMatch(nv -> nv.name().equals("op.about.cfg.pw")); + // The curated component set resolves — including libs with no Implementation-Version (BouncyCastle, + // Prometheus), the Thymeleaf engine internals (attoparser), and the class-less JS bundle (CodeMirror). + assertThat(info.components()).extracting(RuntimeInfoService.NameValue::name) + .contains("Spring Boot", "Jetty", "Thymeleaf", "attoparser", "Jackson", + "BouncyCastle", "Prometheus", "Micrometer", "CodeMirror", "SLF4J"); + // Every listed component carries a non-blank version (no silent-drop / blank rows). + assertThat(info.components()).allSatisfy(nv -> assertThat(nv.value()).isNotBlank()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AppBackupsScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/AppBackupsScreenTest.java new file mode 100644 index 0000000..1aaa5f4 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AppBackupsScreenTest.java @@ -0,0 +1,200 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import mx.quest.runway.backup.BackupService; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** App-realm backups: render, download any site, and create a NEW site from an uploaded backup. */ +@SpringBootTest +class AppBackupsScreenTest { + + private static final String PW = "App-Bk-7"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-appbk"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + new SiteStore(layout, yaml).save(new Site("acme", "Acme", List.of("acme.test"), Locale.ENGLISH, + List.of(Locale.ENGLISH), "https://acme.test", SiteStatus.ACTIVE)); + Files.createDirectories(layout.siteDir("acme").resolve("templates")); + Files.writeString(layout.siteDir("acme").resolve("templates/home.html"), "ACME_HOME", StandardCharsets.UTF_8); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + UserStore users = new UserStore(yaml); + Path appUsers = external.resolve("app-users.yml"); + users.save(appUsers, new User("app-master", "admin", hash, "Admin", "", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + users.save(appUsers, new User("app-op", "op", hash, "Op", "", true, false, Realm.APPLICATION, + Set.of(Roles.SYSTEM_OPERATOR), List.of())); // reaches the app chain, but not a platform master + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.storage.backups", () -> external.resolve("backups").toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteStore sites; + @Autowired + private BackupService backups; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + } + + private MockHttpSession sessionFor(String username) throws Exception { + MvcResult r = mvc.perform(formLogin("/app/login").user(username).password(PW)).andReturn(); + return (MockHttpSession) r.getRequest().getSession(false); + } + + @Test + void theScreenRendersCreateAndPerSite() throws Exception { + mvc.perform(get("/__app/backups").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("action=\"/__app/backups/create-site\""))) + .andExpect(content().string(Matchers.containsString("acme"))) + // The off-site folder is the server's (settings-homes.yml): shown, never edited. + .andExpect(content().string(Matchers.containsString("Off-site copies: none."))); + } + + @Test + void downloadStreamsAZipOfAnySite() throws Exception { + mvc.perform(get("/__app/backups/acme/download").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", "application/zip")) + .andExpect(header().string("Content-Disposition", Matchers.containsString("attachment"))); + } + + @Test + void createSiteFromAnUploadedBackupClonesUnderANewId() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + backups.backup("acme", baos); + MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray()); + + mvc.perform(multipart("/__app/backups/create-site").file(file).session(sessionFor("admin")).with(csrf()) + .param("newId", "clone").param("name", "Clone").param("hosts", "clone.test")) + .andExpect(status().is3xxRedirection()); + + assertTrue(sites.exists("clone"), "the new site exists"); + assertEquals("clone", sites.find("clone").orElseThrow().id(), "site.yml rewritten to the new id"); + assertEquals("Clone", sites.find("clone").orElseThrow().name()); + assertTrue(sites.exists("acme"), "the source site is untouched"); + } + + /** An archive from a newer Runway: the operator is told to upgrade, and nothing is replaced or created. */ + @Test + void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception { + MockMultipartFile future = new MockMultipartFile("file", "future.zip", "application/zip", newerFormatArchive()); + MockHttpSession admin = sessionFor("admin"); + + mvc.perform(multipart("/__app/backups/acme/restore").file(future).session(admin).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("error", Matchers.containsString("newer version of Runway"))) + .andExpect(flash().attribute("error", Matchers.containsString("format 2"))); + assertEquals("ACME_HOME", Files.readString(acmeHome(), StandardCharsets.UTF_8), "the site was not replaced"); + + mvc.perform(multipart("/__app/backups/create-site").file(future).session(admin).with(csrf()) + .param("newId", "future").param("name", "Future")) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("error", Matchers.containsString("newer version of Runway"))); + assertFalse(sites.exists("future"), "no site was created"); + } + + @Test + void aBadOrClaimedHostIsReportedAsAHostProblem() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + backups.backup("acme", baos); + MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray()); + var admin = sessionFor("admin"); + mvc.perform(multipart("/__app/backups/create-site").file(file).session(admin).with(csrf()) + .param("newId", "copy1").param("hosts", "acme.test")) + .andExpect(flash().attribute("error", Matchers.startsWith("Those hosts cannot be used:"))); + mvc.perform(multipart("/__app/backups/create-site").file(file).session(admin).with(csrf()) + .param("newId", "copy2").param("hosts", "not a host!")) + .andExpect(flash().attribute("error", Matchers.containsString("is not a valid hostname"))); + assertFalse(sites.exists("copy1")); + assertFalse(sites.exists("copy2")); + } + + @Autowired + private StorageLayout layout; + + private Path acmeHome() { + return layout.siteDir("acme").resolve("templates/home.html"); + } + + /** A minimal archive whose manifest declares format 2 — what a later Runway might write. */ + static byte[] newerFormatArchive() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(out)) { + zip.putNextEntry(new ZipEntry("manifest.yml")); + zip.write("siteId: acme\nformatVersion: 2\n".getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + zip.putNextEntry(new ZipEntry("site/site.yml")); + zip.write("id: acme\nname: Acme\n".getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + zip.putNextEntry(new ZipEntry("site/templates/home.html")); + zip.write("FROM_THE_FUTURE".getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + return out.toByteArray(); + } + + @Test + void aNonMasterAppOperatorIsDeniedTheseCrossTenantActions() throws Exception { + mvc.perform(get("/__app/backups").session(sessionFor("op"))) + .andExpect(status().isForbidden()); + mvc.perform(get("/__app/backups/acme/download").session(sessionFor("op"))) + .andExpect(status().isForbidden()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AppBandwidthScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/AppBandwidthScreenTest.java new file mode 100644 index 0000000..e0b0889 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AppBandwidthScreenTest.java @@ -0,0 +1,77 @@ +package mx.quest.runway.console; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.bandwidth.BandwidthService; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.YamlStore; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** The app-realm Bandwidth aggregate: all-sites totals, gated by VIEW_BANDWIDTH. */ +@SpringBootTest +class AppBandwidthScreenTest { + + private static final String PW = "App-Bw-7"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-7b-app"); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + new UserStore(new YamlStore()).save(external.resolve("app-users.yml"), + new User("app-master", "admin", hash, "Admin", "", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private BandwidthService bandwidth; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + } + + private MockHttpSession sessionFor(String username) throws Exception { + MvcResult r = mvc.perform(formLogin("/app/login").user(username).password(PW)).andReturn(); + return (MockHttpSession) r.getRequest().getSession(false); + } + + @Test + void theAggregateRendersPerSiteTotals() throws Exception { + bandwidth.record("alpha", 0, 3_000_000); + bandwidth.record("beta", 0, 1_000_000); + mvc.perform(get("/__app/bandwidth").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("data-listing-table=\"runway.app.bandwidth\""))) + .andExpect(content().string(Matchers.containsString("alpha"))); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AppConsolePermissionsTest.java b/runway-app/src/test/java/mx/quest/runway/console/AppConsolePermissionsTest.java new file mode 100644 index 0000000..b7dbd79 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AppConsolePermissionsTest.java @@ -0,0 +1,177 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.authz.GrantFile; +import mx.quest.runway.authz.GrantStore; +import mx.quest.runway.authz.Role; +import mx.quest.runway.authz.RoleStore; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * {@code VIEW_APP_DASHBOARD} and {@code VIEW_TENANCIES} on the application console. The dashboard's content (counts + * and plugin cards) needs the first, but {@code /__app} never answers {@code 403} — it is where sign-in lands, so an + * operator without it gets a minimal landing. The Sites list needs the second (or {@code MANAGE_SITE_HOSTS}) and is + * read-only for a holder: no lifecycle affordance renders and every lifecycle POST stays platform-only. + */ +@SpringBootTest +class AppConsolePermissionsTest { + + private static final String PW = "App-Permissions-Secret-9"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-app-permissions"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + new SiteStore(layout, yaml).save(new Site("acme", "Acme Ltd", List.of("acme.test"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + UserStore users = new UserStore(yaml); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + Path app = external.resolve("app-users.yml"); + users.save(app, new User("app-master", "root", hash, "Root", "", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + users.save(app, appUser("sysadmin-id", "sysadmin", hash, Roles.SYSTEM_ADMIN)); + users.save(app, appUser("op-id", "op", hash, Roles.SYSTEM_OPERATOR)); + users.save(app, appUser("dash-id", "dash", hash, Roles.SYSTEM_OPERATOR)); + users.save(app, appUser("viewer-id", "viewer", hash, Roles.SYSTEM_OPERATOR)); + users.save(app, appUser("roleviewer-id", "roleviewer", hash, Roles.SYSTEM_OPERATOR)); + new GrantStore(layout, yaml).saveAppGrants(GrantFile.empty() + .withUserPermission("dash-id", "VIEW_APP_DASHBOARD") + .withUserPermission("viewer-id", "VIEW_TENANCIES") + // Through a custom ROLE this time: a role carrying the permission opens the list like a direct grant. + .withUserRole("roleviewer-id", "TENANCY_VIEWERS")); + new RoleStore(layout, yaml).saveAppRoles(List.of(new Role("TENANCY_VIEWERS", Realm.APPLICATION, + Set.of("VIEW_TENANCIES"), Set.of()))); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + private static User appUser(String id, String username, String hash, String tier) { + return new User(id, username, hash, username, "", true, false, Realm.APPLICATION, Set.of(tier), List.of()); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteStore siteStore; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + } + + private MockHttpSession login(String username) throws Exception { + MvcResult result = mvc.perform(formLogin("/app/login").user(username).password(PW)) + .andExpect(redirectedUrl("/__app")).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private String okPage(String path, MockHttpSession session) throws Exception { + return mvc.perform(get(path).session(session)).andExpect(status().isOk()).andReturn().getResponse() + .getContentAsString(); + } + + // --- VIEW_APP_DASHBOARD ----------------------------------------------------------------------------- + + @Test + void anOperatorWithoutViewAppDashboardLandsOnAMinimalPageNotA403() throws Exception { + String html = okPage("/__app", login("op")); + assertTrue(html.contains("id=\"home-minimal\""), "the minimal landing renders"); + assertFalse(html.contains("id=\"home-dashboard\"") || html.contains("id=\"home-count-sites\""), + "no dashboard counts without VIEW_APP_DASHBOARD"); + } + + @Test + void anOperatorGrantedViewAppDashboardSeesTheDashboard() throws Exception { + String html = okPage("/__app", login("dash")); + assertTrue(html.contains("id=\"home-count-sites\""), "the counts render"); + assertFalse(html.contains("id=\"home-minimal\""), "and the minimal landing does not"); + assertFalse(html.contains("href=\"/__app/sites\" class=\"card"), + "the Sites tile does not link to a list this operator may not open"); + } + + @Test + void theSuperadminAndSystemAdminSeeTheDashboardWithItsLinks() throws Exception { + for (String username : List.of("root", "sysadmin")) { + String html = okPage("/__app", login(username)); + assertTrue(html.contains("id=\"home-count-sites\""), username + " sees the counts"); + assertTrue(html.contains("href=\"/__app/sites\" class=\"card card-link\" id=\"home-link-sites\""), + username + ": the Sites tile links to the list"); + } + } + + // --- VIEW_TENANCIES --------------------------------------------------------------------------------- + + @Test + void anOperatorWithoutViewTenanciesCannotOpenTheSitesList() throws Exception { + mvc.perform(get("/__app/sites").session(login("op"))).andExpect(status().isForbidden()); + mvc.perform(get("/__app/sites").session(login("dash"))).andExpect(status().isForbidden()); + } + + @Test + void viewTenanciesOpensAReadOnlyList() throws Exception { + for (String username : List.of("viewer", "roleviewer")) { + MockHttpSession session = login(username); + String html = okPage("/__app/sites", session); + assertTrue(html.contains("Acme Ltd"), username + " sees the sites"); + assertFalse(html.contains("/__app/sites/create") || html.contains("/__app/sites/install-demo") + || html.contains("/__app/sites/acme/suspend") || html.contains("/__app/sites/acme/delete") + || html.contains("/__app/sites/acme/edit") || html.contains("/__app/sites/acme/hosts"), + username + ": no create, demo, lifecycle, edit or host affordance"); + mvc.perform(post("/__app/sites/acme/suspend").session(session).with(csrf())) + .andExpect(status().isForbidden()); + mvc.perform(post("/__app/sites/acme/hosts").session(session).with(csrf()).param("hosts", "x.test")) + .andExpect(status().isForbidden()); + } + assertTrue(siteStore.find("acme").orElseThrow().active(), "nothing changed"); + } + + @Test + void theSuperadminAndSystemAdminStillManageSites() throws Exception { + for (String username : List.of("root", "sysadmin")) { + String html = okPage("/__app/sites", login(username)); + assertTrue(html.contains("/__app/sites/create") && html.contains("/__app/sites/acme/suspend"), + username + " keeps the lifecycle affordances"); + } + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AppLogLevelsTest.java b/runway-app/src/test/java/mx/quest/runway/console/AppLogLevelsTest.java new file mode 100644 index 0000000..2d8a23b --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AppLogLevelsTest.java @@ -0,0 +1,175 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import mx.quest.runway.log.AppActivityLog; +import mx.quest.runway.platform.PlatformSettingsStore; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.YamlStore; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.logging.LogLevel; +import org.springframework.boot.logging.LoggingSystem; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * Log levels from the console: applied at once, kept in platform.yml and applied again at startup; Default restores + * the configured level; the server's own logging.level wins and shows locked; platform administrators only; every + * change is recorded in the activity log. + */ +@SpringBootTest +class AppLogLevelsTest { + + private static final String PW = "Log-Levels-Secret-9"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-loglevels"); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + UserStore users = new UserStore(new YamlStore()); + users.save(external.resolve("app-users.yml"), new User("app-master", "admin", hash, "Admin", "", true, true, + Realm.APPLICATION, Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + users.save(external.resolve("app-users.yml"), new User("app-op", "operator", hash, "Op", "", true, false, + Realm.APPLICATION, Set.of(Roles.SYSTEM_OPERATOR), List.of())); + // A level stored by the console before this start: applied when the server is ready. + Files.writeString(external.resolve("platform.yml"), "logLevels:\n mx.quest.runway.page: TRACE\n"); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + // The server sets this one itself: the console must leave it alone. + registry.add("logging.level.mx.quest.runway.cluster", () -> "WARN"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private LoggingSystem logging; + @Autowired + private PlatformSettingsStore platform; + @Autowired + private AppActivityLog activity; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + } + + private MockHttpSession login(String user) throws Exception { + MvcResult result = mvc.perform(formLogin("/app/login").user(user).password(PW)).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + /** The logger's effective level, or null when the logging system has no configuration for it. */ + private LogLevel effective(String name) { + var config = logging.getLoggerConfiguration(name); + return config == null ? null : config.getEffectiveLevel(); + } + + @Test + void aStoredLevelIsAppliedAtStartup() { + assertEquals(LogLevel.TRACE, effective("mx.quest.runway.page")); + } + + @Test + void aLevelAppliesAtOnceIsKeptAndDefaultRestoresIt() throws Exception { + MockHttpSession admin = login("admin"); + LogLevel before = effective("mx.quest.runway.backup"); + mvc.perform(post("/__app/logs/levels").session(admin).with(csrf()) + .param("logger", "mx.quest.runway.backup").param("level", "debug")) + .andExpect(flash().attribute("flash", "Log level of mx.quest.runway.backup set to DEBUG.")); + assertEquals(LogLevel.DEBUG, effective("mx.quest.runway.backup")); + assertEquals("DEBUG", platform.get().logLevels().get("mx.quest.runway.backup")); + assertTrue(activity.tail(10).stream().anyMatch(l -> l.contains("platform.log-level-changed"))); + + String page = mvc.perform(get("/__app/logs/levels").session(admin)).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + assertTrue(page.contains("value=\"DEBUG\" selected=\"selected\""), "the stored level is preselected"); + + mvc.perform(post("/__app/logs/levels").session(admin).with(csrf()) + .param("logger", "mx.quest.runway.backup").param("level", "")) + .andExpect(flash().attributeExists("flash")); + assertEquals(before, effective("mx.quest.runway.backup"), "Default restores the configured level"); + assertFalse(platform.get().logLevels().containsKey("mx.quest.runway.backup")); + } + + @Test + void rootBackToDefaultRestoresInfoInsteadOfFailing() throws Exception { + MockHttpSession admin = login("admin"); + LogLevel before = effective(LoggingSystem.ROOT_LOGGER_NAME); + try { + mvc.perform(post("/__app/logs/levels").session(admin).with(csrf()) + .param("logger", "ROOT").param("level", "WARN")) + .andExpect(flash().attribute("flash", "Log level of ROOT set to WARN.")); + assertEquals(LogLevel.WARN, effective(LoggingSystem.ROOT_LOGGER_NAME)); + assertEquals("WARN", platform.get().logLevels().get("ROOT")); + + mvc.perform(post("/__app/logs/levels").session(admin).with(csrf()) + .param("logger", "ROOT").param("level", "")) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("flash", "Log level of ROOT set to default.")); + assertEquals(LogLevel.INFO, effective(LoggingSystem.ROOT_LOGGER_NAME), + "with no logging.level.root configured, Default is Spring Boot's INFO"); + assertFalse(platform.get().logLevels().containsKey("ROOT")); + } finally { + logging.setLogLevel(LoggingSystem.ROOT_LOGGER_NAME, before); + } + } + + @Test + void badNamesLevelsAndServerSetLoggersAreRefused() throws Exception { + MockHttpSession admin = login("admin"); + mvc.perform(post("/__app/logs/levels").session(admin).with(csrf()) + .param("logger", "../etc").param("level", "DEBUG")) + .andExpect(flash().attributeExists("error")); + mvc.perform(post("/__app/logs/levels").session(admin).with(csrf()) + .param("logger", "mx.quest").param("level", "LOUD")) + .andExpect(flash().attribute("error", "That is not a log level.")); + mvc.perform(post("/__app/logs/levels").session(admin).with(csrf()) + .param("logger", "mx.quest.runway.cluster").param("level", "TRACE")) + .andExpect(flash().attribute("error", + "That logger's level is set on the server, which wins over this page.")); + // (A test property is not applied by Spring's logging setup, so only "not changed by the console" is checked.) + assertFalse(effective("mx.quest.runway.cluster") == LogLevel.TRACE, "the console did not change it"); + assertFalse(platform.get().logLevels().containsKey("mx.quest.runway.cluster")); + String page = mvc.perform(get("/__app/logs/levels").session(admin)).andReturn().getResponse() + .getContentAsString(); + assertTrue(page.contains("Set on the server in"), "the locked logger says where it is set"); + } + + @Test + void onlyPlatformAdministratorsMayChangeLevels() throws Exception { + MockHttpSession op = login("operator"); + mvc.perform(get("/__app/logs/levels").session(op)).andExpect(status().isForbidden()); + mvc.perform(post("/__app/logs/levels").session(op).with(csrf()) + .param("logger", "ROOT").param("level", "TRACE")) + .andExpect(status().isForbidden()); + assertFalse(platform.get().logLevels().containsKey("ROOT")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/AppLogsScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/AppLogsScreenTest.java new file mode 100644 index 0000000..f7feae7 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/AppLogsScreenTest.java @@ -0,0 +1,270 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.LocalDate; +import java.util.List; +import java.util.Set; +import mx.quest.runway.log.AppActivityLog; +import mx.quest.runway.log.AuditQuery; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.YamlStore; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * The app-realm Activity → Logs screen ({@code /__app/logs}) and its CSV export: parsed, filtered, paged rows with + * localized labels; gated by {@code VIEW_AUDIT} (master and wildcard admin pass, an ordinary operator only once + * granted it); logged values escaped; and the newly journaled events (logout, permission changes) land in it. + * Also a smoke test that the whole application context still wires with the journal threaded through every app + * mutation controller. + */ +@SpringBootTest +class AppLogsScreenTest { + + private static final String PASSWORD = "App-Logs-Secret-9"; + private static Path external; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + external = Files.createTempDirectory("runway-applogs"); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PASSWORD); + UserStore users = new UserStore(new YamlStore()); + Path file = external.resolve("app-users.yml"); + users.save(file, new User("app-master", "admin", hash, "Admin", "a@x", true, true, Realm.APPLICATION, + Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + users.save(file, new User("op-user", "operator", hash, "Operator", "o@x", true, false, Realm.APPLICATION, + Set.of(Roles.SYSTEM_OPERATOR), List.of())); + users.save(file, new User("adm-user", "wildcard", hash, "Wildcard", "w@x", true, false, Realm.APPLICATION, + Set.of(Roles.SYSTEM_ADMIN), List.of())); + users.save(file, new User("aud-user", "auditor", hash, "Auditor", "u@x", true, false, Realm.APPLICATION, + Set.of(Roles.SYSTEM_OPERATOR), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private AppActivityLog activity; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); + } + + private MockHttpSession sessionFor(String username) throws Exception { + MvcResult result = mvc.perform(formLogin("/app/login").user(username).password(PASSWORD)).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private String page(String url, String username) throws Exception { + return mvc.perform(get(url).session(sessionFor(username))).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + } + + private static void appendDay(LocalDate day, String text) throws IOException { + Path dir = Files.createDirectories(external.resolve("activity")); + Files.writeString(dir.resolve("activity-" + day + ".log"), text, StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.APPEND); + } + + // --- rendering --------------------------------------------------------------------------------- + + @Test + void theScreenShowsParsedRowsWithLocalizedLabelsInAListingTable() throws Exception { + activity.record("admin", "site.created", "acme-demo-site"); + String html = page("/__app/logs", "admin"); + assertTrue(html.contains("data-listing-table=\"runway.app.audit\""), "a listing table"); + assertTrue(html.contains("Site created"), "the action is labelled"); + assertTrue(html.contains(">site.created<"), "the raw key is shown too (it is what the filter matches)"); + assertTrue(html.contains("acme-demo-site")); + assertTrue(html.contains("href=\"/__app/logs/export.csv\""), "the CSV link carries the (empty) filter"); + } + + @Test + void anUnknownActionIsShownAsItsRawKeyAndALegacyLineStillRenders() throws Exception { + appendDay(LocalDate.now().minusDays(1), LocalDate.now().minusDays(1) + + " 09:15:00\tlegacy-actor\tplugin-x.did-something\tbefore the upgrade\n"); + String html = page("/__app/logs?actor=legacy-actor", "admin"); + assertTrue(html.contains("plugin-x.did-something")); + assertTrue(html.contains(LocalDate.now().minusDays(1) + " 09:15:00<"), "an offset-less time shows as written"); + } + + @Test + void aLoggedValueIsEscapedNeverInterpretedAsMarkup() throws Exception { + activity.record("admin", "site.created", ""); + String html = page("/__app/logs?action=site.created", "admin"); + assertFalse(html.contains("".getBytes()); + mvc.perform(multipart("/__admin/documents/upload").file(file).session(admin).with(csrf())) + .andExpect(status().is3xxRedirection()); + assertTrue(documents.list("acme").stream().anyMatch(d -> d.path().equals("report.html"))); + + // Publicly served as a nosniff attachment (never inline text/html on the site origin). + mvc.perform(get("/static/doc/report.html")) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", Matchers.containsString("application/octet-stream"))) + .andExpect(header().string("X-Content-Type-Options", "nosniff")) + .andExpect(header().string("Content-Disposition", Matchers.containsString("attachment"))); + + // Disable → the same public URL now 404s, but the file is not deleted. + mvc.perform(post("/__admin/documents/toggle").session(admin).with(csrf()) + .param("path", "report.html").param("disable", "true")) + .andExpect(status().is3xxRedirection()); + mvc.perform(get("/static/doc/report.html")).andExpect(status().isNotFound()); + assertTrue(documents.list("acme").stream().filter(d -> d.path().equals("report.html")).findFirst() + .orElseThrow().disabled(), "still present, just withheld"); + } + + @Test + void deleteRemovesTheDocument() throws Exception { + MockHttpSession admin = sessionFor("admin"); + documents.add("acme", "gone.txt", "bye".getBytes()); + mvc.perform(post("/__admin/documents/delete").session(admin).with(csrf()).param("path", "gone.txt")) + .andExpect(status().is3xxRedirection()); + assertFalse(documents.list("acme").stream().anyMatch(d -> d.path().equals("gone.txt"))); + } + + @Test + void aSpacedFilenameIsSanitizedToAUrlSafeNameThatServes() throws Exception { + documents.add("acme", "my report.pdf", "PDF".getBytes()); // stored as my_report.pdf + assertTrue(documents.list("acme").stream().anyMatch(d -> d.path().equals("my_report.pdf"))); + mvc.perform(get("/static/doc/my_report.pdf")) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Disposition", Matchers.containsString("attachment"))); + } + + @Test + void anOperatorWithoutManageDocumentsCannotSeeTheScreen() throws Exception { + mvc.perform(get("/__admin/documents").session(sessionFor("op"))) + .andExpect(status().isForbidden()); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/EditorialWorkflowScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/EditorialWorkflowScreenTest.java new file mode 100644 index 0000000..71fcdc0 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/EditorialWorkflowScreenTest.java @@ -0,0 +1,505 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import mx.quest.runway.authz.GrantFile; +import mx.quest.runway.authz.GrantStore; +import mx.quest.runway.log.SiteLogService; +import mx.quest.runway.page.PageReview; +import mx.quest.runway.page.PageStore; +import mx.quest.runway.page.PageWriteService; +import mx.quest.runway.page.PendingRevisionStore; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.EditorialLevel; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteContextFilter; +import mx.quest.runway.site.SiteLifecycleService; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * The editorial workflow end to end through the tenant console and the public site, with real rendering + * and the real quality checks: a reviewed site's pending revision leaves the live page (body, ETag, routing) + * untouched until approved; approval, send-back, submit and withdraw; the enforced gate refusing a publish and a + * live save; the Site config level switch and who may change it; every new route's permission (403); and that a + * site's queue can never show or act on another site's pages. + * + *

Users on {@code acme}: {@code admin} (wildcard), {@code editor} (EDIT_PAGES + DISABLE_PAGES, no approval), + * {@code approver} (EDIT_PAGES + APPROVE_PAGES), {@code reviewer} (APPROVE_PAGES only), {@code configurer} + * (CONFIGURE_SITE only) and {@code op} (nothing). Each test sets the level it needs and uses its own pages. + */ +@SpringBootTest +class EditorialWorkflowScreenTest { + + private static final String PW = "Editorial-Flow-7"; + private static Path templates; + private static Path betaTemplates; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-editorial"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + SiteStore sites = new SiteStore(layout, yaml); + sites.save(new Site("acme", "Acme", List.of("localhost"), Locale.ENGLISH, List.of(Locale.ENGLISH), null, + SiteStatus.ACTIVE)); + sites.save(new Site("beta", "Beta", List.of("beta.test"), Locale.ENGLISH, List.of(Locale.ENGLISH), null, + SiteStatus.ACTIVE, false, null, EditorialLevel.REVIEWED)); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + UserStore users = new UserStore(yaml); + Path siteUsers = layout.siteDir("acme").resolve("users.yml"); + users.save(siteUsers, new User("acme-admin", "admin", hash, "Admin", "", true, false, Realm.TENANT, + Set.of(Roles.ADMIN), List.of())); + for (String name : List.of("editor", "approver", "reviewer", "configurer", "op")) { + users.save(siteUsers, new User("acme-" + name, name, hash, name, "", true, false, Realm.TENANT, + Set.of(Roles.OPERATOR), List.of())); + } + new GrantStore(layout, yaml).saveSiteGrants("acme", GrantFile.empty() + .withUserPermission("acme-editor", "EDIT_PAGES") + .withUserPermission("acme-editor", "DISABLE_PAGES") + .withUserPermission("acme-approver", "EDIT_PAGES") + .withUserPermission("acme-approver", "APPROVE_PAGES") + .withUserPermission("acme-reviewer", "APPROVE_PAGES") + .withUserPermission("acme-configurer", "CONFIGURE_SITE")); + users.save(external.resolve("app-users.yml"), new User("app-master", "root", hash, "Root", "", true, + true, Realm.APPLICATION, Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + + templates = layout.siteDir("acme").resolve("templates"); + Files.createDirectories(templates); + for (String slug : List.of("rev1", "rev2", "rev3", "rev4", "rev5", "enf2", "enf3")) { + page(templates, slug, false, "Title " + slug, "LIVE_" + slug, ""); + } + page(templates, "draft1", true, "Title draft1", "DRAFT_draft1", ""); + // Re-seed: a master with fresh chrome, and bare published pages carrying a stale copy of it — a + // page without .th.xml seams serves its own .html, so a re-seed changes what visitors see. + Files.writeString(templates.resolve("_master.html"), "m" + + "

FRESH_HEADER
", + StandardCharsets.UTF_8); + for (String slug : List.of("rs1", "rs2", "rs3")) { + page(templates, slug, false, "Title " + slug, "LIVE_" + slug, slug.equals("rs3") ? "" : ""); + Files.writeString(templates.resolve(slug + ".html"), Files.readString(templates.resolve(slug + ".html")) + .replace("", "
STALE_HEADER
"), + StandardCharsets.UTF_8); + } + page(templates, "enf1", true, "Title enf1", "DRAFT_enf1", ""); + + betaTemplates = layout.siteDir("beta").resolve("templates"); + Files.createDirectories(betaTemplates); + page(betaTemplates, "secret-beta", true, "Beta secret", "BETA_ONLY", ""); + Files.createDirectories(betaTemplates.resolve(".pending/secret-beta")); + yaml.write(betaTemplates.resolve(".pending/secret-beta/review.yml"), + PageReview.submitted("beta-ed", Instant.parse("2026-10-01T00:00:00Z"))); + + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + /** A bare page (no master, no logic) whose rendered markup passes every ERROR check unless {@code extra} adds one. */ + private static void page(Path dir, String slug, boolean draft, String title, String marker, String extra) + throws IOException { + Files.writeString(dir.resolve(slug + ".html"), html(marker, extra), StandardCharsets.UTF_8); + Files.writeString(dir.resolve(slug + ".meta.yml"), + "path: /" + slug + "\ndraft: " + draft + "\ntitle:\n en: " + title + "\n", StandardCharsets.UTF_8); + } + + private static String html(String marker, String extra) { + return "t

Heading

" + marker + + "

" + extra + "
"; + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteResolver siteResolver; + @Autowired + private SiteLifecycleService lifecycle; + @Autowired + private SiteStore siteStore; + @Autowired + private PageStore pages; + @Autowired + private PageWriteService writer; + @MockitoSpyBean + private SiteLogService siteLog; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context) + .addFilters(new SiteContextFilter(siteResolver)) + .apply(springSecurity()).build(); + lifecycle.updateEditorial("acme", EditorialLevel.REVIEWED); + } + + private MockHttpSession login(String username) throws Exception { + MvcResult result = mvc.perform(formLogin("/login").user(username).password(PW)).andReturn(); + return (MockHttpSession) result.getRequest().getSession(false); + } + + private org.springframework.test.web.servlet.ResultActions save(MockHttpSession session, String slug, + String title, String marker, String extra) + throws Exception { + return mvc.perform(post("/__admin/pages/" + slug).session(session).with(csrf()) + .param("html", html(marker, extra)).param("path", "/" + slug) + .param("template", "_master").param("title[en]", title)); + } + + private String body(String slug) { + return writer.readBody("acme", slug).orElseThrow(); + } + + private String fingerprintOn(MockHttpSession session, String slug) throws Exception { + String page = mvc.perform(get("/__admin/review/" + slug).session(session)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + Matcher m = Pattern.compile("id=\"ri-fingerprint\"[^>]*value=\"([0-9a-f]{64})\"").matcher(page); + assertTrue(m.find(), "the review screen carries the fingerprint"); + return m.group(1); + } + + // --- reviewed: a live edit waits as a pending revision --------------------------------------------- + + @Test + void aReviewedLiveEditIsInvisibleUntilApprovedThenReplacesTheLivePage() throws Exception { + MvcResult before = mvc.perform(get("/rev1")).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("LIVE_rev1"))).andReturn(); + String etag = before.getResponse().getHeader("ETag"); + assertNotNull(etag, "the live page carries an ETag"); + + MockHttpSession editor = login("editor"); + save(editor, "rev1", "Title rev1 v2", "PROPOSED_rev1", "") + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("flash", Matchers.containsString("pending revision"))); + + // The live page is exactly as it was: body on disk, public render, ETag. + assertTrue(body("rev1").contains("LIVE_rev1")); + MvcResult after = mvc.perform(get("/rev1")).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("LIVE_rev1"))) + .andExpect(content().string(Matchers.not(Matchers.containsString("PROPOSED_rev1")))).andReturn(); + assertEquals(etag, after.getResponse().getHeader("ETag"), "the live ETag did not move"); + + // The editor reopens the page and sees their revision, with the banner; the list shows the status. + mvc.perform(get("/__admin/pages/rev1/edit").session(editor)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("PROPOSED_rev1"))) + .andExpect(content().string(Matchers.containsString("You are editing a pending revision"))) + .andExpect(content().string(Matchers.containsString("/__admin/pages/rev1/preview?revision=1"))); + mvc.perform(get("/__admin/pages").session(editor)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("data-status=\"published-pending\""))); + + // The reviewer sees it in the queue and on its screen (diff + both previews), then approves. + MockHttpSession reviewer = login("reviewer"); + mvc.perform(get("/__admin/review").session(reviewer)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("href=\"/__admin/review/rev1\""))); + mvc.perform(get("/__admin/review/rev1").session(reviewer)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("PROPOSED_rev1"))) // the diff's + line + .andExpect(content().string(Matchers.containsString("rw-d-added"))) + .andExpect(content().string(Matchers.containsString("Title rev1 v2"))) // the metadata change + .andExpect(content().string(Matchers.containsString("src=\"/__admin/pages/rev1/preview\""))); + mvc.perform(get("/__admin/pages/rev1/preview").param("revision", "1").session(reviewer)) + .andExpect(status().isOk()).andExpect(content().string(Matchers.containsString("PROPOSED_rev1"))); + mvc.perform(post("/__admin/review/rev1/approve").session(reviewer).with(csrf()) + .param("fingerprint", fingerprintOn(reviewer, "rev1"))) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attributeExists("flash")); + + assertTrue(body("rev1").contains("PROPOSED_rev1")); + assertEquals("Title rev1 v2", pages.find("acme", "rev1").orElseThrow().title().get("en")); + assertFalse(writer.pending().exists("acme", "rev1")); + mvc.perform(get("/rev1")).andExpect(content().string(Matchers.containsString("PROPOSED_rev1"))); + verify(siteLog).audit(eq("acme"), eq("editor"), eq("page.revision.submitted"), eq("rev1")); + verify(siteLog).audit(eq("acme"), eq("reviewer"), eq("page.review.approved"), eq("rev1")); + } + + @Test + void anApprovalOfContentThatChangedAfterItWasOpenedIsRefused() throws Exception { + MockHttpSession editor = login("editor"); + save(editor, "rev2", "Title rev2", "FIRST_rev2", "").andExpect(status().is3xxRedirection()); + MockHttpSession reviewer = login("reviewer"); + String seen = fingerprintOn(reviewer, "rev2"); + save(editor, "rev2", "Title rev2", "SECOND_rev2", "").andExpect(status().is3xxRedirection()); + + mvc.perform(post("/__admin/review/rev2/approve").session(reviewer).with(csrf()).param("fingerprint", seen)) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("error", Matchers.containsString("changed"))); + assertTrue(body("rev2").contains("LIVE_rev2"), "nothing was published"); + } + + @Test + void sendingBackNeedsANoteAndReturnsTheRevisionToItsEditor() throws Exception { + MockHttpSession editor = login("editor"); + save(editor, "rev3", "Title rev3", "PROPOSED_rev3", "").andExpect(status().is3xxRedirection()); + MockHttpSession reviewer = login("reviewer"); + + mvc.perform(post("/__admin/review/rev3/return").session(reviewer).with(csrf()).param("note", " ")) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("error", Matchers.containsString("note"))); + assertTrue(writer.pending().review("acme", "rev3").orElseThrow().isSubmitted()); + + mvc.perform(post("/__admin/review/rev3/return").session(reviewer).with(csrf()) + .param("note", "Please cite the source.")) + .andExpect(status().is3xxRedirection()); + assertTrue(writer.pending().review("acme", "rev3").orElseThrow().isReturned()); + assertTrue(body("rev3").contains("LIVE_rev3")); + mvc.perform(get("/__admin/pages/rev3/edit").session(editor)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("Please <b>cite</b> the source."))) + .andExpect(content().string(Matchers.containsString("PROPOSED_rev3"))); + mvc.perform(get("/__admin/pages").session(editor)) + .andExpect(content().string(Matchers.containsString("data-status=\"published-returned\""))); + mvc.perform(get("/__admin/review").session(reviewer)) + .andExpect(content().string(Matchers.not(Matchers.containsString("/__admin/review/rev3")))); + + // Discarding the revision restores the plain published state. + mvc.perform(post("/__admin/pages/rev3/withdraw").session(editor).with(csrf())) + .andExpect(status().is3xxRedirection()); + assertFalse(writer.pending().exists("acme", "rev3")); + } + + @Test + void onAReviewedSiteAnEditorSubmitsADraftAndOnlyAnApproverPublishesIt() throws Exception { + MockHttpSession editor = login("editor"); + // DISABLE_PAGES alone no longer publishes, and the list offers no Enable for the draft. + mvc.perform(post("/__admin/pages/draft1/enable").session(editor).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("error", Matchers.containsString("requires review"))); + assertTrue(pages.find("acme", "draft1").orElseThrow().draft()); + mvc.perform(get("/__admin/pages").session(editor)) + .andExpect(content().string(Matchers.not(Matchers.containsString("/__admin/pages/draft1/enable")))) + .andExpect(content().string(Matchers.containsString("/__admin/pages/rev5/disable"))); + mvc.perform(get("/__admin/pages/draft1/edit").session(editor)) + .andExpect(content().string(Matchers.containsString("/__admin/pages/draft1/submit"))) + .andExpect(content().string(Matchers.not(Matchers.containsString("/__admin/pages/draft1/enable")))); + + mvc.perform(post("/__admin/pages/draft1/submit").session(editor).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attributeExists("flash")); + mvc.perform(get("/__admin/pages").session(editor)) + .andExpect(content().string(Matchers.containsString("data-status=\"in-review\""))); + + MockHttpSession reviewer = login("reviewer"); + mvc.perform(get("/__admin/review/draft1").session(reviewer)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("First publication"))); + mvc.perform(post("/__admin/review/draft1/approve").session(reviewer).with(csrf()) + .param("fingerprint", fingerprintOn(reviewer, "draft1"))) + .andExpect(status().is3xxRedirection()); + assertTrue(pages.find("acme", "draft1").orElseThrow().published()); + mvc.perform(get("/draft1")).andExpect(status().isOk()); + } + + @Test + void anApproverPublishesTheirOwnEditDirectly() throws Exception { + MockHttpSession approver = login("approver"); + mvc.perform(get("/__admin/pages/rev4/edit").session(approver)) + .andExpect(content().string(Matchers.not(Matchers.containsString("Save as pending revision")))); + save(approver, "rev4", "Title rev4", "DIRECT_rev4", "").andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("flash", Matchers.not(Matchers.containsString("pending")))); + assertTrue(body("rev4").contains("DIRECT_rev4")); + assertFalse(writer.pending().exists("acme", "rev4")); + } + + // --- enforced ----------------------------------------------------------------------------------------- + + @Test + void enforcedRefusesToPublishAPageWithErrors() throws Exception { + lifecycle.updateEditorial("acme", EditorialLevel.ENFORCED); + MockHttpSession editor = login("editor"); + mvc.perform(post("/__admin/pages/enf1/enable").session(editor).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("error", Matchers.containsString("no alt attribute"))); + assertTrue(pages.find("acme", "enf1").orElseThrow().draft()); + verify(siteLog).audit(eq("acme"), eq("editor"), eq("page.quality.blocked"), eq("enf1 publish: img.alt-missing")); + // On an enforced (not reviewed) site DISABLE_PAGES still publishes a clean page. + save(editor, "enf1", "Title enf1", "FIXED_enf1", "\"\"") + .andExpect(status().is3xxRedirection()); + mvc.perform(post("/__admin/pages/enf1/enable").session(editor).with(csrf())) + .andExpect(status().is3xxRedirection()).andExpect(flash().attributeCount(0)); + assertTrue(pages.find("acme", "enf1").orElseThrow().published()); + } + + @Test + void enforcedRefusesALiveSaveWithErrorsAndKeepsTheAuthorsWork() throws Exception { + lifecycle.updateEditorial("acme", EditorialLevel.ENFORCED); + MockHttpSession editor = login("editor"); + // No title: an ERROR. The editor is re-shown (200, not a redirect) with the typed content. + save(editor, "enf2", "", "TYPED_enf2", "") + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("TYPED_enf2"))) + .andExpect(content().string(Matchers.containsString("id=\"pe-ed-blocked\""))) + .andExpect(content().string(Matchers.containsString("The page has no title"))); + assertTrue(body("enf2").contains("LIVE_enf2"), "nothing was written"); + // Warnings never block: no description, a generic link — saved. + save(editor, "enf3", "Title enf3 new", "OK_enf3", "click here") + .andExpect(status().is3xxRedirection()); + assertTrue(body("enf3").contains("OK_enf3")); + } + + // --- site config -------------------------------------------------------------------------------------- + + @Test + void theLevelIsChosenInSiteConfigAndOnlyAnApproverMayChangeIt() throws Exception { + lifecycle.updateEditorial("acme", EditorialLevel.ADVISORY); + MockHttpSession admin = login("admin"); + mvc.perform(get("/__admin/config").session(admin)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("value=\"reviewed\""))); + mvc.perform(post("/__admin/config").session(admin).with(csrf()).param("name", "Acme") + .param("defaultLocale", "en").param("locale", "en").param("editorial", "bogus")) + .andExpect(flash().attribute("error", Matchers.containsString("editorial level"))); + assertEquals(EditorialLevel.ADVISORY, siteStore.find("acme").orElseThrow().editorial()); + mvc.perform(post("/__admin/config").session(admin).with(csrf()).param("name", "Acme") + .param("defaultLocale", "en").param("locale", "en").param("editorial", "reviewed")) + .andExpect(status().is3xxRedirection()); + assertEquals(EditorialLevel.REVIEWED, siteStore.find("acme").orElseThrow().editorial()); + verify(siteLog).audit(eq("acme"), eq("admin"), eq("site-config.changed"), eq("editorial=reviewed")); + + MockHttpSession configurer = login("configurer"); + mvc.perform(get("/__admin/config").session(configurer)).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("Only a user who may approve pages"))) + .andExpect(content().string(Matchers.matchesPattern("(?s).*id=\"cfg-ed-advisory\"[^>]*disabled.*"))); + mvc.perform(post("/__admin/config").session(configurer).with(csrf()).param("name", "Acme") + .param("defaultLocale", "en").param("locale", "en").param("editorial", "advisory")) + .andExpect(flash().attribute("error", Matchers.containsString("Approve pages"))); + assertEquals(EditorialLevel.REVIEWED, siteStore.find("acme").orElseThrow().editorial(), + "a configurer cannot switch review off"); + mvc.perform(post("/__admin/config").session(configurer).with(csrf()).param("name", "Acme") + .param("defaultLocale", "en").param("locale", "en")) + .andExpect(status().is3xxRedirection()).andExpect(flash().attributeExists("flash")); + assertEquals(EditorialLevel.REVIEWED, siteStore.find("acme").orElseThrow().editorial(), + "a form without the field keeps the level"); + } + + // --- authorization + isolation ------------------------------------------------------------------------ + + @Test + void everyNewRouteIsGated() throws Exception { + MockHttpSession op = login("op"); + MockHttpSession editor = login("editor"); + MockHttpSession reviewer = login("reviewer"); + for (MockHttpSession noApprove : List.of(op, editor)) { + mvc.perform(get("/__admin/review").session(noApprove)).andExpect(status().isForbidden()); + mvc.perform(get("/__admin/review/rev5").session(noApprove)).andExpect(status().isForbidden()); + mvc.perform(post("/__admin/review/rev5/approve").session(noApprove).with(csrf()).param("fingerprint", "x")) + .andExpect(status().isForbidden()); + mvc.perform(post("/__admin/review/rev5/return").session(noApprove).with(csrf()).param("note", "n")) + .andExpect(status().isForbidden()); + } + for (MockHttpSession noEdit : List.of(op, reviewer)) { + mvc.perform(post("/__admin/pages/rev5/submit").session(noEdit).with(csrf())) + .andExpect(status().isForbidden()); + mvc.perform(post("/__admin/pages/rev5/withdraw").session(noEdit).with(csrf())) + .andExpect(status().isForbidden()); + } + // The preview admits an approver without EDIT_PAGES, and nobody without either. + mvc.perform(get("/__admin/pages/rev5/preview").session(reviewer)).andExpect(status().isOk()); + mvc.perform(get("/__admin/pages/rev5/preview-window").param("revision", "1").session(reviewer)) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("/__admin/pages/rev5/preview?revision=1"))); + mvc.perform(get("/__admin/pages/rev5/preview").session(op)).andExpect(status().isForbidden()); + mvc.perform(get("/__admin/review")).andExpect(status().is3xxRedirection()); // anonymous → login + } + + @Test + void aSitesQueueNeverShowsOrActsOnAnotherSitesPages() throws Exception { + MockHttpSession reviewer = login("reviewer"); + mvc.perform(get("/__admin/review").param("site", "beta").param("siteId", "beta").session(reviewer)) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.not(Matchers.containsString("secret-beta")))); + mvc.perform(get("/__admin/review/secret-beta").session(reviewer)) + .andExpect(status().is3xxRedirection()); + mvc.perform(post("/__admin/review/secret-beta/approve").session(reviewer).with(csrf()) + .param("fingerprint", "x")) + .andExpect(status().is3xxRedirection()); + mvc.perform(post("/__admin/review/secret-beta/return").session(reviewer).with(csrf()).param("note", "n")) + .andExpect(status().is3xxRedirection()); + assertTrue(pages.find("beta", "secret-beta").orElseThrow().draft(), "beta's page was not published"); + assertTrue(writer.pending().review("beta", "secret-beta").orElseThrow().isSubmitted(), + "beta's review was not touched"); + } + + // --- re-seed follows the editorial level -------------------------- + + /** + * The reproduction: on a reviewed site an editor without APPROVE_PAGES re-seeded a published page + * and its live file changed ({@code page.saved}). Now the re-seed is a pending revision; the public page is + * untouched until approved. + */ + @Test + void aReviewedReseedByANonApproverIsAPendingRevision() throws Exception { + String before = body("rs1"); + mvc.perform(post("/__admin/pages/rs1/reseed").session(login("editor")).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("flash", Matchers.containsString("pending revision"))); + assertEquals(before, body("rs1"), "the live file is byte-for-byte unchanged"); + mvc.perform(get("/rs1")).andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("STALE_HEADER"))) + .andExpect(content().string(Matchers.not(Matchers.containsString("FRESH_HEADER")))); + PendingRevisionStore.Revision revision = writer.pending().revision("acme", "rs1").orElseThrow(); + assertTrue(revision.html().contains("FRESH_HEADER") && revision.html().contains("LIVE_rs1"), + "the re-seeded page waits for review, content kept"); + assertTrue(writer.pending().review("acme", "rs1").orElseThrow().isSubmitted(), "and it is in the queue"); + } + + @Test + void aReviewedReseedByAnApproverWritesLiveAfterTheGate() throws Exception { + mvc.perform(post("/__admin/pages/rs2/reseed").session(login("approver")).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("flash", "Chrome re-seeded from the master.")); + assertTrue(body("rs2").contains("FRESH_HEADER") && body("rs2").contains("LIVE_rs2")); + assertFalse(writer.pending().exists("acme", "rs2"), "nothing pending"); + } + + @Test + void anEnforcedReseedOfAPublishedPageWithQualityErrorsIsRefused() throws Exception { + lifecycle.updateEditorial("acme", EditorialLevel.ENFORCED); + String before = body("rs3"); + mvc.perform(post("/__admin/pages/rs3/reseed").session(login("editor")).with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(flash().attribute("error", Matchers.startsWith("Not re-seeded"))); + assertEquals(before, body("rs3"), "nothing was written"); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/FragmentsScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/FragmentsScreenTest.java new file mode 100644 index 0000000..338d482 --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/FragmentsScreenTest.java @@ -0,0 +1,369 @@ +package mx.quest.runway.console; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.page.FragmentTemplates; +import mx.quest.runway.page.PageStore; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteContextFilter; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** + * The tenant Fragments editor ({@code /__admin/fragments}). Proves the screen renders and is + * CONFIGURE_SITE-gated; that create/edit/delete persist to the bound site's {@code templates/} only + * (a second site is byte-for-byte untouched — isolation); that a traversal / error-page / non-underscore name + * is rejected without writing; that the editor cannot clobber a page's {@code .meta.yml} or a master; and that + * a save is visible on the next read (the source round-trips) — the immediate-apply contract. + * + *

The bound tenancy is {@code acme} (host {@code localhost}, which MockMvc requests carry). A second site + * {@code other} (host {@code other.test}) exists only to prove isolation — this route can never touch it. + */ +@SpringBootTest +class FragmentsScreenTest { + + private static final String PW = "Fragments-Screen-2"; + + private static Path externalDir; + private static StorageLayout layout; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-2-2"); + externalDir = external; + StorageProperties props = new StorageProperties(); + props.setExternal(external); + layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + SiteStore sites = new SiteStore(layout, yaml); + sites.save(new Site("acme", "Acme", List.of("localhost"), Locale.ENGLISH, + List.of(Locale.ENGLISH, Locale.forLanguageTag("es")), null, SiteStatus.ACTIVE)); + sites.save(new Site("other", "Other", List.of("other.test"), Locale.ENGLISH, + List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + UserStore users = new UserStore(yaml); + Path acmeUsers = layout.siteDir("acme").resolve("users.yml"); + users.save(acmeUsers, new User("acme-admin", "admin", hash, "Admin", "", true, false, Realm.TENANT, + Set.of(Roles.ADMIN), List.of())); // wildcard → has CONFIGURE_SITE + users.save(acmeUsers, new User("acme-op", "op", hash, "Op", "", true, false, Realm.TENANT, + Set.of(Roles.OPERATOR), List.of())); // no CONFIGURE_SITE + users.save(external.resolve("app-users.yml"), new User("app-master", "root", hash, "Root", "", true, + true, Realm.APPLICATION, Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteResolver siteResolver; + @Autowired + private FragmentTemplates fragments; + @Autowired + private PageStore pages; + private MockMvc mvc; + + @BeforeEach + void setUp() throws IOException { + // Reset both sites' templates/ to a known baseline before each test (they share the class's external + // dir), so the mutating tests do not depend on each other's ordering. + resetTemplates("acme"); + resetTemplates("other"); + mvc = MockMvcBuilders.webAppContextSetup(context) + .addFilters(new SiteContextFilter(siteResolver)) + .apply(springSecurity()).build(); + } + + /** Lays down a master, a fragment, and one routable page under a site's templates dir. */ + private static void resetTemplates(String siteId) throws IOException { + Path templates = layout.siteDir(siteId).resolve("templates"); + // Wipe any files a prior test wrote (only regular files; the dir itself is kept). + if (Files.isDirectory(templates)) { + try (var walk = Files.list(templates)) { + for (Path p : walk.toList()) { + Files.deleteIfExists(p); + } + } + } + Files.createDirectories(templates); + write(templates.resolve("_master.html"), "Mm"); + write(templates.resolve("_head.html"), ""); + // A routable page (its .meta.yml is the anchor the fragment editor must never touch). + write(templates.resolve("index.html"), "

hi
"); + write(templates.resolve("index.meta.yml"), "path: /\ntemplate: _master\ntitle:\n en: Home\n"); + } + + private static void write(Path file, String content) throws IOException { + Files.writeString(file, content, StandardCharsets.UTF_8); + } + + private MockHttpSession sessionFor(String username) throws Exception { + MvcResult r = mvc.perform(formLogin("/login").user(username).password(PW)).andReturn(); + return (MockHttpSession) r.getRequest().getSession(false); + } + + // --- list + gating ----------------------------------------------------------------------------- + + @Test + void theListRendersTheBoundSitesFragments() throws Exception { + mvc.perform(get("/__admin/fragments").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("_master"))) // the master is a fragment + .andExpect(content().string(Matchers.containsString("_head"))) // and the head partial + .andExpect(content().string(Matchers.containsString("/__admin/fragments/_head/edit"))) + .andExpect(content().string(Matchers.containsString("New fragment"))); + } + + @Test + void thePageAndItsMetaAreNotListedAsFragments() throws Exception { + // index is a routable page (backed by index.meta.yml) — it must not appear in the chrome list. + mvc.perform(get("/__admin/fragments").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.not(Matchers.containsString(">index<")))); + } + + @Test + void anOperatorWithoutConfigureSiteCannotSeeTheList() throws Exception { + mvc.perform(get("/__admin/fragments").session(sessionFor("op"))) + .andExpect(status().isForbidden()); + } + + @Test + void anOperatorWithoutConfigureSiteCannotSave() throws Exception { + mvc.perform(post("/__admin/fragments/_head").session(sessionFor("op")).with(csrf()) + .param("html", "")) + .andExpect(status().isForbidden()); + } + + // --- editor render ----------------------------------------------------------------------------- + + @Test + void theEditorRendersTheFragmentSourceAndTheCodeMirrorBundle() throws Exception { + mvc.perform(get("/__admin/fragments/_head/edit").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("/__assets/vendor/codemirror.min.js"))) + .andExpect(content().string(Matchers.containsString("meta charset"))) // the html source + .andExpect(content().string(Matchers.containsString("action=\"/__admin/fragments/_head\""))); + } + + @Test + void theEditorIs404ForAnUnknownFragment() throws Exception { + mvc.perform(get("/__admin/fragments/_nope/edit").session(sessionFor("admin"))) + .andExpect(status().isNotFound()); + } + + @Test + void theCreateFormPostsToTheCollection() throws Exception { + mvc.perform(get("/__admin/fragments/new").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("action=\"/__admin/fragments\""))) + .andExpect(content().string(Matchers.containsString("name=\"name\""))); + } + + // --- create / edit / delete round-trip --------------------------------------------------------- + + @Test + void creatingAFragmentPersistsBothFilesToTheBoundSite() throws Exception { + mvc.perform(post("/__admin/fragments").session(sessionFor("admin")).with(csrf()) + .param("name", "_scripts") + .param("html", "
S
") + .param("thxml", "")) + .andExpect(status().is3xxRedirection()); + + assertEquals("
S
", fragments.readHtml("acme", "_scripts").orElseThrow()); + assertEquals("", fragments.readLogic("acme", "_scripts").orElseThrow()); + // A create with no name in 'other' proves nothing crossed over. + assertFalse(fragments.exists("other", "_scripts"), "the second site got no fragment"); + } + + @Test + void savingOverwritesTheFragmentAndIsVisibleOnTheNextRead() throws Exception { + // Immediate-apply contract: the write path + cache evict means a re-read returns the new source. + mvc.perform(post("/__admin/fragments/_head").session(sessionFor("admin")).with(csrf()) + .param("html", "CHANGED") + .param("thxml", "")) + .andExpect(status().is3xxRedirection()); + + assertEquals("CHANGED", fragments.readHtml("acme", "_head").orElseThrow()); + assertTrue(fragments.readLogic("acme", "_head").isEmpty(), "a blank thxml removes any logic file"); + } + + @Test + void deletingRemovesTheFragmentFiles() throws Exception { + assertTrue(fragments.exists("acme", "_head")); + mvc.perform(post("/__admin/fragments/_head/delete").session(sessionFor("admin")).with(csrf())) + .andExpect(status().is3xxRedirection()); + assertFalse(fragments.exists("acme", "_head"), "the fragment was deleted from the bound site"); + } + + // --- isolation --------------------------------------------------------------------------------- + + @Test + void mutationsLeaveASecondSiteEntirelyUntouched() throws Exception { + MockHttpSession admin = sessionFor("admin"); + // Create, overwrite and delete in the bound site (acme)… + mvc.perform(post("/__admin/fragments").session(admin).with(csrf()) + .param("name", "_nav").param("html", "")) + .andExpect(status().is3xxRedirection()); + mvc.perform(post("/__admin/fragments/_head").session(admin).with(csrf()) + .param("html", "acme-changed")) + .andExpect(status().is3xxRedirection()); + + // …the 'other' site (host other.test) must be byte-for-byte its baseline. + Path otherHead = layout.siteDir("other").resolve("templates").resolve("_head.html"); + assertEquals("", + Files.readString(otherHead, StandardCharsets.UTF_8), "the other site's _head is unchanged"); + assertFalse(Files.exists(layout.siteDir("other").resolve("templates").resolve("_nav.html")), + "the created fragment did not leak into the other site"); + } + + // --- path-safety + scope ----------------------------------------------------------------------- + + @Test + void aTraversalNameIsRejectedAndWritesNothing() throws Exception { + // A '..'-bearing name reaches the create form's `name` param; isFragmentName rejects it (its safe-id + // grammar forbids '/' and '..'), so nothing is written and nothing escapes templates/. + mvc.perform(post("/__admin/fragments").session(sessionFor("admin")).with(csrf()) + .param("name", "../evil").param("html", "PWNED")) + .andExpect(status().is3xxRedirection()); + assertFalse(Files.exists(layout.siteDir("acme").resolve("evil.html")), + "a traversal name never writes outside templates/"); + assertFalse(Files.exists(externalDir.resolve("evil.html")), "nothing landed in the external root"); + assertFalse(Files.exists(layout.siteDir("acme").resolve("templates").resolve("evil.html")), + "and no 'evil' fragment was created either"); + } + + @Test + void anErrorPageNameIsRejected() throws Exception { + // _404 is an error page, not a chrome fragment — out of scope, rejected. + mvc.perform(post("/__admin/fragments").session(sessionFor("admin")).with(csrf()) + .param("name", "_404").param("html", "")) + .andExpect(status().is3xxRedirection()); + assertFalse(fragments.exists("acme", "_404"), "an error-page name is refused"); + assertFalse(Files.exists(layout.siteDir("acme").resolve("templates").resolve("_404.html"))); + } + + @Test + void aNonUnderscoreNameIsRejected() throws Exception { + // A page-shaped slug (no leading underscore) is not a fragment — the two areas stay disjoint. + mvc.perform(post("/__admin/fragments").session(sessionFor("admin")).with(csrf()) + .param("name", "index").param("html", "")) + .andExpect(status().is3xxRedirection()); + // The routable page's files are untouched (the create was refused before any write). + Path meta = layout.siteDir("acme").resolve("templates").resolve("index.meta.yml"); + assertTrue(Files.exists(meta), "the page's meta anchor is intact"); + assertEquals("
hi
", + Files.readString(layout.siteDir("acme").resolve("templates").resolve("index.html"), + StandardCharsets.UTF_8), "the page body was not clobbered"); + // And the page still resolves through the read-only PageStore. + assertTrue(pages.find("acme", "index").isPresent(), "the page is still a page"); + } + + @Test + void savingAFragmentDoesNotDisturbTheRoutablePagesMeta() throws Exception { + // Editing the _head fragment must leave index.meta.yml exactly as it was. + Path meta = layout.siteDir("acme").resolve("templates").resolve("index.meta.yml"); + String before = Files.readString(meta, StandardCharsets.UTF_8); + mvc.perform(post("/__admin/fragments/_head").session(sessionFor("admin")).with(csrf()) + .param("html", "edited")) + .andExpect(status().is3xxRedirection()); + assertEquals(before, Files.readString(meta, StandardCharsets.UTF_8), "a fragment save never touches page meta"); + } + + @Test + void anErrorPageIsCreatedFromTheMasterEditedAndServedForThatStatus() throws Exception { + MockHttpSession admin = sessionFor("admin"); + String list = mvc.perform(get("/__admin/fragments").session(admin)).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + assertTrue(list.contains("Error pages"), "the screen has the error-pages card"); + assertTrue(list.contains("value=\"404\""), "404 is offered"); + + mvc.perform(post("/__admin/fragments/error-pages").session(admin).with(csrf()).param("code", "404")) + .andExpect(redirectedUrl("/__admin/fragments/_404/edit")); + assertTrue(fragments.errorPageExists("acme", "_404")); + assertFalse(fragments.exists("acme", "_404"), "it is an error page, never a fragment"); + String starter = fragments.readErrorPageHtml("acme", "_404").orElseThrow(); + assertTrue(starter.contains("Page not found"), "starter text for the status"); + assertTrue(fragments.readErrorPageLogic("acme", "_404").orElseThrow().contains("${master} :: head"), + "it pulls the master's head like a page born from the master"); + + mvc.perform(get("/__admin/fragments/_404/edit").session(admin)).andExpect(status().isOk()); + mvc.perform(post("/__admin/fragments/_404").session(admin).with(csrf()) + .param("html", "x" + + "
LOST_IN_ACME
") + .param("thxml", "")) + .andExpect(redirectedUrl("/__admin/fragments/_404/edit")); + mvc.perform(get("/no-such-page-here")) + .andExpect(status().isNotFound()) + .andExpect(content().string(Matchers.containsString("LOST_IN_ACME"))); + + String after = mvc.perform(get("/__admin/fragments").session(admin)).andReturn().getResponse() + .getContentAsString(); + assertTrue(after.contains("404 Not Found"), "listed with its status"); + mvc.perform(post("/__admin/fragments/error-pages").session(admin).with(csrf()).param("code", "404")) + .andExpect(flash().attributeExists("error")); + + mvc.perform(post("/__admin/fragments/_404/delete").session(admin).with(csrf())) + .andExpect(redirectedUrl("/__admin/fragments")); + assertFalse(fragments.errorPageExists("acme", "_404")); + mvc.perform(get("/no-such-page-here")) + .andExpect(status().isNotFound()) + .andExpect(content().string(Matchers.not(Matchers.containsString("LOST_IN_ACME")))); + } + + @Test + void onlyErrorStatusesMakeErrorPagesAndOnlyForAuthorizedUsers() throws Exception { + MockHttpSession admin = sessionFor("admin"); + for (String bad : new String[] {"200", "302", "600", "4044", "abc", "../4"}) { + mvc.perform(post("/__admin/fragments/error-pages").session(admin).with(csrf()).param("code", bad)) + .andExpect(flash().attributeExists("error")); + } + mvc.perform(post("/__admin/fragments/_404").session(admin).with(csrf()).param("html", "")) + .andExpect(flash().attributeExists("error")); + assertFalse(fragments.errorPageExists("acme", "_404"), "saving cannot conjure an error page up"); + mvc.perform(post("/__admin/fragments/error-pages").session(sessionFor("op")).with(csrf()).param("code", "500")) + .andExpect(status().isForbidden()); + assertFalse(fragments.errorPageExists("acme", "_500")); + } +} diff --git a/runway-app/src/test/java/mx/quest/runway/console/IconsScreenTest.java b/runway-app/src/test/java/mx/quest/runway/console/IconsScreenTest.java new file mode 100644 index 0000000..19bf11d --- /dev/null +++ b/runway-app/src/test/java/mx/quest/runway/console/IconsScreenTest.java @@ -0,0 +1,200 @@ +package mx.quest.runway.console; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import mx.quest.runway.icon.SiteIcon; +import mx.quest.runway.icon.SiteIconService; +import mx.quest.runway.icon.SiteManifestService; +import mx.quest.runway.security.PasswordEncoders; +import mx.quest.runway.security.PasswordStrength; +import mx.quest.runway.security.Roles; +import mx.quest.runway.security.User; +import mx.quest.runway.security.UserStore; +import mx.quest.runway.site.Site; +import mx.quest.runway.site.SiteContextFilter; +import mx.quest.runway.site.SiteResolver; +import mx.quest.runway.site.SiteStatus; +import mx.quest.runway.site.SiteStore; +import mx.quest.runway.spi.model.Realm; +import mx.quest.runway.storage.StorageLayout; +import mx.quest.runway.storage.StorageProperties; +import mx.quest.runway.storage.YamlStore; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +/** The tenant Icons screen: render, per-slot upload/delete, manifest save, and CONFIGURE_SITE gating. */ +@SpringBootTest +class IconsScreenTest { + + private static final String PW = "Icons-Screen-7"; + + @DynamicPropertySource + static void config(DynamicPropertyRegistry registry) throws IOException { + Path external = Files.createTempDirectory("runway-4b"); + StorageProperties props = new StorageProperties(); + props.setExternal(external); + StorageLayout layout = StorageLayout.from(props); + YamlStore yaml = new YamlStore(); + new SiteStore(layout, yaml).save(new Site("acme", "Acme", List.of("localhost"), + Locale.ENGLISH, List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE)); + String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode(PW); + UserStore users = new UserStore(yaml); + Path siteUsers = layout.siteDir("acme").resolve("users.yml"); + users.save(siteUsers, new User("acme-admin", "admin", hash, "Admin", "", true, false, Realm.TENANT, + Set.of(Roles.ADMIN), List.of())); + users.save(siteUsers, new User("acme-op", "op", hash, "Op", "", true, false, Realm.TENANT, + Set.of(Roles.OPERATOR), List.of())); + users.save(external.resolve("app-users.yml"), new User("app-master", "root", hash, "Root", "", true, + true, Realm.APPLICATION, Set.of(Roles.SYSTEM_SUPERADMIN), List.of())); + registry.add("runway.storage.external", () -> external.toString()); + registry.add("runway.security.app-master-id", () -> "app-master"); + } + + @Autowired + private WebApplicationContext context; + @Autowired + private SiteResolver siteResolver; + @Autowired + private SiteIconService icons; + @Autowired + private SiteManifestService manifests; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.webAppContextSetup(context) + .addFilters(new SiteContextFilter(siteResolver)) + .apply(springSecurity()).build(); + } + + private MockHttpSession sessionFor(String username) throws Exception { + MvcResult r = mvc.perform(formLogin("/login").user(username).password(PW)).andReturn(); + return (MockHttpSession) r.getRequest().getSession(false); + } + + @Test + void theIconsScreenRendersSlotsAndNoLongerCarriesTheManifestForm() throws Exception { + mvc.perform(get("/__admin/icons").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("/favicon.svg"))) + // the Web app manifest form moved to its own /__admin/manifest screen + .andExpect(content().string(Matchers.not(Matchers.containsString("action=\"/__admin/manifest\"")))); + } + + @Test + void theManifestScreenRendersItsOwnForm() throws Exception { + mvc.perform(get("/__admin/manifest").session(sessionFor("admin"))) + .andExpect(status().isOk()) + .andExpect(content().string(Matchers.containsString("action=\"/__admin/manifest\""))); + } + + @Test + void uploadThenTheSlotIsPresentAndDeleteRemovesIt() throws Exception { + MockHttpSession admin = sessionFor("admin"); + MockMultipartFile file = new MockMultipartFile("file", "favicon.svg", "image/svg+xml", "".getBytes()); + mvc.perform(multipart("/__admin/icons/svg-favicon/upload").file(file).session(admin).with(csrf())) + .andExpect(status().is3xxRedirection()); + assertTrue(icons.present("acme", SiteIcon.SVG_FAVICON), "the icon is stored after upload"); + + mvc.perform(post("/__admin/icons/svg-favicon/delete").session(admin).with(csrf())) + .andExpect(status().is3xxRedirection()); + assertFalse(icons.present("acme", SiteIcon.SVG_FAVICON), "the icon is gone after delete"); + } + + @Test + void manifestSavePersistsTheFields() throws Exception { + mvc.perform(post("/__admin/manifest").session(sessionFor("admin")).with(csrf()) + .param("name", "Acme").param("display", "standalone").param("themeColor", "#0d6efd")) + .andExpect(status().is3xxRedirection()); + assertEquals("Acme", manifests.get("acme").name()); + assertEquals("standalone", manifests.get("acme").display()); + } + + @Test + void anInvalidColourDisplayOrLanguageIsRefusedAndNothingIsSaved() throws Exception { + var admin = sessionFor("admin"); + mvc.perform(post("/__admin/manifest").session(admin).with(csrf()) + .param("name", "Acme").param("display", "standalone").param("themeColor", "#0d6efd")) + .andExpect(status().is3xxRedirection()); + for (String[] bad : new String[][] {{"themeColor", "blue"}, {"backgroundColor", "#12345"}, + {"display", "window"}, {"lang", "english"}}) { + mvc.perform(post("/__admin/manifest").session(admin).with(csrf()).param("name", "Changed") + .param(bad[0], bad[1])) + .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash() + .attributeExists("error")); + } + assertEquals("Acme", manifests.get("acme").name(), "a refused save changes nothing"); + mvc.perform(post("/__admin/manifest").session(admin).with(csrf()).param("name", "Acme") + .param("themeColor", "#ABC").param("display", "MINIMAL-UI").param("lang", "pt-br")) + .andExpect(status().is3xxRedirection()); + assertEquals("#abc", manifests.get("acme").themeColor()); + assertEquals("minimal-ui", manifests.get("acme").display()); + assertEquals("pt-BR", manifests.get("acme").lang()); + mvc.perform(get("/__admin/manifest").session(admin)) + .andExpect(content().string(org.hamcrest.Matchers.containsString( + "