Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package io.terrakube.api.plugin.announcement;

import io.terrakube.api.plugin.announcement.PublicAnnouncementController.PublicAnnouncementDto;
import io.terrakube.api.repository.AnnouncementRepository;
import io.terrakube.api.rs.announcement.Announcement;
import io.terrakube.api.rs.announcement.AnnouncementSeverity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;

/**
* Per-pod in-memory cache for active login-screen global announcements so steady-state
* unauthenticated traffic to {@code /public/v1/announcements} avoids hitting the database
* and does not expose internal announcement UUIDs.
*/
@Service
@RequiredArgsConstructor
public class PublicAnnouncementCacheService {

static final Duration CACHE_TTL = Duration.ofSeconds(30);

private final AnnouncementRepository announcementRepository;

private volatile CachedSnapshot cachedSnapshot;

Check warning on line 33 in api/src/main/java/io/terrakube/api/plugin/announcement/PublicAnnouncementCacheService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use a thread-safe type; adding "volatile" is not enough to make this field thread-safe.

See more on https://sonarcloud.io/project/issues?id=AzBuilder_azb-server&issues=AaIov2vxvcVldxuqYCV8&open=AaIov2vxvcVldxuqYCV8&pullRequest=4004

public List<PublicAnnouncementDto> getActiveLoginAnnouncements(Instant now) {
CachedSnapshot snapshot = getOrRefreshSnapshot();
Date nowDate = Date.from(now);
return snapshot.entries().stream()
.filter(entry -> isWithinScheduleWindow(entry, nowDate))
.map(entry -> new PublicAnnouncementDto(
entry.key(),
entry.title(),
entry.message(),
entry.severity(),
entry.startsAt(),
entry.endsAt(),
entry.updatedDate()))
.toList();
}

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.

}

private CachedSnapshot getOrRefreshSnapshot() {
CachedSnapshot current = cachedSnapshot;
Instant now = Instant.now();
if (current != null && now.isBefore(current.loadedAt().plus(CACHE_TTL))) {
return current;
}
synchronized (this) {
current = cachedSnapshot;
now = Instant.now();
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.

.map(CachedEntry::from)
.toList();
CachedSnapshot refreshed = new CachedSnapshot(now, entries);
cachedSnapshot = refreshed;
return refreshed;
}
}

private static boolean isWithinScheduleWindow(CachedEntry entry, Date now) {
if (entry.startsAt() != null && entry.startsAt().after(now)) {
return false;
}
return entry.endsAt() == null || entry.endsAt().after(now);
}

private static String computeOpaqueKey(UUID id, Date updatedDate) {

Check warning on line 83 in api/src/main/java/io/terrakube/api/plugin/announcement/PublicAnnouncementCacheService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Move this method into "CachedEntry".

See more on https://sonarcloud.io/project/issues?id=AzBuilder_azb-server&issues=AaIov2vxvcVldxuqYCV9&open=AaIov2vxvcVldxuqYCV9&pullRequest=4004
String raw = id + ":" + (updatedDate != null ? updatedDate.getTime() : 0L);
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(raw.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(hash);
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("SHA-256 unavailable", ex);
}
}

private record CachedSnapshot(Instant loadedAt, List<CachedEntry> entries) {}

