Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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,27 @@
package io.jenkins.plugins.casc;

import hudson.ExtensionList;
import hudson.ExtensionPoint;
import java.util.logging.Level;
import java.util.logging.Logger;

public interface CasCReloadListener extends ExtensionPoint {

void onConfigurationReloaded();

static void fire() {
Logger logger = Logger.getLogger(CasCReloadListener.class.getName());

for (CasCReloadListener listener : ExtensionList.lookup(CasCReloadListener.class)) {
try {
listener.onConfigurationReloaded();
} catch (Exception e) {
logger.log(
Level.WARNING,
"Listener " + listener.getClass().getName()
+ " threw an exception during CasC reload notification",
e);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -754,9 +754,9 @@ public void configureWith(YamlSource source) throws ConfiguratorException {
}

private void configureWith(List<YamlSource> sources) throws ConfiguratorException {
lastTimeLoaded = System.currentTimeMillis();
ConfigurationContext context = new ConfigurationContext(registry);
configureWith(YamlUtils.loadFrom(sources, context), context);
lastTimeLoaded = System.currentTimeMillis();
}

@Restricted(NoExternalUse.class)
Expand Down Expand Up @@ -886,6 +886,7 @@ private void configureWith(Mapping entries, ConfigurationContext context) throws
try (ACLContext acl = ACL.as2(ACL.SYSTEM2)) {
invokeWith(entries, (configurator, config) -> configurator.configure(config, context));
}
CasCReloadListener.fire();
}

public Map<Source, String> checkWith(Mapping entries, ConfigurationContext context) throws ConfiguratorException {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package io.jenkins.plugins.casc.history;

import hudson.Extension;
import hudson.model.ManagementLink;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse2;
import org.springframework.lang.NonNull;
import org.w3c.dom.Document;

@Extension
public class CasCHistoryAction extends ManagementLink {

private static final Logger LOGGER = Logger.getLogger(CasCHistoryAction.class.getName());

@Override
public String getIconFileName() {
return "symbol-time";
}

@Override
public String getDisplayName() {
return "CasC History";
}

@Override
public String getUrlName() {
return "casc-history";
}

@Override
public String getDescription() {
return "Browse CasC history and snapshots.";
}

public List<HistoryEntry> getHistoryEntries() {
List<HistoryEntry> entries = new ArrayList<>();
File baseDir = new File(Jenkins.get().getRootDir(), "casc-history");

if (baseDir.exists() && baseDir.isDirectory()) {
File[] historyFolders = baseDir.listFiles(File::isDirectory);
if (historyFolders != null) {
Arrays.sort(historyFolders, Comparator.comparing(File::getName).reversed());

for (File folder : historyFolders) {
entries.add(new HistoryEntry(folder.getName(), parseUserFromXml(folder)));
}
}
}
return entries;
}

private String parseUserFromXml(File folder) {
File xmlFile = new File(folder, "history.xml");
if (xmlFile.exists()) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);

return doc.getElementsByTagName("user").item(0).getTextContent();
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to read history.xml in " + folder.getName(), e);
}
}
return "Unknown User";
}

public record HistoryEntry(String timestamp, String user) {

@SuppressWarnings("unused")
public String getFormattedTimestamp() {
LocalDateTime dt = LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"));

return dt.format(DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm:ss"));
}
}

@SuppressWarnings("unused")
public void doView(StaplerRequest2 req, StaplerResponse2 res) throws IOException {

Check warning

Code scanning / Jenkins Security Scan

Stapler: Missing POST/RequirePOST annotation Warning

Potential CSRF vulnerability: If CasCHistoryAction#doView connects to user-specified URLs, modifies state, or is expensive to run, it should be annotated with @POST or @RequirePOST
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
Jenkins.get().checkPermission(Jenkins.ADMINISTER);

String timestamp = req.getParameter("timestamp");
if (timestamp == null || timestamp.isEmpty()) {
res.sendError(400, "Missing timestamp parameter");
return;
}

if (!timestamp.matches("^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}-[0-9]{2}(_[0-9]+)?$")) {
res.sendError(400, "Invalid timestamp format");
return;
}

File baseDir = new File(Jenkins.get().getRootDir(), "casc-history");
File historyDir = new File(baseDir, timestamp);
File yamlFile = new File(historyDir, "jenkins.yaml");

if (!yamlFile.exists()) {
res.sendError(404, "History record not found");
return;
}

res.setContentType("text/plain;charset=UTF-8");
Files.copy(yamlFile.toPath(), res.getOutputStream());
}

@Override
@NonNull
public Category getCategory() {
return Category.CONFIGURATION;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package io.jenkins.plugins.casc.history;

import hudson.ExtensionPoint;
import java.io.IOException;

public abstract class CasCHistoryBackend implements ExtensionPoint {

public abstract void save(String yamlContent, String triggeredBy) throws IOException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.jenkins.plugins.casc.history;

import hudson.Extension;
import hudson.ExtensionList;
import io.jenkins.plugins.casc.CasCReloadListener;
import io.jenkins.plugins.casc.ConfigurationAsCode;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.util.Timer;
import org.springframework.security.core.Authentication;

@Extension
@SuppressWarnings("unused")
public class CasCHistoryRecorder implements CasCReloadListener {

private static final Logger LOGGER = Logger.getLogger(CasCHistoryRecorder.class.getName());

@Override
public void onConfigurationReloaded() {
LOGGER.fine("CasC reload detected. Queuing async capture of current YAML state...");

final Authentication auth = Jenkins.getAuthentication2();
final String triggeredBy = auth.getName();

Timer.get().submit(() -> {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ConfigurationAsCode.get().export(out);
String currentYaml = out.toString(StandardCharsets.UTF_8);

CasCHistoryBackend backend = ExtensionList.lookupFirst(CasCHistoryBackend.class);
backend.save(currentYaml, triggeredBy);

} catch (Exception e) {
LOGGER.log(Level.WARNING, "Failed to capture CasC history asynchronously", e);
}
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package io.jenkins.plugins.casc.history;

import static org.apache.commons.lang.StringEscapeUtils.escapeXml;

import hudson.Extension;
import hudson.Util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;

@Extension
public class LocalFileHistoryBackend extends CasCHistoryBackend {
private static final Logger LOGGER = Logger.getLogger(LocalFileHistoryBackend.class.getName());
private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd_HH-mm-ss";
private static final int MAX_HISTORY_ENTRIES = 50;
private final Object writeLock = new Object();

@Override
public void save(String yamlContent, String triggeredBy) throws IOException {
File jenkinsHome = Jenkins.get().getRootDir();
File baseHistoryDir = new File(jenkinsHome, "casc-history");

synchronized (writeLock) {
if (!baseHistoryDir.mkdirs() && !baseHistoryDir.exists()) {
throw new IOException("Failed to create base history directory: " + baseHistoryDir.getAbsolutePath());
}

String timestamp = getCurrentTimestamp();
File specificHistoryDir = new File(baseHistoryDir, timestamp);

int counter = 1;
while (specificHistoryDir.exists()) {
specificHistoryDir = new File(baseHistoryDir, timestamp + "_" + counter);
counter++;
}

if (!specificHistoryDir.mkdirs()) {
throw new IOException(
"Failed to create specific history directory: " + specificHistoryDir.getAbsolutePath());
}

Path yamlFile = new File(specificHistoryDir, "jenkins.yaml").toPath();
Files.writeString(yamlFile, yamlContent);

String xmlMetadata = String.format(
"<?xml version='1.1' encoding='UTF-8'?>%n" + "<history>%n"
+ " <user>%s</user>%n"
+ " <timestamp>%s</timestamp>%n"
+ "</history>",
escapeXml(triggeredBy), timestamp);
Path metadataFile = new File(specificHistoryDir, "history.xml").toPath();
Files.writeString(metadataFile, xmlMetadata);

LOGGER.info("CasC history successfully saved at: " + specificHistoryDir.getAbsolutePath());

cleanupOldHistory(baseHistoryDir);
}
}

private void cleanupOldHistory(File baseHistoryDir) {
File[] historyFolders = baseHistoryDir.listFiles(File::isDirectory);

if (historyFolders != null && historyFolders.length > MAX_HISTORY_ENTRIES) {
Arrays.sort(historyFolders, Comparator.comparing(File::getName));
int directoriesToDelete = historyFolders.length - MAX_HISTORY_ENTRIES;

for (int i = 0; i < directoriesToDelete; i++) {
File folderToDelete = historyFolders[i];
LOGGER.fine("Deleting old CasC history entry: " + folderToDelete.getName());
try {
Util.deleteRecursive(folderToDelete);
} catch (IOException e) {
LOGGER.log(
Level.WARNING,
"Failed to delete old CasC history folder: " + folderToDelete.getAbsolutePath(),
e);
}
}
}
}

String getCurrentTimestamp() {
return new SimpleDateFormat(TIMESTAMP_FORMAT).format(new Date());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:l="/lib/layout">
<l:layout title="CasC Configuration History" permission="${app.ADMINISTER}">

<l:main-panel>
<h1>CasC Configuration History</h1>
<p> Browse the history of CasC changes and view the resulting configuration snapshots</p>

<table class="jenkins-table sortable">
<thead>
<tr>
<th class="jenkins-table__cell--tight">Timestamp</th>
<th>User</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<j:forEach var="entry" items="${it.historyEntries}">
<tr>
<td>${entry.formattedTimestamp}</td>
<td>${entry.user()}</td>
<td>
<a href="view?timestamp=${entry.timestamp()}"
class="jenkins-button jenkins-button--tertiary">
View YAML
</a>
</td>
</tr>
</j:forEach>
</tbody>
</table>

<j:if test="${empty(it.historyEntries)}">
<p class="jenkins-!-margin-top-3">No history found. Try reloading your configuration first!</p>
</j:if>

</l:main-panel>
</l:layout>
</j:jelly>
Loading
Loading