Skip to content

feat: add announcement and scheduled maintenance banner system (#3733) - #4004

Open
alfespa17 wants to merge 2 commits into
mainfrom
feat/announcements-banner
Open

alfespa17 wants to merge 2 commits into
mainfrom
feat/announcements-banner

Conversation

@alfespa17

Copy link
Copy Markdown
Member

Fixes #3733

Summary

Introduces a centralized Announcement & Scheduled Maintenance Banner system across terrakube/api and terrakube/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

  • Platform-Wide Maintenance & Login Notices (Platform Superuser): Broadcast global banners across all organizations and optionally display them on the unauthenticated /login screen (displayOnLogin = true) before an API/database upgrade or during an incident.
  • Organization-Scoped Advisories (Organization Admin): Communicate org-specific maintenance, credential rotations, or VCS migrations strictly to members browsing that organization (/organizations/:orgId/*), with full multi-tenant isolation.
  • Distraction-Free Visibility & Smart Resurfacing (End User): View an edge-to-edge banner pinned at the top of the screen with severity styling, relative/UTC timing, and clickable Markdown links. Dismissible banners stay hidden across navigation until an admin edits the announcement (updating updatedDate, title, or message) or marks it non-dismissible.
  • Multi-Banner Stacking: Multiple active banners are sorted by severity (CRITICAL > WARNING > INFO) and startsAt descending, 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)

  • Schema (local/changelog-2.35.0-announcements.xml, registered in changelog.xml): Creates the announcement table (id, title max 120 chars, message as text, severity, scope, schedule_type, organization_id FK with ON DELETE CASCADE, starts_at, ends_at, is_active, is_dismissible, display_on_login, and GenericAuditFields columns) with indexes on (scope, is_active, starts_at, ends_at) and (organization_id).
  • Sample Organization (demo-data/simple-announcements.xml, registered in changelog-demo.xml): Seeds the simple-announcements organization (80000000-0000-0000-0000-000000000001), RBAC v2 teams (TERRAKUBE_ADMIN, TERRAKUBE_DEVELOPERS, ANNOUNCEMENT_ORG_ADMIN with all 13 permission columns), a sample workspace/template, and 4 active sample announcements (1 global INFO login banner, 1 org-scoped non-dismissible CRITICAL, 1 org-scoped scheduled WARNING, and 1 org-scoped INFO with Markdown links).

2. Backend API, Security & Lifecycle (terrakube/api)

  • Elide Resource (io.terrakube.api.rs.announcement): Announcement extends GenericAuditFields and uses AnnouncementSeverity, AnnouncementScope, and AnnouncementScheduleType. scope and organization fields enforce @UpdatePermission(expression = "user is a superuser"). Added announcement relationship to Organization.
  • RBAC & Security Checks:
    • Added canManageAnnouncements(Team) to RbacService / RbacV2Service (strictly role == "admin").
    • Implemented AnnouncementReadCheck ("announcement read check") and AnnouncementManageCheck ("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.
    • Updated TeamTokenController (/access-token/v1/teams/permissions/... and /current-teams) to expose superUser and manageAnnouncements.
  • Validation & Soft-Delete Cascade:
    • AnnouncementManageHook (PRECOMMIT on CREATE/UPDATE) enforces title length (<= 120), non-blank message, scope/organization/login invariants, SCHEDULED date-range validity (endsAt > startsAt), and bumps updatedDate on update.
    • SoftDeleteService.disableOrganization() invokes a native SQL delete (AnnouncementRepository.deleteByOrganizationId) so Hibernate's @SQLRestriction("disabled = false") on Organization does not leave orphaned rows.
  • Public Login Endpoint & Clock-Skew Protection:
    • PublicAnnouncementController (GET /public/v1/announcements) permitted in DexWebSecurityAdapter returns minimal DTOs (id, title, message, severity, startsAt, endsAt, updatedDate) only for active GLOBAL announcements with displayOnLogin = true (no organization or audit metadata).
    • ServerTimeResponseFilter attaches X-Server-Time (exposed via CORS) to announcement/GraphQL responses so UI activation windows align with server UTC.

3. Frontend (terrakube/ui)

  • Top Banner & State (src/modules/announcements):
    • AnnouncementBanner renders edge-to-edge at the very top of AppLayout above AppSidebar and content, avoiding overlap with the sidebar edge-collapse toggle.
    • AnnouncementProvider fetches via axiosAuxiliary on mount, route/org transitions, 60s polling, and scheduled boundary timers using the X-Server-Time offset.
    • dismissalStorage.ts stores { announcementId, versionHash } in localStorage under terrakube_dismissed_announcements, automatically resurfacing banners when updatedDate, title, or message changes or when dismissible becomes false.
  • Sanitized Markdown & Login Screen:
    • AnnouncementMarkdown renders Markdown via react-markdown, remark-gfm, and rehype-sanitize (without rehype-raw) and restricts link hrefs to http:, https:, mailto:, or relative paths.
    • LoginAnnouncements renders active global login banners above the sign-in card on /login.
  • Admin Management UI:
    • Organization Settings (/organizations/:orgid/settings/announcements) with an extra Platform Announcements tab for superusers.
    • Dedicated /settings/announcements route (PlatformAnnouncementsPage) linked in the root sidebar for superusers (useSuperUser).
    • AnnouncementFormModal supports Markdown write/preview tabs, severity selection, IMMEDIATE / SCHEDULED date-time pickers with live UTC conversion, and scope/login toggles.

How It Was Tested

Backend (terrakube/api, JDK 25.0.4-librca)

  • mvn test -pl api -Dtest="AnnouncementTests,RbacV2ServiceTest,SoftDeleteServiceTest,AccessTests,PolicyExemptionTests": 47 tests run, 0 failures, 0 errors
    • AnnouncementTests: Verified simple-announcements demo data, GET /public/v1/announcements public DTO filtering and X-Server-Time, superuser global CRUD, non-superuser org-admin isolation & scope escalation prevention, developer read-only enforcement, internal machine token fail-closed behavior, AnnouncementManageHook validation rules, /permissions & /current-teams flags, and soft-delete cascade.
    • RbacV2ServiceTest: Verified canManageAnnouncements allows admin and denies write/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 in dismissalStorage.test.ts, announcementUtils.test.ts, AnnouncementBanner.test.tsx (verifying <script> and javascript: URI stripping, dismissibility, and collapsible multi-banner tray), LoginAnnouncements.test.tsx, and AppSidebar.test.tsx.
  • yarn build: Vite production build succeeded cleanly.

Examples

Login Page

image

Organization Page

image

Inside Organization Page

image image

@github-actions github-actions Bot added terrakube-ui terrakube-api area/db-migration Touches Liquibase changelogs area/security Touches authentication, tokens or authorization area/rbac Touches teams and permissions author/maintainer Authored by a maintainer priority/high Review soon: high-risk area, bug fix or security update size/XL 1000 or more lines changed, consider splitting type/feature New functionality labels Nov 21, 2026

@Macbet Macbet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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", {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@jakegroves

Copy link
Copy Markdown
Member

Thanks for this, it is a well-scoped feature. The additive announcement table is safe for a rolling upgrade, the manage check fails closed on internal tokens, and the scope/organization fields are superuser-only on update, so an org admin can't promote an announcement to GLOBAL. The sanitised Markdown rendering without rehype-raw is also the right call.

I fetched the branch and it merges cleanly onto current main. I ran AnnouncementTests (10), RbacV2ServiceTest (9), SoftDeleteServiceTest (2), AccessTests (21), OrganizationTests (5) and TeamTokenControllerTest (3) with Maven on JDK 25 and they all pass. CI shows build-jammy failing in the "Build Terrakube" step, and I can't see the log from here. Could you check which test fails there and re-run? It may be unrelated, but it needs to be green.

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.
AnnouncementReadCheck returns true for any GLOBAL announcement without looking at active, startsAt or endsAt. The window is only applied in the UI (isAnnouncementCurrentlyActive), so anyone with a token can GET /api/v1/announcement and read an unpublished incident or maintenance notice. The same applies to inactive org-scoped ones for org members. I'd let non-superusers (and non-org-admins for org scope) read only rows where active && now within [startsAt, endsAt]. A test with a non-superuser reading an inactive and a future-dated global announcement would pin it.

2. The unauthenticated endpoint should not hit the database on every request.
GET /public/v1/announcements runs the JPQL query on each call, has no rate limit and returns the row id. A short in-memory cache per pod (around 30s) bounds the DB load without any cross-replica invalidation, and the Cache-Control can then allow a short public TTL instead of no-store. If the UI needs a dismissal key for login banners, an opaque hash of id + updatedDate would avoid exposing the UUID. I'd also add a test for the endpoint on its own, since it is the only public surface this PR adds.

3. /permissions changes behaviour for existing callers.
I diffed TeamTokenController against main. Before, groups.contains(instanceOwner) set managePermission and managePolicies. Now that block is gated by isSuperUser, which returns false for internal tokens and when instanceOwner is blank. That may well be the safer behaviour, but it is a change to an existing endpoint that the UI and other clients read, and it isn't mentioned in the description or covered by a test of the old behaviour. Delegating to the existing superuser helper, as suggested in the inline comment, would also keep the UI and Elide in agreement about who is a superuser.

4. canManageAnnouncements is admin-only, unlike the other canManage* methods.
Same point as the inline comment: the custom role (which null roles normalise to) can never manage announcements, and nothing in the description says that is deliberate. If it is, please document it. If not, fall back to team.isManagePermission() or similar for custom.

5. The banner tray can take over the viewport.
I checked the CSS diff and there is no max-height or overflow anywhere on the tray, and it lives inside the 100vh; overflow: hidden shell. A long non-dismissible CRITICAL message on a small screen leaves the app unusable. max-height: 40vh; overflow-y: auto on the tray fixes it.

A few smaller things:

  • The 120 character check measures title.trim() but the untrimmed title is persisted, so 118 characters plus trailing spaces gets a 500 at flush instead of a 400.
  • The UI fetches every announcement in the system on each route change and every 60s, then filters client-side. A server-side filter (active==true;(scope==GLOBAL,organization.id==<orgId>)) and no refetch on route change would cut that a lot.
  • useSuperUser caches false on error for the lifetime of the token, so a transient failure hides the nav item from a real superuser until reload.
  • Nits, none blocking: the manual setUpdatedDate in the hook (GenericAuditFields already has @UpdateTimestamp), and the null guard on announcementRepository in SoftDeleteService, which is dead code and would hide a mis-wiring.
  • Tests: the existing ones cover CRUD, isolation, internal tokens and the soft-delete cascade well. Missing are the read-window case from point 1, the trailing-space title, and hard-deleting an organization that has org-scoped announcements (the concern raised on the hook).

Not for this PR: this adds a new API resource, so it would be worth a follow-up issue for terrakube-go, the Terraform provider and the CLI, and a docs page for the new settings screens.

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

@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Nov 29, 2026
@alfespa17

Copy link
Copy Markdown
Member Author

@Macbet (and @jakegroves) — thank you for the thorough review! I have synced feat/announcements-banner with the latest origin/main and addressed all 11 inline comments:

Summary of Fixes

  1. PublicAnnouncementController caching, zero steady-state DB hits, and UUID removal (PublicAnnouncementController.java:28)

    • Added PublicAnnouncementCacheService holding a per-pod in-memory snapshot (30s TTL, immediately evicted via AnnouncementManageHook on POSTCOMMIT CREATE/UPDATE/DELETE) and filtering active schedule windows in memory so steady-state unauthenticated GET /public/v1/announcements executes zero DB queries.
    • Changed Cache-Control from no-store to public, max-age=30.
    • Removed the internal UUID id from PublicAnnouncementDto and replaced it with an opaque SHA-256 key (and updated PublicAnnouncementItem / LoginAnnouncements.tsx to match).
    • Added /public/v1 to docs/single-domain/route-table.yaml (RouteTableDriftTests passes).
  2. Banner tray viewport overflow (AnnouncementBanner.css:2)

    • Added max-height: 40vh; overflow-y: auto; to .announcement-banner-tray so long or expanded multi-banner stacks never collapse .layout on small viewports.
  3. RbacV2Service.canManageAnnouncements(Team) custom/null role handling (RbacV2Service.java:130)

    • Kept organization-scoped announcement management intentionally restricted to role == "admin" (unlike workspace/module/policy permissions, Team does not define a dedicated announcement flag column, so custom and legacy null roles do not grant announcement admin rights). Documented this explicitly in Javadoc and verified with RbacV2ServiceTest.
  4. Hard Organization deletion with org-scoped announcements (AnnouncementManageHook.java:77)

    • Reproduced the Elide inverse-relationship UPDATE PRECOMMIT HTTP 400 failure during DELETE /api/v1/organization/{id}.
    • Added cascade = CascadeType.REMOVE, orphanRemoval = true to Organization.announcement (Organization.java) and verified via AnnouncementTests.hardDeletingOrganizationWithAnnouncementsSucceedsAndDirectNullOrgPatchFails that hard organization deletion now returns 204 No Content and removes the announcements, while a direct PATCH clearing organization on an ORGANIZATION announcement still returns 400 Bad Request.
  5. Draft / future-scheduled / expired visibility (AnnouncementReadCheck.java:43)

    • Restricted non-superusers on GLOBAL announcements and non-admin org members on ORGANIZATION announcements so they can only read currently published records (active == true, startsAt <= now, endsAt > now).
    • Platform superusers and org admins (rbacService.canManageAnnouncements) retain full read access to drafts, future-scheduled, and expired announcements for management screens. Added integration tests in AnnouncementTests.
  6. Avoid caching false on transient errors in useSuperUser (useSuperUser.ts:47)

    • Cleared cached state on request failure instead of caching false for the lifetime of the access token so subsequent mounts/navigations retry, aligned the URL with apiUrl(...), and added unit tests in ui/src/modules/permissions/__tests__/useSuperUser.test.tsx.
  7. Title trimming vs. max length (AnnouncementManageHook.java:53)

    • Validated raw title.length() > 120 cleanly (matching @Size(max = 120) / varchar(120) so oversized trailing whitespace returns 400 Bad Request rather than hitting DB constraint errors) and assigned announcement.setTitle(title.trim()) before persisting.
  8. RSQL filtering, route-change refetching, and background polling (announcementService.ts:94 & AnnouncementContext.tsx)

    • Scoped fetchAnnouncementsForBanner using Elide RSQL (active==true;(scope==GLOBAL,organization.id==<orgId>) or active==true;scope==GLOBAL).
    • Removed the routeKey refetch dependency from AnnouncementProvider so intra-org navigation no longer triggers extra requests.
    • Paused the 60s poll while document.hidden is true and added a visibilitychange listener to refresh on tab return, covered by AnnouncementContext.test.tsx and AnnouncementTests.bannerRsqlFilterReturnsActiveGlobalAndOrgAnnouncements.
  9. TeamTokenController superuser delegation (TeamTokenController.java:179)

    • Injected AuthenticatedUser into TeamTokenController and replaced the duplicated local isSuperUser check with authenticatedUser.isSuperUser(new User(principalJwt)), integrating cleanly with origin/main's mergeOrganizationGrants and adding coverage in TeamTokenControllerTest.
  10. Redundant setUpdatedDate(new Date()) (AnnouncementManageHook.java:40)

    • Removed manual updatedDate assignment on UPDATE, relying on @UpdateTimestamp from GenericAuditFields.
  11. Dead null guard (SoftDeleteService.java:118)

    • Removed if (announcementRepository != null) in disableOrganization.

Verification Re-run After All Fixes & origin/main Merge

  • Backend (mvn test, JDK 25): RbacV2ServiceTest (9/9), SoftDeleteServiceTest (2/2), TeamTokenControllerTest (7/7), AnnouncementTests (14/14), OrganizationTests (9/9), RouteTableDriftTests (2/2), AccessTests (21/21), CrossOrganizationSecurityIntegrationTest (31/31) — 95/95 passing.
  • Frontend (ui): yarn lint:check, yarn format:check, yarn typecheck, CI=true yarn test --watchAll=false (207 passed, 1 pre-existing skipped suite / 1742 tests passed, 1 skipped), and yarn build — all passing.

Could you please take another look when you have a moment, @Macbet?

@Macbet Macbet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
B Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/db-migration Touches Liquibase changelogs area/rbac Touches teams and permissions area/security Touches authentication, tokens or authorization author/maintainer Authored by a maintainer documentation Improvements or additions to documentation priority/high Review soon: high-risk area, bug fix or security update size/XL 1000 or more lines changed, consider splitting terrakube-api terrakube-ui type/feature New functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Platform & Organization-Level Announcement and Scheduled Maintenance Banners

3 participants