Repository navigation
Conversation
Macbet
left a comment
There was a problem hiding this comment.
Thanks for this. I went through the change and left inline comments. The main ones are the unauthenticated /public/v1/announcements endpoint (AGENTS.md §12), banner overflow on small screens, the custom/null-role permission gap, and reads of draft or scheduled GLOBAL announcements. The rest are smaller fixes and cleanups.
| public ResponseEntity<PublicAnnouncementsResponse> getActiveLoginAnnouncements() { | ||
| Instant now = Instant.now(); | ||
| List<PublicAnnouncementDto> announcements = announcementRepository | ||
| .findActiveLoginGlobalAnnouncements(Date.from(now)) |
There was a problem hiding this comment.
This endpoint is unauthenticated (permitted in DexWebSecurityAdapter), but it runs findActiveLoginGlobalAnnouncements on every request, sends Cache-Control: no-store, has no rate limit, and the DTO exposes the announcement id (UUID). AGENTS.md §12 says unauthenticated endpoints must be stateless with zero DB queries and zero internal UUID exposure. It is also a custom JPQL listing outside Elide (§1).
One option: keep a small in-memory snapshot of the login announcements, refreshed on announcement create/update/delete or on a short timer. Serve that with a short public cache TTL and drop id from the public DTO.
| @@ -0,0 +1,218 @@ | |||
| .announcement-banner-tray { | |||
| flex-shrink: 0; | |||
There was a problem hiding this comment.
The tray has flex-shrink: 0 and no max-height/overflow, and it sits inside .app-shell (height: 100vh; overflow: hidden). A non-dismissible CRITICAL banner with a long Markdown message, or the expanded "View N more" list on a phone or short laptop screen, can fill the viewport. .layout then collapses to zero height and the app can't be used or scrolled. Consider max-height: 40vh; overflow-y: auto (or similar) on the tray.
|
|
||
| @Override | ||
| public boolean canManageAnnouncements(Team team) { | ||
| return ROLE_ADMIN.equals(normalizeRole(team.getRole())); |
There was a problem hiding this comment.
Every other canManage* method maps ROLE_CUSTOM to a boolean flag, but this one returns true only for admin. Older teams with a null role are normalized to custom, so an org admin team created before roles existed (all manage* flags true) gets manageAnnouncements=false and a 403 from AnnouncementManageCheck. A custom role also can't be given this permission at all. Is that intended? If not, a fallback such as ROLE_CUSTOM -> team.isManagePermission() (or a dedicated flag) would keep it consistent.
| HttpStatus.SC_BAD_REQUEST, "Global announcements cannot be linked to an organization"); | ||
| } | ||
| } else if (announcement.getScope() == AnnouncementScope.ORGANIZATION) { | ||
| if (announcement.getOrganization() == null) { |
There was a problem hiding this comment.
I haven't reproduced this, but I think it can block hard org deletion. When an Organization is deleted through Elide, Elide clears the inverse organization relationship on each related Announcement and marks it dirty. This UPDATE PRECOMMIT hook then sees an ORGANIZATION-scoped announcement with a null org, throws a 400 and rolls back the delete, even though the FK has ON DELETE CASCADE for this case. Worth a test that deletes an org with org-scoped announcements.
| if (AnnouncementCheckSupport.isInternalOrUnauthenticated(user)) { | ||
| return false; | ||
| } | ||
| if (announcement.getScope() == AnnouncementScope.GLOBAL) { |
There was a problem hiding this comment.
Any authenticated user can read every GLOBAL announcement through JSON:API/GraphQL, including inactive drafts (active=false) and scheduled ones whose startsAt is in the future. A draft maintenance or incident notice is readable by a user with read access to a single project before it's published, because the time window is only enforced in the UI. Suggest allowing non-superusers only when active && now within [startsAt, endsAt], or filtering that server-side.
| if (title == null || title.isBlank()) { | ||
| throw new AnnouncementValidationException(HttpStatus.SC_BAD_REQUEST, "title is required"); | ||
| } | ||
| if (title.trim().length() > MAX_TITLE_LENGTH) { |
There was a problem hiding this comment.
The check measures title.trim(), but the untrimmed title is what gets persisted to the varchar(120) column. An API client sending 118 characters plus trailing spaces passes this check and then fails at flush with a 500 instead of this 400. Either trim and set the title before validating, or check title.length().
| announcements: AnnouncementItem[]; | ||
| serverTimeMs: number; | ||
| }> { | ||
| const response = await axiosAuxiliary.get("announcement?include=organization", { |
There was a problem hiding this comment.
This fetches every announcement in the system with no server-side filter. It runs on every route change (the routeKey dependency in AnnouncementContext.tsx) and every 60s, then filters in the browser. Each call makes Elide load all rows, run AnnouncementReadCheck per row (which lazy-loads org teams and group membership) and serialize the included organizations. A superuser downloads every org's announcements just to render the GLOBAL ones.
Suggest a filter like filter[announcement]=active==true;(scope==GLOBAL,organization.id==<orgId>), and dropping the refetch on every route change (refetch only on org change and on the timer, ideally pausing the timer while the tab is hidden).
| } | ||
| } | ||
|
|
||
| private boolean isSuperUser(JwtAuthenticationToken principalJwt, List<String> groups) { |
There was a problem hiding this comment.
This duplicates the superuser logic that already exists in the IsSuperUser check / AuthenticatedUser.isSuperUser (internal-token exclusion plus instance-owner membership). The controller uses groups.contains(instanceOwner) while Elide uses isMember/isServiceMember, so the UI and API could disagree about who is a superuser. It also changes existing /permissions behavior: internal tokens, and the case where instanceOwner is blank, no longer get managePermission/managePolicies as they did before. Could this delegate to the existing helper instead?
| validate(announcement); | ||
|
|
||
| if (operation == LifeCycleHookBinding.Operation.UPDATE) { | ||
| announcement.setUpdatedDate(new Date()); |
There was a problem hiding this comment.
Nit: GenericAuditFields already has @UpdateTimestamp, so setting updatedDate by hand isn't needed.
| public void disableOrganization(Organization organization){ | ||
| log.info("Disable Organization Id: {}", organization.getId().toString()); | ||
|
|
||
| if (announcementRepository != null) { |
There was a problem hiding this comment.
Nit: announcementRepository is always injected through @AllArgsConstructor, so this null guard is dead code. If the repository were ever mis-wired, the guard would silently skip the cascade and leave orphaned announcements instead of failing at startup. Suggest removing it (and updating the test that passes null, if there is one).
|
Thanks for this, it is a well-scoped feature. The additive I fetched the branch and it merges cleanly onto current I've read the inline comments already on the PR and agree with them, so I won't repeat them in full. These are the ones I think matter most, plus what I verified myself. 1. Drafts and future-dated global announcements are readable by every authenticated user. 2. The unauthenticated endpoint should not hit the database on every request. 3. 4. 5. The banner tray can take over the viewport. A few smaller things:
Not for this PR: this adds a new API resource, so it would be worth a follow-up issue for Point 1 is the one I'd want fixed before merge, along with the CI failure. Happy to re-review once those and the public endpoint are sorted |
|
@Macbet (and @jakegroves) — thank you for the thorough review! I have synced Summary of Fixes
Verification Re-run After All Fixes &
|
Macbet
left a comment
There was a problem hiding this comment.
Two correctness issues worth fixing before merge (refetch loop in AnnouncementContext, orphanRemoval deleting announcements on scope change); the rest are minor.
| const timeoutId = window.setTimeout(() => { | ||
| setTick((t) => t + 1); | ||
| void refreshAnnouncements(); | ||
| }, nextBoundaryMs + 250); |
There was a problem hiding this comment.
Bug: tight refetch loop for far-future boundaries. getNextScheduleBoundaryMs clamps to MAX_TIMEOUT_MS (2_147_483_647), but + 250 is added after the clamp. Browsers treat a delay above int32 max as ~0, so the timeout fires immediately → setTick → effect re-runs → fires again, calling refreshAnnouncements() each time.
Any active announcement with startsAt/endsAt more than ~24.8 days ahead triggers it (e.g. the demo announcement ending 2030-12-31), so every signed-in page hammers GET /api/v1/announcement.
Suggestion: clamp after adding the slack, e.g. Math.min(nextBoundaryMs + 250, MAX_TIMEOUT_MS), or skip scheduling when the boundary is beyond ~24 days (the 60s poll covers it). A unit test with a boundary far in the future would catch this.
| private List<io.terrakube.api.rs.policy.PolicyExemption> policyExemption; | ||
|
|
||
| @UpdatePermission(expression = "user belongs organization") | ||
| @OneToMany(mappedBy = "organization", cascade = CascadeType.REMOVE, orphanRemoval = true) |
There was a problem hiding this comment.
Bug: orphanRemoval = true can delete an announcement when its scope/org is edited. When an announcement's organization is changed, Elide removes it from the old Organization.announcement collection, and Hibernate deletes the removed element as an orphan on flush.
The UI does exactly this in updateAnnouncement: switching scope to GLOBAL sends organization: {data: null}, and changing org points it at another id. Result: the edit silently deletes the announcement.
Suggestion: drop orphanRemoval (DB ON DELETE CASCADE + CascadeType.REMOVE already cover org deletion) and add an integration test for ORGANIZATION → GLOBAL and org → org moves.
| } | ||
|
|
||
| public void evict() { | ||
| cachedSnapshot = null; |
There was a problem hiding this comment.
Minor race: evict() writes cachedSnapshot = null without the monitor. A refresh already inside synchronized (this) may have read the DB before the commit and assign its (stale) snapshot after the evict, so the login page keeps serving the old/deactivated announcement until the TTL expires.
Suggestion: take the same lock in evict() and add a generation counter so a refresh started before an evict doesn't publish its result.
| if (current != null && now.isBefore(current.loadedAt().plus(CACHE_TTL))) { | ||
| return current; | ||
| } | ||
| List<CachedEntry> entries = announcementRepository.findActiveLoginGlobalAnnouncements().stream() |
There was a problem hiding this comment.
This anonymous endpoint still hits the DB (findActiveLoginGlobalAnnouncements()) on every TTL expiry/evict. Project rules (CLAUDE.md §12) require unauthenticated endpoints to be stateless with zero DB queries. Either get an explicit maintainer exception for this case, or populate the snapshot from the write path (hooks / startup) so anonymous requests never trigger a query.
| if (title == null || title.isBlank()) { | ||
| throw new AnnouncementValidationException(HttpStatus.SC_BAD_REQUEST, "title is required"); | ||
| } | ||
| if (title.length() > MAX_TITLE_LENGTH) { |
There was a problem hiding this comment.
Length is checked before trim(), so a 118-char title with trailing spaces gets a 400 even though the stored value would fit (the entity's @Size(max = 120) also sees the untrimmed value). The related test name says it's trimmed before the length check, which is the opposite of what happens. Suggest trimming first, then validating blank/length.
| List<PublicAnnouncementDto> announcements = publicAnnouncementCacheService.getActiveLoginAnnouncements(now); | ||
|
|
||
| return ResponseEntity.ok() | ||
| .header("Cache-Control", "public, max-age=30") |
There was a problem hiding this comment.
Cache-Control: public, max-age=30 on a response that carries X-Server-Time / serverTime: a browser or shared cache can serve a copy up to 30s old, and LoginAnnouncements uses that stale server time as "now" — countdown labels drift and an announcement past endsAt can stay visible for up to another 30s. Consider private, no-cache (server-side cache already absorbs load) or not deriving the clock offset from cached responses.
|




Fixes #3733
Summary
Introduces a centralized Announcement & Scheduled Maintenance Banner system across
terrakube/apiandterrakube/ui, supporting two-tier administration (Platform Superusers and Organization Admins), scheduled activation windows, severity categorization (INFO,WARNING,CRITICAL), sanitized Markdown formatting, and version-aware client-side dismissal.Use Cases
/loginscreen (displayOnLogin = true) before an API/database upgrade or during an incident./organizations/:orgId/*), with full multi-tenant isolation.updatedDate,title, ormessage) or marks it non-dismissible.CRITICAL>WARNING>INFO) andstartsAtdescending, with secondary banners collapsed behind an expandable "View N more active announcement(s)" tray.How It Was Implemented
1. Liquibase Schema & Sample Demo Data (
terrakube/api)local/changelog-2.35.0-announcements.xml, registered inchangelog.xml): Creates theannouncementtable (id,titlemax 120 chars,messageastext,severity,scope,schedule_type,organization_idFK withON DELETE CASCADE,starts_at,ends_at,is_active,is_dismissible,display_on_login, andGenericAuditFieldscolumns) with indexes on(scope, is_active, starts_at, ends_at)and(organization_id).demo-data/simple-announcements.xml, registered inchangelog-demo.xml): Seeds thesimple-announcementsorganization (80000000-0000-0000-0000-000000000001), RBAC v2 teams (TERRAKUBE_ADMIN,TERRAKUBE_DEVELOPERS,ANNOUNCEMENT_ORG_ADMINwith all 13 permission columns), a sample workspace/template, and 4 active sample announcements (1 globalINFOlogin banner, 1 org-scoped non-dismissibleCRITICAL, 1 org-scoped scheduledWARNING, and 1 org-scopedINFOwith Markdown links).2. Backend API, Security & Lifecycle (
terrakube/api)io.terrakube.api.rs.announcement):AnnouncementextendsGenericAuditFieldsand usesAnnouncementSeverity,AnnouncementScope, andAnnouncementScheduleType.scopeandorganizationfields enforce@UpdatePermission(expression = "user is a superuser"). Addedannouncementrelationship toOrganization.canManageAnnouncements(Team)toRbacService/RbacV2Service(strictlyrole == "admin").AnnouncementReadCheck("announcement read check") andAnnouncementManageCheck("announcement manage check") failing closed on unauthenticated or internal machine tokens (InternalTokenClassifier), restricting global CRUD to superusers and org CRUD to that org's admin teams or superusers.TeamTokenController(/access-token/v1/teams/permissions/...and/current-teams) to exposesuperUserandmanageAnnouncements.AnnouncementManageHook(PRECOMMITonCREATE/UPDATE) enforces title length (<= 120), non-blank message, scope/organization/login invariants,SCHEDULEDdate-range validity (endsAt > startsAt), and bumpsupdatedDateon update.SoftDeleteService.disableOrganization()invokes a native SQL delete (AnnouncementRepository.deleteByOrganizationId) so Hibernate's@SQLRestriction("disabled = false")onOrganizationdoes not leave orphaned rows.PublicAnnouncementController(GET /public/v1/announcements) permitted inDexWebSecurityAdapterreturns minimal DTOs (id,title,message,severity,startsAt,endsAt,updatedDate) only for activeGLOBALannouncements withdisplayOnLogin = true(no organization or audit metadata).ServerTimeResponseFilterattachesX-Server-Time(exposed via CORS) to announcement/GraphQL responses so UI activation windows align with server UTC.3. Frontend (
terrakube/ui)src/modules/announcements):AnnouncementBannerrenders edge-to-edge at the very top ofAppLayoutaboveAppSidebarand content, avoiding overlap with the sidebar edge-collapse toggle.AnnouncementProviderfetches viaaxiosAuxiliaryon mount, route/org transitions, 60s polling, and scheduled boundary timers using theX-Server-Timeoffset.dismissalStorage.tsstores{ announcementId, versionHash }inlocalStorageunderterrakube_dismissed_announcements, automatically resurfacing banners whenupdatedDate,title, ormessagechanges or whendismissiblebecomesfalse.AnnouncementMarkdownrenders Markdown viareact-markdown,remark-gfm, andrehype-sanitize(withoutrehype-raw) and restricts linkhrefs tohttp:,https:,mailto:, or relative paths.LoginAnnouncementsrenders active global login banners above the sign-in card on/login./organizations/:orgid/settings/announcements) with an extra Platform Announcements tab for superusers./settings/announcementsroute (PlatformAnnouncementsPage) linked in the root sidebar for superusers (useSuperUser).AnnouncementFormModalsupports Markdown write/preview tabs, severity selection,IMMEDIATE/SCHEDULEDdate-time pickers with live UTC conversion, and scope/login toggles.How It Was Tested
Backend (
terrakube/api, JDK25.0.4-librca)mvn test -pl api -Dtest="AnnouncementTests,RbacV2ServiceTest,SoftDeleteServiceTest,AccessTests,PolicyExemptionTests": 47 tests run, 0 failures, 0 errorsAnnouncementTests: Verifiedsimple-announcementsdemo data,GET /public/v1/announcementspublic DTO filtering andX-Server-Time, superuser global CRUD, non-superuser org-admin isolation & scope escalation prevention, developer read-only enforcement, internal machine token fail-closed behavior,AnnouncementManageHookvalidation rules,/permissions&/current-teamsflags, and soft-delete cascade.RbacV2ServiceTest: VerifiedcanManageAnnouncementsallowsadminand denieswrite/plan/read/custom.mvn test -pl api -Dtest="CrossOrganizationSecurityIntegrationTest": 31 tests run, 0 failures, 0 errors.Frontend (
terrakube/ui)yarn lint:check && yarn format:check && yarn typecheck: 0 errors.yarn test --watchAll=false: 144 passed suites (1 pre-existing skipped), 1174 passed tests (1 pre-existing skipped), including new unit/component tests indismissalStorage.test.ts,announcementUtils.test.ts,AnnouncementBanner.test.tsx(verifying<script>andjavascript:URI stripping, dismissibility, and collapsible multi-banner tray),LoginAnnouncements.test.tsx, andAppSidebar.test.tsx.yarn build: Vite production build succeeded cleanly.Examples
Login Page
Organization Page
Inside Organization Page