private record CachedEntry(
String key,
String title,
String message,
AnnouncementSeverity severity,
Date startsAt,
Date endsAt,
Date updatedDate) {

static CachedEntry from(Announcement announcement) {
return new CachedEntry(
computeOpaqueKey(announcement.getId(), announcement.getUpdatedDate()),
announcement.getTitle(),
announcement.getMessage(),
announcement.getSeverity(),
announcement.getStartsAt(),
announcement.getEndsAt(),
announcement.getUpdatedDate());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.terrakube.api.plugin.announcement;

import io.terrakube.api.rs.announcement.AnnouncementSeverity;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/public/v1/announcements")
@RequiredArgsConstructor
public class PublicAnnouncementController {

private final PublicAnnouncementCacheService publicAnnouncementCacheService;

@GetMapping
public ResponseEntity<PublicAnnouncementsResponse> getActiveLoginAnnouncements() {
Instant now = Instant.now();
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.

.header(ServerTimeResponseFilter.SERVER_TIME_HEADER, now.toString())
.body(new PublicAnnouncementsResponse(now, announcements));
}

public record PublicAnnouncementsResponse(Instant serverTime, List<PublicAnnouncementDto> announcements) {}

public record PublicAnnouncementDto(
String key,
String title,
String message,
AnnouncementSeverity severity,
Date startsAt,
Date endsAt,
Date updatedDate) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.terrakube.api.plugin.announcement;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.time.Instant;

@Component
public class ServerTimeResponseFilter extends OncePerRequestFilter {

public static final String SERVER_TIME_HEADER = "X-Server-Time";

@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri != null
&& (uri.contains("/api/v1/announcement")
|| uri.contains("/graphql/api/v1")
|| uri.contains("/public/v1/announcements"))) {
response.setHeader(SERVER_TIME_HEADER, Instant.now().toString());
}
filterChain.doFilter(request, response);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.terrakube.api.plugin.security.authentication.dex;

import io.terrakube.api.plugin.announcement.ServerTimeResponseFilter;
import io.terrakube.api.plugin.logs.StepLogResponses;
import io.terrakube.api.plugin.token.login.TerraformLoginProperties;
import io.terrakube.api.repository.FederatedRepository;
Expand Down Expand Up @@ -121,6 +122,7 @@ public SecurityFilterChain filterChain(HttpSecurity http,
.requestMatchers("/subscriptions").permitAll()
.requestMatchers("/tofu/index.json").permitAll()
.requestMatchers("/terraform/index.json").permitAll()
.requestMatchers(HttpMethod.GET, "/public/v1/announcements").permitAll()
.anyRequest().authenticated();
})
.oauth2ResourceServer(oauth2 -> {
Expand Down Expand Up @@ -164,8 +166,11 @@ CorsConfigurationSource corsConfigurationSource(
"Origin", "Cache-Control",
"Content-Type", "Accept", "Authorization", "X-TFC-Token", "X-TFC-Url"));
configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT", "OPTIONS"));
// The UI reads this header to tell that a step log is only the part that was saved.
configuration.setExposedHeaders(List.of(StepLogResponses.INCOMPLETE_HEADER));
// The UI reads this header to tell that a step log is only the part that was saved,
// and X-Server-Time for announcement schedule windows.
configuration.setExposedHeaders(List.of(
StepLogResponses.INCOMPLETE_HEADER,
ServerTimeResponseFilter.SERVER_TIME_HEADER));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public interface RbacService {

boolean canManagePolicies(Team team);

boolean canManageAnnouncements(Team team);

/**
* Whether the team can create/queue jobs (plans).
* Maps to planJob flag or role-derived permission (admin/write/plan roles).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,16 @@ public boolean canManagePolicies(Team team) {
};
}

/**
* Organization-scoped announcement management is intentionally restricted to teams with the
* {@code admin} role. Unlike workspace/module/policy permissions, {@link Team} does not define a
* dedicated announcement flag column, so {@code custom} (and legacy null) roles are excluded.
*/
@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.

}

@Override
public boolean canPlanJob(Team team) {
String role = normalizeRole(team.getRole());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import io.terrakube.api.plugin.scheduler.JobStatusChangeService;
import io.terrakube.api.plugin.scheduler.ScheduleJobService;
import io.terrakube.api.plugin.scheduler.workspace.DeleteStorageBackendJob;
import io.terrakube.api.repository.AnnouncementRepository;
import io.terrakube.api.repository.JobRepository;
import io.terrakube.api.repository.ScheduleRepository;
import io.terrakube.api.repository.WorkspaceRepository;
Expand Down Expand Up @@ -38,6 +39,8 @@ public class SoftDeleteService {

JobStatusChangeService jobStatusChangeService;

AnnouncementRepository announcementRepository;

public void disableWorkspaceSchedules(Workspace workspace){
for(Schedule schedule: workspace.getSchedule()){
try {
Expand Down Expand Up @@ -112,6 +115,8 @@ public void deleteWorkspaceStorage(Workspace workspace){
public void disableOrganization(Organization organization){
log.info("Disable Organization Id: {}", organization.getId().toString());

announcementRepository.deleteByOrganizationId(organization.getId().toString());

for(Workspace workspace: organization.getWorkspace()){
log.info("Disable Workspace: {}", workspace.getId().toString());
disableWorkspaceSchedules(workspace);
Expand Down
Loading
Loading