Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc9b4c2e6f | ||
|
|
6f6243688d | ||
|
|
425b65e6b2 | ||
|
|
649fd5407c | ||
|
|
2b118556f3 | ||
|
|
fbaff56d1c | ||
|
|
38ccea074c | ||
|
|
a7307ff393 | ||
|
|
72729e99c1 | ||
|
|
5fba2720f0 | ||
|
|
01a1ef8c44 | ||
|
|
8535c7e9ac | ||
|
|
cca3f42623 | ||
|
|
1b7ffcdbac | ||
|
|
67a0ca6110 | ||
|
|
8e4b2e2fc6 | ||
|
|
3c93457021 |
@@ -1,6 +1,6 @@
|
||||
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
|
||||
pkgname=stirling-pdf-desktop
|
||||
pkgver=2.14.1
|
||||
pkgver=2.14.2
|
||||
pkgrel=1
|
||||
pkgdesc="Locally hosted, web-based PDF manipulation tool (Tauri desktop app, official Stirling PDF Inc build)"
|
||||
arch=('x86_64')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
|
||||
pkgname=stirling-pdf-server-bin
|
||||
pkgver=2.14.1
|
||||
pkgver=2.14.2
|
||||
pkgrel=1
|
||||
pkgdesc="Locally hosted, web-based PDF manipulation tool (server JAR, prebuilt)"
|
||||
arch=('any')
|
||||
|
||||
@@ -510,6 +510,7 @@ jobs:
|
||||
# cargo output unsigned, so checking it produces false negatives.
|
||||
- name: Verify Windows Code Signature
|
||||
if: ${{ matrix.platform == 'windows-latest' && env.SM_API_KEY != '' && (github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.sign != 'false') || github.ref == 'refs/heads/V2-master') }}
|
||||
timeout-minutes: 15
|
||||
shell: pwsh
|
||||
run: |
|
||||
$allSigned = $true
|
||||
@@ -531,11 +532,26 @@ jobs:
|
||||
|
||||
# Extract MSI and verify the inner exe (the file that actually gets installed).
|
||||
# This is the critical check - AV flags the installed exe at runtime.
|
||||
# Use lessmsi, not `msiexec /a`: msiexec serializes on the global
|
||||
# _MSIExecute mutex and hangs forever on hosted runners when another
|
||||
# installer is busy. lessmsi reads MSI tables directly - no mutex, no service.
|
||||
$msi = $msiFiles[0].FullName
|
||||
$extractDir = Join-Path $env:RUNNER_TEMP "msi-verify"
|
||||
if (Test-Path $extractDir) { Remove-Item $extractDir -Recurse -Force }
|
||||
$proc = Start-Process msiexec.exe -ArgumentList '/a', $msi, '/qn', "TARGETDIR=$extractDir" -Wait -PassThru -NoNewWindow
|
||||
if ($proc.ExitCode -eq 0) {
|
||||
New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
|
||||
|
||||
choco install lessmsi -y --no-progress --limit-output | Out-Null
|
||||
|
||||
# Bound the extraction and kill on hang (defence in depth over timeout-minutes).
|
||||
$proc = Start-Process lessmsi -ArgumentList 'x', "`"$msi`"", "`"$extractDir\`"" -PassThru -NoNewWindow
|
||||
if (-not $proc.WaitForExit(120000)) {
|
||||
try { $proc.Kill() } catch {}
|
||||
Write-Host "[ERROR] MSI extraction timed out after 120s"
|
||||
$allSigned = $false
|
||||
} elseif ($proc.ExitCode -ne 0) {
|
||||
Write-Host "[ERROR] Failed to extract MSI for verification (exit code: $($proc.ExitCode))"
|
||||
$allSigned = $false
|
||||
} else {
|
||||
$innerExe = Get-ChildItem -Path $extractDir -Filter "stirling-pdf.exe" -Recurse -File | Select-Object -First 1
|
||||
if ($innerExe) {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $innerExe.FullName
|
||||
@@ -548,9 +564,6 @@ jobs:
|
||||
Write-Host "[ERROR] Could not find stirling-pdf.exe inside MSI"
|
||||
$allSigned = $false
|
||||
}
|
||||
} else {
|
||||
Write-Host "[ERROR] Failed to extract MSI for verification (exit code: $($proc.ExitCode))"
|
||||
$allSigned = $false
|
||||
}
|
||||
|
||||
if (-not $allSigned) {
|
||||
@@ -800,7 +813,11 @@ jobs:
|
||||
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
|
||||
with:
|
||||
tag_name: v${{ needs.determine-matrix.outputs.version }}
|
||||
generate_release_notes: true
|
||||
# Don't regenerate/append notes on re-runs, and don't force this into the
|
||||
# "Latest" slot - leave the release body and latest marker as they are.
|
||||
generate_release_notes: false
|
||||
append_body: false
|
||||
make_latest: false
|
||||
fail_on_unmatched_files: true
|
||||
# Installers + updater payloads + manifest. .sig contents are embedded
|
||||
# in latest.json so the .sig files themselves are not uploaded.
|
||||
|
||||
+1
-16
@@ -78,16 +78,6 @@ tasks:
|
||||
cmds:
|
||||
- npx tauri build --bundles nsis --config '{"bundle":{"createUpdaterArtifacts":false}}'
|
||||
|
||||
build:msi:
|
||||
desc: "Build Tauri desktop MSI installer with bundled JRE (Windows)"
|
||||
deps: [prepare]
|
||||
dir: editor
|
||||
platforms: [windows]
|
||||
cmds:
|
||||
# prepare -> jlink (real bundled JRE) + jar + frontend + provisioner.
|
||||
# No updater artifacts, so no signing key is required for a local MSI.
|
||||
- npx tauri build --bundles msi --config '{"bundle":{"createUpdaterArtifacts":false}}'
|
||||
|
||||
build:dev:linux:
|
||||
desc: "Build Tauri desktop AppImage (Linux)"
|
||||
deps: [prepare]
|
||||
@@ -204,12 +194,7 @@ tasks:
|
||||
# `desktop:build` run `jlink:clean` first to force a fresh build.
|
||||
- cmd: chmod -R u+w runtime/jre
|
||||
platforms: [linux, darwin]
|
||||
# Single-quote the PowerShell so go-task's POSIX shell passes $_ and $false
|
||||
# through literally. With double quotes it expands $_ to the task path and
|
||||
# $false to empty, so read-only never clears and the next incremental build
|
||||
# dies with "Permission denied (os error 13)" staging the JRE. -File keeps
|
||||
# it to FileInfo (only files carry a settable IsReadOnly).
|
||||
- cmd: powershell -NoProfile -Command 'Get-ChildItem -Recurse -Force -File runtime/jre | ForEach-Object { $_.IsReadOnly = $false }'
|
||||
- cmd: powershell -NoProfile -Command "Get-ChildItem -Recurse runtime/jre | ForEach-Object { $_.IsReadOnly = $false }"
|
||||
platforms: [windows]
|
||||
status:
|
||||
- test -f runtime/jre/release
|
||||
|
||||
@@ -4,6 +4,8 @@ import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
@@ -47,6 +49,9 @@ public class JobResult {
|
||||
*/
|
||||
private final List<String> notes = new CopyOnWriteArrayList<>();
|
||||
|
||||
/** Key/value metadata that survives the write-through into the shared job store. */
|
||||
private final Map<String, String> metadata = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Create a new JobResult with the given job ID
|
||||
*
|
||||
@@ -161,4 +166,16 @@ public class JobResult {
|
||||
public List<String> getNotes() {
|
||||
return Collections.unmodifiableList(notes);
|
||||
}
|
||||
|
||||
/** Attach a metadata value, e.g. a policy id so cluster peers can identify a policy run. */
|
||||
public void putMetadata(String key, String value) {
|
||||
if (key != null && value != null) {
|
||||
this.metadata.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
/** An unmodifiable view of this job's metadata. */
|
||||
public Map<String, String> getMetadata() {
|
||||
return Collections.unmodifiableMap(metadata);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,6 +230,18 @@ public class TaskManager {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Attach metadata to a job and write it through to the shared store for cluster peers. */
|
||||
public boolean putMetadata(String jobId, String key, String value) {
|
||||
JobResult jobResult = jobResults.get(jobId);
|
||||
if (jobResult != null) {
|
||||
jobResult.putMetadata(key, value);
|
||||
writeThrough(jobId, jobResult);
|
||||
return true;
|
||||
}
|
||||
log.warn("Attempted to set metadata on non-existent job ID: {}", jobId);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get statistics about all jobs in the system
|
||||
*
|
||||
@@ -378,7 +390,7 @@ public class TaskManager {
|
||||
fileIds.add(rf.getFileId());
|
||||
}
|
||||
}
|
||||
Map<String, String> meta = new HashMap<>();
|
||||
Map<String, String> meta = new HashMap<>(result.getMetadata());
|
||||
if (result.getNotes() != null && !result.getNotes().isEmpty()) {
|
||||
meta.put("notesCount", Integer.toString(result.getNotes().size()));
|
||||
}
|
||||
|
||||
@@ -96,7 +96,8 @@ spring.main.allow-bean-definition-overriding=true
|
||||
# spring-data-redis is on the classpath only for the optional Valkey backplane (which wires its own
|
||||
# factory); exclude Spring Boot's stock Redis auto-config so a default install doesn't create a dead
|
||||
# localhost:6379 factory that flips /actuator/health to DOWN.
|
||||
spring.autoconfigure.exclude=org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration,org.springframework.boot.data.redis.autoconfigure.DataRedisReactiveAutoConfiguration
|
||||
# Also exclude the repositories auto-config: in cluster mode it needs a redisTemplate bean we don't define.
|
||||
spring.autoconfigure.exclude=org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration,org.springframework.boot.data.redis.autoconfigure.DataRedisReactiveAutoConfiguration,org.springframework.boot.data.redis.autoconfigure.DataRedisRepositoriesAutoConfiguration
|
||||
|
||||
# Set up a consistent temporary directory location
|
||||
java.io.tmpdir=${stirling.tempfiles.directory:${java.io.tmpdir}/stirling-pdf}
|
||||
|
||||
+12
-1
@@ -44,10 +44,13 @@ public class CredentialEncryption {
|
||||
private static volatile SecretKey key;
|
||||
|
||||
private final String configuredKey;
|
||||
private final boolean clusterEnabled;
|
||||
|
||||
public CredentialEncryption(
|
||||
@Value("${stirling.security.credentialEncryptionKey:}") String configuredKey) {
|
||||
@Value("${stirling.security.credentialEncryptionKey:}") String configuredKey,
|
||||
@Value("${cluster.enabled:false}") boolean clusterEnabled) {
|
||||
this.configuredKey = configuredKey;
|
||||
this.clusterEnabled = clusterEnabled;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -64,6 +67,14 @@ public class CredentialEncryption {
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
return new SecretKeySpec(Base64.getDecoder().decode(configured.trim()), ALGORITHM);
|
||||
}
|
||||
// Cluster nodes must share this key, so fail fast rather than generate a node-local one.
|
||||
if (clusterEnabled) {
|
||||
throw new IllegalStateException(
|
||||
"cluster.enabled=true requires a shared credential encryption key. Set"
|
||||
+ " STIRLING_CREDENTIAL_ENCRYPTION_KEY (or"
|
||||
+ " stirling.security.credentialEncryptionKey) to the same value on every"
|
||||
+ " node.");
|
||||
}
|
||||
return loadOrCreateKeyFile();
|
||||
}
|
||||
|
||||
|
||||
+35
-6
@@ -6,6 +6,7 @@ import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
@@ -40,6 +41,8 @@ import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.cluster.JobStore;
|
||||
import stirling.software.common.cluster.JobStoreEntry;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.job.JobResponse;
|
||||
import stirling.software.common.service.JobOwnershipService;
|
||||
@@ -104,6 +107,8 @@ public class PolicyController {
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final TempFileManager tempFileManager;
|
||||
private final JobOwnershipService jobOwnershipService;
|
||||
// Shared job store: lets the run endpoints see runs that executed on other nodes.
|
||||
private final JobStore jobStore;
|
||||
|
||||
@PostMapping(value = "/run", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@Operation(
|
||||
@@ -174,10 +179,19 @@ public class PolicyController {
|
||||
description = "Returns the current status, step cursor, and output files of a run.")
|
||||
public ResponseEntity<PolicyRunView> status(@PathVariable String runId) {
|
||||
PolicyRun run = runRegistry.get(runId);
|
||||
if (run == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
if (run != null) {
|
||||
return ResponseEntity.ok(PolicyRunView.of(run));
|
||||
}
|
||||
return ResponseEntity.ok(PolicyRunView.of(run));
|
||||
// Not local: read the run's shared projection so any node can serve its status.
|
||||
if (ownedByCurrentUser(runId)) {
|
||||
Optional<JobStoreEntry> entry = jobStore.get(runId);
|
||||
if (entry.isPresent()
|
||||
&& entry.get().resultMeta() != null
|
||||
&& entry.get().resultMeta().containsKey("policyId")) {
|
||||
return ResponseEntity.ok(PolicyRunView.ofEntry(entry.get()));
|
||||
}
|
||||
}
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
@GetMapping("/runs")
|
||||
@@ -190,11 +204,26 @@ public class PolicyController {
|
||||
+ " collected, rather than orphaned on the backend. Ad-hoc runs (no"
|
||||
+ " policy id) are excluded.")
|
||||
public List<PolicyRunView> listRuns() {
|
||||
return runRegistry.all().stream()
|
||||
// Local runs first (they carry live step state); keyed by runId to dedupe shared entries.
|
||||
Map<String, PolicyRunView> byRunId = new LinkedHashMap<>();
|
||||
runRegistry.all().stream()
|
||||
.filter(run -> run.getPolicyId() != null)
|
||||
.filter(run -> ownedByCurrentUser(run.getRunId()))
|
||||
.map(PolicyRunView::of)
|
||||
.toList();
|
||||
.forEach(run -> byRunId.put(run.getRunId(), PolicyRunView.of(run)));
|
||||
// Then runs from other nodes, read from the shared job store.
|
||||
for (JobStoreEntry entry : jobStore.all()) {
|
||||
if (byRunId.containsKey(entry.jobId())) {
|
||||
continue;
|
||||
}
|
||||
Map<String, String> meta = entry.resultMeta();
|
||||
if (meta == null || !meta.containsKey("policyId")) {
|
||||
continue; // ad-hoc job, not a stored-policy run
|
||||
}
|
||||
if (ownedByCurrentUser(entry.jobId())) {
|
||||
byRunId.put(entry.jobId(), PolicyRunView.ofEntry(entry));
|
||||
}
|
||||
}
|
||||
return List.copyOf(byRunId.values());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+4
@@ -136,6 +136,10 @@ public class PolicyEngine {
|
||||
// ownership check passes. No-op when security is off.
|
||||
String runId = jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString());
|
||||
taskManager.createTask(runId);
|
||||
// Tag the shared job entry with the policy id so peers can list it as a policy run.
|
||||
if (policyId != null) {
|
||||
taskManager.putMetadata(runId, "policyId", policyId);
|
||||
}
|
||||
PolicyRun run = new PolicyRun(runId, policyId, definition);
|
||||
registry.register(run);
|
||||
CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
|
||||
|
||||
+31
@@ -1,7 +1,9 @@
|
||||
package stirling.software.proprietary.policy.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import stirling.software.common.cluster.JobStoreEntry;
|
||||
import stirling.software.common.model.job.ResultFile;
|
||||
|
||||
/**
|
||||
@@ -34,4 +36,33 @@ public record PolicyRunView(
|
||||
run.getOutputs(),
|
||||
run.getCreatedAt().toEpochMilli());
|
||||
}
|
||||
|
||||
/** Cross-node view from a shared job-store entry; step cursor is node-local so it reads 0. */
|
||||
public static PolicyRunView ofEntry(JobStoreEntry entry) {
|
||||
Map<String, String> meta = entry.resultMeta() == null ? Map.of() : entry.resultMeta();
|
||||
PolicyRunStatus status =
|
||||
switch (entry.state()) {
|
||||
case COMPLETE -> PolicyRunStatus.COMPLETED;
|
||||
case FAILED -> PolicyRunStatus.FAILED;
|
||||
case RUNNING, PENDING -> PolicyRunStatus.RUNNING;
|
||||
};
|
||||
List<ResultFile> outputs =
|
||||
entry.fileIds() == null
|
||||
? List.of()
|
||||
: entry.fileIds().stream()
|
||||
.map(id -> ResultFile.builder().fileId(id).build())
|
||||
.toList();
|
||||
long createdAt = entry.createdAt() == null ? 0L : entry.createdAt().toEpochMilli();
|
||||
return new PolicyRunView(
|
||||
entry.jobId(),
|
||||
meta.get("policyId"),
|
||||
status,
|
||||
0,
|
||||
0,
|
||||
entry.error(),
|
||||
null,
|
||||
null,
|
||||
outputs,
|
||||
createdAt);
|
||||
}
|
||||
}
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package stirling.software.proprietary.security.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Convert;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import stirling.software.proprietary.integration.crypto.EncryptedStringConverter;
|
||||
|
||||
/** A JWT signing keypair in the shared DB; the private key is encrypted at rest. */
|
||||
@Entity
|
||||
@Table(name = "jwt_signing_keys")
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class JwtSigningKeyEntity implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@Column(name = "key_id", length = 128)
|
||||
private String keyId;
|
||||
|
||||
// Base64 X.509 public key (non-secret).
|
||||
@Column(name = "verifying_key", columnDefinition = "text", nullable = false)
|
||||
private String verifyingKey;
|
||||
|
||||
// Base64 PKCS#8 private key, encrypted at rest.
|
||||
@Convert(converter = EncryptedStringConverter.class)
|
||||
@Column(name = "signing_key", columnDefinition = "text", nullable = false)
|
||||
private String signingKey;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
public JwtSigningKeyEntity(String keyId, String verifyingKey, String signingKey) {
|
||||
this.keyId = keyId;
|
||||
this.verifyingKey = verifyingKey;
|
||||
this.signingKey = signingKey;
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,6 @@ public class User implements UserDetails, Serializable {
|
||||
|
||||
@ElementCollection
|
||||
@MapKeyColumn(name = "setting_key")
|
||||
@Lob
|
||||
@Column(name = "setting_value", columnDefinition = "text")
|
||||
@CollectionTable(name = "user_settings", joinColumns = @JoinColumn(name = "user_id"))
|
||||
@JsonIgnore
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package stirling.software.proprietary.security.repository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import stirling.software.proprietary.security.model.JwtSigningKeyEntity;
|
||||
|
||||
/** Shared-DB store of JWT signing keys - the source of truth every cluster node reads from. */
|
||||
@Repository
|
||||
public interface JwtSigningKeyRepository extends JpaRepository<JwtSigningKeyEntity, String> {
|
||||
|
||||
/** Newest first, so the most recently created key is the active signing key. */
|
||||
List<JwtSigningKeyEntity> findAllByOrderByCreatedAtDesc();
|
||||
|
||||
/**
|
||||
* The current active signing key: the single newest row. Used for cheap cluster convergence.
|
||||
*/
|
||||
Optional<JwtSigningKeyEntity> findFirstByOrderByCreatedAtDesc();
|
||||
|
||||
/** Keys created before the cutoff, eligible for rotation cleanup. */
|
||||
List<JwtSigningKeyEntity> findByCreatedAtBefore(LocalDateTime cutoff);
|
||||
}
|
||||
+34
-1
@@ -3,8 +3,10 @@ package stirling.software.proprietary.security.service;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -17,6 +19,8 @@ import jakarta.annotation.PostConstruct;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.cluster.DistributedLock;
|
||||
import stirling.software.common.cluster.DistributedLock.LockHandle;
|
||||
import stirling.software.common.configuration.InstallationPathConfig;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.security.model.JwtVerificationKey;
|
||||
@@ -26,15 +30,23 @@ import stirling.software.proprietary.security.model.JwtVerificationKey;
|
||||
@ConditionalOnBooleanProperty("v2")
|
||||
public class KeyPairCleanupService {
|
||||
|
||||
// Cluster-wide single-writer: keys live in the shared DB, so only one node may prune + rotate
|
||||
// per cycle. Otherwise every node runs this and they race to delete each other's keys.
|
||||
private static final String CLEANUP_LOCK = "jwt-key-cleanup";
|
||||
private static final Duration LOCK_LEASE = Duration.ofMinutes(5);
|
||||
|
||||
private final KeyPersistenceService keyPersistenceService;
|
||||
private final ApplicationProperties.Security.Jwt jwtProperties;
|
||||
private final DistributedLock distributedLock;
|
||||
|
||||
@Autowired
|
||||
public KeyPairCleanupService(
|
||||
KeyPersistenceService keyPersistenceService,
|
||||
ApplicationProperties applicationProperties) {
|
||||
ApplicationProperties applicationProperties,
|
||||
DistributedLock distributedLock) {
|
||||
this.keyPersistenceService = keyPersistenceService;
|
||||
this.jwtProperties = applicationProperties.getSecurity().getJwt();
|
||||
this.distributedLock = distributedLock;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -44,7 +56,28 @@ public class KeyPairCleanupService {
|
||||
if (!jwtProperties.isEnableKeyCleanup() || !keyPersistenceService.isKeystoreEnabled()) {
|
||||
return;
|
||||
}
|
||||
// A lock-backend error must never fail this @PostConstruct/scheduled run: degrade to
|
||||
// "skip this cycle" so a transient Valkey blip can't stop a node from booting.
|
||||
Optional<LockHandle> lock;
|
||||
try {
|
||||
lock = distributedLock.tryAcquire(CLEANUP_LOCK, LOCK_LEASE);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn(
|
||||
"Could not acquire the JWT key-cleanup lock ({}); skipping this cycle",
|
||||
e.getMessage());
|
||||
return;
|
||||
}
|
||||
// No lock means another node is already pruning; skip until the next tick.
|
||||
if (lock.isEmpty()) {
|
||||
log.debug("Another node holds the JWT key-cleanup lock; skipping this cycle");
|
||||
return;
|
||||
}
|
||||
try (LockHandle held = lock.get()) {
|
||||
runCleanup();
|
||||
}
|
||||
}
|
||||
|
||||
private void runCleanup() {
|
||||
LocalDateTime cutoffDate =
|
||||
LocalDateTime.now().minusDays(jwtProperties.getKeyRetentionDays());
|
||||
|
||||
|
||||
+172
-257
@@ -18,15 +18,17 @@ import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.caffeine.CaffeineCache;
|
||||
import org.springframework.context.annotation.DependsOn;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
@@ -34,27 +36,39 @@ import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.configuration.InstallationPathConfig;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.security.model.JwtSigningKeyEntity;
|
||||
import stirling.software.proprietary.security.model.JwtVerificationKey;
|
||||
import stirling.software.proprietary.security.repository.JwtSigningKeyRepository;
|
||||
|
||||
/** Persists JWT signing keys in the shared DB so all nodes sign/verify with the same key. */
|
||||
@Slf4j
|
||||
@Service
|
||||
// CredentialEncryption must init first: startup persists an encrypted private key.
|
||||
@DependsOn("credentialEncryption")
|
||||
public class KeyPersistenceService implements KeyPersistenceServiceInterface {
|
||||
|
||||
public static final String KEY_SUFFIX = ".key";
|
||||
public static final String PUB_KEY_SUFFIX = ".pub";
|
||||
|
||||
private final ApplicationProperties.Security.Jwt jwtProperties;
|
||||
private final CacheManager cacheManager;
|
||||
private final Cache verifyingKeyCache;
|
||||
private final JwtSigningKeyRepository keyRepository;
|
||||
private final boolean clusterEnabled;
|
||||
|
||||
// kid -> KeyPair; safe to cache since key material is immutable.
|
||||
private final Map<String, KeyPair> keyPairCache = new ConcurrentHashMap<>();
|
||||
|
||||
private volatile JwtVerificationKey activeKey;
|
||||
|
||||
@Autowired
|
||||
public KeyPersistenceService(
|
||||
ApplicationProperties applicationProperties, CacheManager cacheManager) {
|
||||
ApplicationProperties applicationProperties,
|
||||
CacheManager cacheManager,
|
||||
JwtSigningKeyRepository keyRepository,
|
||||
@Value("${cluster.enabled:false}") boolean clusterEnabled) {
|
||||
this.jwtProperties = applicationProperties.getSecurity().getJwt();
|
||||
this.cacheManager = cacheManager;
|
||||
this.verifyingKeyCache = cacheManager.getCache("verifyingKeys");
|
||||
this.keyRepository = keyRepository;
|
||||
this.clusterEnabled = clusterEnabled;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -63,138 +77,86 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {
|
||||
log.info("JWT keystore is disabled - keys will be generated in memory");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
ensurePrivateKeyDirectoryExists();
|
||||
loadExistingKeysFromDisk();
|
||||
importLegacyDiskKeysIfPresent();
|
||||
loadKeysFromDb();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to initialize keystore, using in-memory generation", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all existing JWT keys from disk into memory on startup.
|
||||
*
|
||||
* <p>This ensures tokens signed with previous keys remain valid after server restart. If no
|
||||
* keys exist on disk, generates a new keypair.
|
||||
*/
|
||||
private void loadExistingKeysFromDisk() {
|
||||
try {
|
||||
Path keyDirectory = Path.of(InstallationPathConfig.getPrivateKeyPath());
|
||||
|
||||
if (!Files.exists(keyDirectory)) {
|
||||
log.info("No existing keys found, generating new keypair");
|
||||
generateAndStoreKeypair();
|
||||
return;
|
||||
}
|
||||
|
||||
List<Path> keyFiles;
|
||||
try (var stream = Files.list(keyDirectory)) {
|
||||
keyFiles =
|
||||
stream.filter(path -> path.toString().endsWith(KEY_SUFFIX))
|
||||
.sorted(
|
||||
(a, b) ->
|
||||
b.getFileName().compareTo(a.getFileName())) // Most
|
||||
// recent
|
||||
// first
|
||||
.toList();
|
||||
}
|
||||
|
||||
if (keyFiles.isEmpty()) {
|
||||
log.info("No existing keys found in directory, generating new keypair");
|
||||
generateAndStoreKeypair();
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("Loading {} existing JWT keys from disk", keyFiles.size());
|
||||
int loadedCount = 0;
|
||||
|
||||
for (Path keyFile : keyFiles) {
|
||||
try {
|
||||
String keyId = keyFile.getFileName().toString().replace(KEY_SUFFIX, "");
|
||||
|
||||
// Load private key first
|
||||
PrivateKey privateKey = loadPrivateKey(keyId);
|
||||
|
||||
// Try to load public key, or generate it from private key if missing
|
||||
// (migration)
|
||||
String encodedPublicKey;
|
||||
try {
|
||||
encodedPublicKey = loadPublicKey(keyId);
|
||||
} catch (IOException e) {
|
||||
// Public key file doesn't exist - generate it from private key (migration)
|
||||
log.info("Migrating legacy key: generating public key file for {}", keyId);
|
||||
KeyPair keyPair = reconstructKeyPair(privateKey);
|
||||
|
||||
// Save the public key file
|
||||
Path publicKeyFile = keyDirectory.resolve(keyId + PUB_KEY_SUFFIX);
|
||||
encodedPublicKey = encodePublicKey(keyPair.getPublic());
|
||||
Files.writeString(publicKeyFile, encodedPublicKey);
|
||||
publicKeyFile.toFile().setReadable(true, true);
|
||||
publicKeyFile.toFile().setWritable(true, true);
|
||||
publicKeyFile.toFile().setExecutable(false, false);
|
||||
|
||||
log.info("Successfully migrated key: {}", keyId);
|
||||
}
|
||||
|
||||
// Create verification key and add to cache
|
||||
JwtVerificationKey verifyingKey =
|
||||
new JwtVerificationKey(keyId, encodedPublicKey);
|
||||
verifyingKeyCache.put(keyId, verifyingKey);
|
||||
loadedCount++;
|
||||
|
||||
// Set the most recent key as active (first in sorted list)
|
||||
if (activeKey == null) {
|
||||
activeKey = verifyingKey;
|
||||
log.info("Set active JWT signing key: {}", keyId);
|
||||
} else {
|
||||
log.debug(
|
||||
"Loaded historical JWT key: {} (created: {})",
|
||||
keyId,
|
||||
verifyingKey.getCreatedAt());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"Failed to load key: {}, skipping. Error: {}",
|
||||
keyFile.getFileName(),
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
if (loadedCount == 0) {
|
||||
log.warn("No valid keys could be loaded from disk, generating new keypair");
|
||||
generateAndStoreKeypair();
|
||||
} else {
|
||||
log.info(
|
||||
"Successfully loaded {} JWT keys, active key: {}",
|
||||
loadedCount,
|
||||
activeKey.getKeyId());
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to load keys from disk, generating new keypair", e);
|
||||
log.error("Failed to initialize keystore, generating a fresh keypair", e);
|
||||
generateAndStoreKeypair();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
private JwtVerificationKey generateAndStoreKeypair() {
|
||||
JwtVerificationKey verifyingKey = null;
|
||||
/**
|
||||
* Cluster convergence: adopt the newest signing key in the shared DB as this node's active key.
|
||||
* Runs on every node so a key a peer just minted becomes the shared active signer within one
|
||||
* interval, keeping cluster rotation equivalent to single-node. Cluster-only: a single node
|
||||
* always holds its own newest key, so this is skipped entirely off-cluster.
|
||||
*/
|
||||
@Scheduled(fixedDelayString = "${stirling.security.jwt.activeKeyReloadMs:300000}")
|
||||
public void reloadActiveKeyFromDb() {
|
||||
if (!clusterEnabled || !isKeystoreEnabled()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Optional<JwtSigningKeyEntity> newestOpt =
|
||||
keyRepository.findFirstByOrderByCreatedAtDesc();
|
||||
if (newestOpt.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
JwtSigningKeyEntity newest = newestOpt.get();
|
||||
JwtVerificationKey current = activeKey;
|
||||
if (current != null && newest.getKeyId().equals(current.getKeyId())) {
|
||||
return;
|
||||
}
|
||||
JwtVerificationKey adopted =
|
||||
new JwtVerificationKey(newest.getKeyId(), newest.getVerifyingKey());
|
||||
verifyingKeyCache.put(newest.getKeyId(), adopted);
|
||||
activeKey = adopted;
|
||||
log.info(
|
||||
"Adopted newest JWT signing key {} from the shared DB as active",
|
||||
newest.getKeyId());
|
||||
} catch (Exception e) {
|
||||
log.warn("Could not reload active JWT key from the shared DB: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Load every signing key from the shared DB into the caches; most recent becomes active. */
|
||||
private void loadKeysFromDb() {
|
||||
List<JwtSigningKeyEntity> keys = keyRepository.findAllByOrderByCreatedAtDesc();
|
||||
if (keys.isEmpty()) {
|
||||
log.info("No JWT keys in the database, generating a new keypair");
|
||||
generateAndStoreKeypair();
|
||||
return;
|
||||
}
|
||||
for (JwtSigningKeyEntity key : keys) {
|
||||
verifyingKeyCache.put(
|
||||
key.getKeyId(), new JwtVerificationKey(key.getKeyId(), key.getVerifyingKey()));
|
||||
}
|
||||
activeKey = new JwtVerificationKey(keys.get(0).getKeyId(), keys.get(0).getVerifyingKey());
|
||||
log.info("Loaded {} JWT key(s) from DB, active key: {}", keys.size(), activeKey.getKeyId());
|
||||
}
|
||||
|
||||
private JwtVerificationKey generateAndStoreKeypair() {
|
||||
try {
|
||||
KeyPair keyPair = generateRSAKeypair();
|
||||
String keyId = generateKeyId();
|
||||
String verifyingKey = encodePublicKey(keyPair.getPublic());
|
||||
String signingKey =
|
||||
Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
|
||||
|
||||
storeKeyPair(keyId, keyPair);
|
||||
verifyingKey = new JwtVerificationKey(keyId, encodePublicKey(keyPair.getPublic()));
|
||||
verifyingKeyCache.put(keyId, verifyingKey);
|
||||
activeKey = verifyingKey;
|
||||
// Converter encrypts the private key at rest with the shared credential-encryption key.
|
||||
keyRepository.save(new JwtSigningKeyEntity(keyId, verifyingKey, signingKey));
|
||||
|
||||
keyPairCache.put(keyId, keyPair);
|
||||
JwtVerificationKey verificationKey = new JwtVerificationKey(keyId, verifyingKey);
|
||||
verifyingKeyCache.put(keyId, verificationKey);
|
||||
activeKey = verificationKey;
|
||||
log.info("Generated and stored new JWT keypair: {}", keyId);
|
||||
} catch (IOException e) {
|
||||
return verificationKey;
|
||||
} catch (RuntimeException e) {
|
||||
log.error("Failed to generate and store keypair", e);
|
||||
return null;
|
||||
}
|
||||
|
||||
return verifyingKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -207,25 +169,29 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {
|
||||
|
||||
@Override
|
||||
public Optional<KeyPair> getKeyPair(String keyId) {
|
||||
if (!isKeystoreEnabled()) {
|
||||
if (!isKeystoreEnabled() || keyId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
KeyPair cached = keyPairCache.get(keyId);
|
||||
if (cached != null) {
|
||||
return Optional.of(cached);
|
||||
}
|
||||
Optional<JwtSigningKeyEntity> entityOpt = keyRepository.findById(keyId);
|
||||
if (entityOpt.isEmpty()) {
|
||||
log.warn("No signing key found in DB for keyId: {}", keyId);
|
||||
return Optional.empty();
|
||||
}
|
||||
JwtSigningKeyEntity entity = entityOpt.get();
|
||||
try {
|
||||
JwtVerificationKey verifyingKey =
|
||||
verifyingKeyCache.get(keyId, JwtVerificationKey.class);
|
||||
|
||||
if (verifyingKey == null) {
|
||||
log.warn("No signing key found in database for keyId: {}", keyId);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
PrivateKey privateKey = loadPrivateKey(keyId);
|
||||
PublicKey publicKey = decodePublicKey(verifyingKey.getVerifyingKey());
|
||||
|
||||
return Optional.of(new KeyPair(publicKey, privateKey));
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to load keypair for keyId: {}", keyId, e);
|
||||
KeyPair keyPair =
|
||||
new KeyPair(
|
||||
decodePublicKey(entity.getVerifyingKey()),
|
||||
decodePrivateKey(entity.getSigningKey()));
|
||||
keyPairCache.put(keyId, keyPair);
|
||||
verifyingKeyCache.put(keyId, new JwtVerificationKey(keyId, entity.getVerifyingKey()));
|
||||
return Optional.of(keyPair);
|
||||
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
|
||||
log.error("Failed to decode keypair for keyId: {}", keyId, e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -241,44 +207,69 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {
|
||||
}
|
||||
|
||||
@Override
|
||||
@CacheEvict(
|
||||
value = {"verifyingKeys"},
|
||||
key = "#keyId",
|
||||
condition = "#root.target.isKeystoreEnabled()")
|
||||
public void removeKey(String keyId) {
|
||||
keyRepository.deleteById(keyId);
|
||||
verifyingKeyCache.evict(keyId);
|
||||
keyPairCache.remove(keyId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<JwtVerificationKey> getKeysEligibleForCleanup(LocalDateTime cutoffDate) {
|
||||
CaffeineCache caffeineCache = (CaffeineCache) verifyingKeyCache;
|
||||
com.github.benmanes.caffeine.cache.Cache<Object, Object> nativeCache =
|
||||
caffeineCache.getNativeCache();
|
||||
|
||||
log.debug(
|
||||
"Cache size: {}, Checking {} keys for cleanup",
|
||||
nativeCache.estimatedSize(),
|
||||
nativeCache.asMap().size());
|
||||
|
||||
return nativeCache.asMap().values().stream()
|
||||
.filter(value -> value instanceof JwtVerificationKey)
|
||||
.map(value -> (JwtVerificationKey) value)
|
||||
.filter(
|
||||
key -> {
|
||||
boolean eligible = key.getCreatedAt().isBefore(cutoffDate);
|
||||
log.debug(
|
||||
"Key {} created at {}, eligible for cleanup: {}",
|
||||
key.getKeyId(),
|
||||
key.getCreatedAt(),
|
||||
eligible);
|
||||
return eligible;
|
||||
})
|
||||
return keyRepository.findByCreatedAtBefore(cutoffDate).stream()
|
||||
.map(e -> new JwtVerificationKey(e.getKeyId(), e.getVerifyingKey()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** Import any pre-existing on-disk keys into the DB once, so upgrades keep sessions valid. */
|
||||
private void importLegacyDiskKeysIfPresent() {
|
||||
if (keyRepository.count() > 0) {
|
||||
return;
|
||||
}
|
||||
Path keyDirectory = Path.of(InstallationPathConfig.getPrivateKeyPath());
|
||||
if (!Files.exists(keyDirectory)) {
|
||||
return;
|
||||
}
|
||||
List<Path> keyFiles;
|
||||
try (var stream = Files.list(keyDirectory)) {
|
||||
keyFiles = stream.filter(p -> p.toString().endsWith(KEY_SUFFIX)).toList();
|
||||
} catch (IOException e) {
|
||||
log.warn("Could not list legacy key directory {}: {}", keyDirectory, e.getMessage());
|
||||
return;
|
||||
}
|
||||
int imported = 0;
|
||||
for (Path keyFile : keyFiles) {
|
||||
String keyId = keyFile.getFileName().toString().replace(KEY_SUFFIX, "");
|
||||
try {
|
||||
PrivateKey privateKey = loadPrivateKey(keyId);
|
||||
String verifyingKey = resolveLegacyPublicKey(keyId, privateKey);
|
||||
String signingKey = Base64.getEncoder().encodeToString(privateKey.getEncoded());
|
||||
keyRepository.save(new JwtSigningKeyEntity(keyId, verifyingKey, signingKey));
|
||||
imported++;
|
||||
} catch (Exception e) {
|
||||
log.warn("Skipping legacy key {}: {}", keyId, e.getMessage());
|
||||
}
|
||||
}
|
||||
if (imported > 0) {
|
||||
log.info("Imported {} legacy JWT key(s) from disk into the shared DB", imported);
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveLegacyPublicKey(String keyId, PrivateKey privateKey)
|
||||
throws NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
try {
|
||||
return loadPublicKey(keyId);
|
||||
} catch (IOException e) {
|
||||
// No .pub file: derive the public key from the RSA private key.
|
||||
return encodePublicKey(reconstructKeyPair(privateKey).getPublic());
|
||||
}
|
||||
}
|
||||
|
||||
// UUID suffix so two nodes booting the same second don't collide on keyId.
|
||||
private String generateKeyId() {
|
||||
return "jwt-key-"
|
||||
+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss"));
|
||||
+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss"))
|
||||
+ "-"
|
||||
+ UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private KeyPair generateRSAKeypair() {
|
||||
@@ -291,125 +282,49 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {
|
||||
}
|
||||
}
|
||||
|
||||
private void ensurePrivateKeyDirectoryExists() throws IOException {
|
||||
Path keyPath = Path.of(InstallationPathConfig.getPrivateKeyPath());
|
||||
|
||||
if (!Files.exists(keyPath)) {
|
||||
Files.createDirectories(keyPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store both private and public keys to disk.
|
||||
*
|
||||
* <p>Private key stored as: keyId.key
|
||||
*
|
||||
* <p>Public key stored as: keyId.pub
|
||||
*/
|
||||
private void storeKeyPair(String keyId, KeyPair keyPair) throws IOException {
|
||||
Path keyDirectory = Path.of(InstallationPathConfig.getPrivateKeyPath());
|
||||
|
||||
// Store private key
|
||||
Path privateKeyFile = keyDirectory.resolve(keyId + KEY_SUFFIX);
|
||||
String encodedPrivateKey =
|
||||
Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
|
||||
Files.writeString(privateKeyFile, encodedPrivateKey);
|
||||
|
||||
// Set read/write to only the owner (security)
|
||||
privateKeyFile.toFile().setReadable(true, true);
|
||||
privateKeyFile.toFile().setWritable(true, true);
|
||||
privateKeyFile.toFile().setExecutable(false, false);
|
||||
|
||||
// Store public key
|
||||
Path publicKeyFile = keyDirectory.resolve(keyId + PUB_KEY_SUFFIX);
|
||||
String encodedPublicKey =
|
||||
Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
|
||||
Files.writeString(publicKeyFile, encodedPublicKey);
|
||||
|
||||
// Public key can be more permissive but still restrict to owner
|
||||
publicKeyFile.toFile().setReadable(true, true);
|
||||
publicKeyFile.toFile().setWritable(true, true);
|
||||
publicKeyFile.toFile().setExecutable(false, false);
|
||||
|
||||
log.debug(
|
||||
"Stored keypair to disk: {} (private: {}, public: {})",
|
||||
keyId,
|
||||
privateKeyFile.getFileName(),
|
||||
publicKeyFile.getFileName());
|
||||
}
|
||||
|
||||
private PrivateKey loadPrivateKey(String keyId)
|
||||
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
Path keyFile =
|
||||
Path.of(InstallationPathConfig.getPrivateKeyPath()).resolve(keyId + KEY_SUFFIX);
|
||||
|
||||
if (!Files.exists(keyFile)) {
|
||||
throw new IOException("Private key not found: " + keyFile);
|
||||
}
|
||||
|
||||
String encodedKey = Files.readString(keyFile);
|
||||
byte[] keyBytes = Base64.getDecoder().decode(encodedKey);
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
|
||||
return keyFactory.generatePrivate(keySpec);
|
||||
return decodePrivateKey(Files.readString(keyFile));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load public key from disk.
|
||||
*
|
||||
* @param keyId the key identifier
|
||||
* @return Base64-encoded public key string
|
||||
* @throws IOException if the public key file is not found
|
||||
*/
|
||||
private String loadPublicKey(String keyId) throws IOException {
|
||||
Path publicKeyFile =
|
||||
Path.of(InstallationPathConfig.getPrivateKeyPath()).resolve(keyId + PUB_KEY_SUFFIX);
|
||||
|
||||
if (!Files.exists(publicKeyFile)) {
|
||||
throw new IOException("Public key not found: " + publicKeyFile);
|
||||
}
|
||||
|
||||
return Files.readString(publicKeyFile).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstruct a KeyPair from a PrivateKey.
|
||||
*
|
||||
* <p>For RSA keys, derives the public key from the private key.
|
||||
*
|
||||
* @param privateKey the RSA private key
|
||||
* @return reconstructed KeyPair
|
||||
* @throws NoSuchAlgorithmException if RSA algorithm is not available
|
||||
* @throws InvalidKeySpecException if the key specification is invalid
|
||||
*/
|
||||
private KeyPair reconstructKeyPair(PrivateKey privateKey)
|
||||
throws NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
// For RSA, we can derive the public key from the private key
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
|
||||
// Get the private key spec
|
||||
RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
|
||||
|
||||
// Create public key spec from private key parameters
|
||||
RSAPublicKeySpec publicKeySpec =
|
||||
new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent());
|
||||
|
||||
// Generate public key
|
||||
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
|
||||
|
||||
return new KeyPair(publicKey, privateKey);
|
||||
return new KeyPair(keyFactory.generatePublic(publicKeySpec), privateKey);
|
||||
}
|
||||
|
||||
private String encodePublicKey(PublicKey publicKey) {
|
||||
return Base64.getEncoder().encodeToString(publicKey.getEncoded());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PublicKey decodePublicKey(String encodedKey)
|
||||
throws NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
byte[] keyBytes = Base64.getDecoder().decode(encodedKey);
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
return keyFactory.generatePublic(keySpec);
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
|
||||
return KeyFactory.getInstance("RSA").generatePublic(keySpec);
|
||||
}
|
||||
|
||||
private PrivateKey decodePrivateKey(String encodedKey)
|
||||
throws NoSuchAlgorithmException, InvalidKeySpecException {
|
||||
PKCS8EncodedKeySpec keySpec =
|
||||
new PKCS8EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
|
||||
return KeyFactory.getInstance("RSA").generatePrivate(keySpec);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-1
@@ -27,6 +27,8 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import stirling.software.common.cluster.JobStore;
|
||||
import stirling.software.common.cluster.inprocess.InProcessJobStore;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.job.JobResponse;
|
||||
import stirling.software.common.service.JobOwnershipService;
|
||||
@@ -78,6 +80,7 @@ class PolicyControllerTest {
|
||||
@Mock private JobOwnershipService jobOwnershipService;
|
||||
|
||||
private ApplicationProperties applicationProperties;
|
||||
private final JobStore jobStore = new InProcessJobStore();
|
||||
private PolicyController controller;
|
||||
|
||||
private final java.util.List<stirling.software.proprietary.policy.trigger.PolicyTrigger>
|
||||
@@ -106,7 +109,8 @@ class PolicyControllerTest {
|
||||
policyTriggers,
|
||||
applicationProperties,
|
||||
tempFileManager,
|
||||
jobOwnershipService);
|
||||
jobOwnershipService,
|
||||
jobStore);
|
||||
}
|
||||
|
||||
private static stirling.software.proprietary.policy.trigger.PolicyTrigger trigger(
|
||||
@@ -264,6 +268,8 @@ class PolicyControllerTest {
|
||||
@DisplayName("returns 404 when run is unknown")
|
||||
void notFound() {
|
||||
when(runRegistry.get("missing")).thenReturn(null);
|
||||
when(jobOwnershipService.extractJobId("missing")).thenReturn("missing");
|
||||
when(jobOwnershipService.createScopedJobKey("missing")).thenReturn("missing");
|
||||
|
||||
ResponseEntity<PolicyRunView> response = controller.status("missing");
|
||||
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package stirling.software.proprietary.security.service;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import stirling.software.common.cluster.DistributedLock;
|
||||
import stirling.software.common.cluster.DistributedLock.LockHandle;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.security.model.JwtVerificationKey;
|
||||
|
||||
/** Cluster safety: pruning JWT keys is single-writer, gated on the shared cleanup lock. */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeyPairCleanupServiceTest {
|
||||
|
||||
@Mock private KeyPersistenceService keyPersistenceService;
|
||||
@Mock private ApplicationProperties applicationProperties;
|
||||
@Mock private ApplicationProperties.Security security;
|
||||
@Mock private ApplicationProperties.Security.Jwt jwtProperties;
|
||||
@Mock private DistributedLock distributedLock;
|
||||
@Mock private LockHandle lockHandle;
|
||||
|
||||
private KeyPairCleanupService cleanupService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lenient().when(applicationProperties.getSecurity()).thenReturn(security);
|
||||
lenient().when(security.getJwt()).thenReturn(jwtProperties);
|
||||
lenient().when(jwtProperties.isEnableKeyCleanup()).thenReturn(true);
|
||||
lenient().when(keyPersistenceService.isKeystoreEnabled()).thenReturn(true);
|
||||
cleanupService =
|
||||
new KeyPairCleanupService(
|
||||
keyPersistenceService, applicationProperties, distributedLock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsPruningWhenAnotherNodeHoldsTheLock() {
|
||||
when(distributedLock.tryAcquire(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
cleanupService.cleanup();
|
||||
|
||||
// No node-local pruning happened; the lock holder owns this cycle.
|
||||
verify(keyPersistenceService, never()).getKeysEligibleForCleanup(any());
|
||||
verify(keyPersistenceService, never()).refreshActiveKeyPair();
|
||||
}
|
||||
|
||||
@Test
|
||||
void prunesAndRotatesWhenLockAcquiredThenReleasesIt() {
|
||||
when(distributedLock.tryAcquire(any(), any())).thenReturn(Optional.of(lockHandle));
|
||||
when(keyPersistenceService.getKeysEligibleForCleanup(any()))
|
||||
.thenReturn(List.of(new JwtVerificationKey("old-key", "cHVi")));
|
||||
|
||||
cleanupService.cleanup();
|
||||
|
||||
verify(keyPersistenceService).removeKey("old-key");
|
||||
verify(keyPersistenceService).refreshActiveKeyPair();
|
||||
verify(lockHandle).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void releasesTheLockEvenWhenNoKeysAreEligible() {
|
||||
when(distributedLock.tryAcquire(any(), any())).thenReturn(Optional.of(lockHandle));
|
||||
when(keyPersistenceService.getKeysEligibleForCleanup(any())).thenReturn(List.of());
|
||||
|
||||
cleanupService.cleanup();
|
||||
|
||||
verify(keyPersistenceService, never()).refreshActiveKeyPair();
|
||||
verify(lockHandle).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsPruningWhenTheLockBackendErrors() {
|
||||
// A Valkey blip at boot must not fail startup: tryAcquire throwing degrades to skip.
|
||||
when(distributedLock.tryAcquire(any(), any()))
|
||||
.thenThrow(new RuntimeException("valkey unreachable"));
|
||||
|
||||
cleanupService.cleanup();
|
||||
|
||||
verify(keyPersistenceService, never()).getKeysEligibleForCleanup(any());
|
||||
verify(keyPersistenceService, never()).refreshActiveKeyPair();
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNothingWhenCleanupDisabled() {
|
||||
when(jwtProperties.isEnableKeyCleanup()).thenReturn(false);
|
||||
|
||||
cleanupService.cleanup();
|
||||
|
||||
verify(distributedLock, never()).tryAcquire(any(), any());
|
||||
}
|
||||
}
|
||||
+93
-144
@@ -4,45 +4,41 @@ 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.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
|
||||
|
||||
import stirling.software.common.configuration.InstallationPathConfig;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.security.model.JwtSigningKeyEntity;
|
||||
import stirling.software.proprietary.security.model.JwtVerificationKey;
|
||||
import stirling.software.proprietary.security.repository.JwtSigningKeyRepository;
|
||||
|
||||
/** DB-backed keystore: a key present only in the shared DB still resolves (the cross-node case). */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeyPersistenceServiceInterfaceTest {
|
||||
|
||||
@Mock private ApplicationProperties applicationProperties;
|
||||
|
||||
@Mock private ApplicationProperties.Security security;
|
||||
|
||||
@Mock private ApplicationProperties.Security.Jwt jwtConfig;
|
||||
|
||||
@TempDir Path tempDir;
|
||||
@Mock private JwtSigningKeyRepository keyRepository;
|
||||
|
||||
private KeyPersistenceService keyPersistenceService;
|
||||
private KeyPair testKeyPair;
|
||||
@@ -58,175 +54,128 @@ class KeyPersistenceServiceInterfaceTest {
|
||||
|
||||
lenient().when(applicationProperties.getSecurity()).thenReturn(security);
|
||||
lenient().when(security.getJwt()).thenReturn(jwtConfig);
|
||||
lenient().when(jwtConfig.isEnableKeystore()).thenReturn(true); // Default value
|
||||
lenient().when(jwtConfig.isEnableKeystore()).thenReturn(true);
|
||||
lenient().when(keyRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
// clusterEnabled=true so the convergence-reload path is exercised.
|
||||
keyPersistenceService =
|
||||
new KeyPersistenceService(applicationProperties, cacheManager, keyRepository, true);
|
||||
}
|
||||
|
||||
private JwtSigningKeyEntity entityFrom(String keyId) {
|
||||
return new JwtSigningKeyEntity(
|
||||
keyId,
|
||||
Base64.getEncoder().encodeToString(testKeyPair.getPublic().getEncoded()),
|
||||
Base64.getEncoder().encodeToString(testKeyPair.getPrivate().getEncoded()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testKeystoreEnabled(boolean keystoreEnabled) {
|
||||
when(jwtConfig.isEnableKeystore()).thenReturn(keystoreEnabled);
|
||||
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
|
||||
assertEquals(keystoreEnabled, keyPersistenceService.isKeystoreEnabled());
|
||||
}
|
||||
assertEquals(keystoreEnabled, keyPersistenceService.isKeystoreEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActiveKeypairWhenNoActiveKeyExists() {
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
keyPersistenceService.initializeKeystore();
|
||||
void generatesAndPersistsAKeyWhenNoneIsActive() {
|
||||
// getActiveKey with no active key mints one and persists it - no disk involved.
|
||||
JwtVerificationKey active = keyPersistenceService.getActiveKey();
|
||||
|
||||
JwtVerificationKey result = keyPersistenceService.getActiveKey();
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getKeyId());
|
||||
assertNotNull(result.getVerifyingKey());
|
||||
}
|
||||
assertNotNull(active);
|
||||
assertNotNull(active.getKeyId());
|
||||
assertNotNull(active.getVerifyingKey());
|
||||
verify(keyRepository).save(any(JwtSigningKeyEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActiveKeyPairWithExistingKey() throws Exception {
|
||||
String keyId = "test-key-2024-01-01-120000";
|
||||
String publicKeyBase64 =
|
||||
Base64.getEncoder().encodeToString(testKeyPair.getPublic().getEncoded());
|
||||
String privateKeyBase64 =
|
||||
Base64.getEncoder().encodeToString(testKeyPair.getPrivate().getEncoded());
|
||||
void loadsTheMostRecentExistingKeyAsActive() {
|
||||
when(keyRepository.count()).thenReturn(1L);
|
||||
when(keyRepository.findAllByOrderByCreatedAtDesc())
|
||||
.thenReturn(List.of(entityFrom("jwt-key-2026-07-13-000000-abcd1234")));
|
||||
|
||||
JwtVerificationKey existingKey = new JwtVerificationKey(keyId, publicKeyBase64);
|
||||
keyPersistenceService.initializeKeystore();
|
||||
JwtVerificationKey active = keyPersistenceService.getActiveKey();
|
||||
|
||||
Path keyFile = tempDir.resolve(keyId + ".key");
|
||||
Files.writeString(keyFile, privateKeyBase64);
|
||||
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
keyPersistenceService.initializeKeystore();
|
||||
|
||||
JwtVerificationKey result = keyPersistenceService.getActiveKey();
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getKeyId());
|
||||
}
|
||||
assertEquals("jwt-key-2026-07-13-000000-abcd1234", active.getKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeyPair() throws Exception {
|
||||
String keyId = "test-key-123";
|
||||
String publicKeyBase64 =
|
||||
Base64.getEncoder().encodeToString(testKeyPair.getPublic().getEncoded());
|
||||
String privateKeyBase64 =
|
||||
Base64.getEncoder().encodeToString(testKeyPair.getPrivate().getEncoded());
|
||||
void getKeyPairResolvesAKeyPresentOnlyInTheSharedDb() {
|
||||
// Never initialised locally: the key lives only in the DB, as if another node minted it.
|
||||
String keyId = "jwt-key-from-another-node";
|
||||
when(keyRepository.findById(keyId)).thenReturn(Optional.of(entityFrom(keyId)));
|
||||
|
||||
JwtVerificationKey signingKey = new JwtVerificationKey(keyId, publicKeyBase64);
|
||||
Optional<KeyPair> result = keyPersistenceService.getKeyPair(keyId);
|
||||
|
||||
Path keyFile = tempDir.resolve(keyId + ".key");
|
||||
Files.writeString(keyFile, privateKeyBase64);
|
||||
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
|
||||
keyPersistenceService
|
||||
.getClass()
|
||||
.getDeclaredField("verifyingKeyCache")
|
||||
.setAccessible(true);
|
||||
var cache = cacheManager.getCache("verifyingKeys");
|
||||
cache.put(keyId, signingKey);
|
||||
|
||||
Optional<KeyPair> result = keyPersistenceService.getKeyPair(keyId);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertNotNull(result.get().getPublic());
|
||||
assertNotNull(result.get().getPrivate());
|
||||
}
|
||||
assertTrue(result.isPresent());
|
||||
assertNotNull(result.get().getPublic());
|
||||
assertNotNull(result.get().getPrivate());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeyPairNotFound() {
|
||||
String keyId = "non-existent-key";
|
||||
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
|
||||
Optional<KeyPair> result = keyPersistenceService.getKeyPair(keyId);
|
||||
|
||||
assertFalse(result.isPresent());
|
||||
}
|
||||
void getKeyPairIsEmptyWhenTheKeyIsUnknown() {
|
||||
when(keyRepository.findById("nope")).thenReturn(Optional.empty());
|
||||
assertFalse(keyPersistenceService.getKeyPair("nope").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeyPairWhenKeystoreDisabled() {
|
||||
void getKeyPairIsEmptyWhenKeystoreDisabled() {
|
||||
when(jwtConfig.isEnableKeystore()).thenReturn(false);
|
||||
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
|
||||
Optional<KeyPair> result = keyPersistenceService.getKeyPair("any-key");
|
||||
|
||||
assertFalse(result.isPresent());
|
||||
}
|
||||
assertFalse(keyPersistenceService.getKeyPair("any-key").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInitializeKeystoreCreatesDirectory() throws IOException {
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
keyPersistenceService.initializeKeystore();
|
||||
void eligibleForCleanupIsSourcedFromTheDb() {
|
||||
when(keyRepository.findByCreatedAtBefore(any())).thenReturn(List.of(entityFrom("old-key")));
|
||||
|
||||
assertTrue(Files.exists(tempDir));
|
||||
assertTrue(Files.isDirectory(tempDir));
|
||||
}
|
||||
List<JwtVerificationKey> stale =
|
||||
keyPersistenceService.getKeysEligibleForCleanup(java.time.LocalDateTime.now());
|
||||
|
||||
assertEquals(1, stale.size());
|
||||
assertEquals("old-key", stale.get(0).getKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLoadExistingKeypairWithMissingPrivateKeyFile() throws Exception {
|
||||
String keyId = "test-key-missing-file";
|
||||
String publicKeyBase64 =
|
||||
Base64.getEncoder().encodeToString(testKeyPair.getPublic().getEncoded());
|
||||
void reloadAdoptsTheNewestKeyAPeerMinted() {
|
||||
// Boot with our own key active, then a peer mints a newer one in the shared DB.
|
||||
when(keyRepository.count()).thenReturn(1L);
|
||||
when(keyRepository.findAllByOrderByCreatedAtDesc())
|
||||
.thenReturn(List.of(entityFrom("jwt-key-local-old")));
|
||||
keyPersistenceService.initializeKeystore();
|
||||
assertEquals("jwt-key-local-old", keyPersistenceService.getActiveKey().getKeyId());
|
||||
|
||||
JwtVerificationKey existingKey = new JwtVerificationKey(keyId, publicKeyBase64);
|
||||
when(keyRepository.findFirstByOrderByCreatedAtDesc())
|
||||
.thenReturn(Optional.of(entityFrom("jwt-key-peer-new")));
|
||||
|
||||
try (MockedStatic<InstallationPathConfig> mockedStatic =
|
||||
mockStatic(InstallationPathConfig.class)) {
|
||||
mockedStatic
|
||||
.when(InstallationPathConfig::getPrivateKeyPath)
|
||||
.thenReturn(tempDir.toString());
|
||||
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
|
||||
keyPersistenceService.initializeKeystore();
|
||||
keyPersistenceService.reloadActiveKeyFromDb();
|
||||
|
||||
JwtVerificationKey result = keyPersistenceService.getActiveKey();
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getKeyId());
|
||||
assertNotNull(result.getVerifyingKey());
|
||||
}
|
||||
// Converged: this node now signs with the peer's newer key.
|
||||
assertEquals("jwt-key-peer-new", keyPersistenceService.getActiveKey().getKeyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadDoesNothingOffCluster() {
|
||||
KeyPersistenceService singleNode =
|
||||
new KeyPersistenceService(
|
||||
applicationProperties, cacheManager, keyRepository, false);
|
||||
|
||||
singleNode.reloadActiveKeyFromDb();
|
||||
|
||||
// Off-cluster the DB is never consulted for convergence.
|
||||
verify(keyRepository, org.mockito.Mockito.never()).findFirstByOrderByCreatedAtDesc();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadIsANoOpWhenAlreadyHoldingTheNewestKey() {
|
||||
when(keyRepository.count()).thenReturn(1L);
|
||||
when(keyRepository.findAllByOrderByCreatedAtDesc())
|
||||
.thenReturn(List.of(entityFrom("jwt-key-current")));
|
||||
keyPersistenceService.initializeKeystore();
|
||||
|
||||
when(keyRepository.findFirstByOrderByCreatedAtDesc())
|
||||
.thenReturn(Optional.of(entityFrom("jwt-key-current")));
|
||||
|
||||
keyPersistenceService.reloadActiveKeyFromDb();
|
||||
|
||||
assertEquals("jwt-key-current", keyPersistenceService.getActiveKey().getKeyId());
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -91,7 +91,7 @@ springBoot {
|
||||
|
||||
allprojects {
|
||||
group = 'stirling.software'
|
||||
version = '2.14.1'
|
||||
version = '2.14.2'
|
||||
|
||||
configurations.configureEach {
|
||||
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
|
||||
|
||||
@@ -3655,7 +3655,6 @@ shareSelected = "Share Files"
|
||||
sharing = "Sharing"
|
||||
showAll = "Show All"
|
||||
showHistory = "Show History"
|
||||
showInFolder = "Show in folder"
|
||||
sortByDate = "Sort by Date"
|
||||
sortByName = "Sort by Name"
|
||||
sortBySize = "Sort by Size"
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::utils::add_log;
|
||||
use std::sync::Mutex;
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
// Store the opened file paths globally (supports multiple files)
|
||||
static OPENED_FILES: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
@@ -43,41 +42,3 @@ pub async fn pop_opened_files() -> Result<Vec<String>, String> {
|
||||
add_log(format!("📂 Returning and clearing {} opened file(s)", all_files.len()));
|
||||
Ok(all_files)
|
||||
}
|
||||
|
||||
// Report whether a path still exists on disk (used to prune stale recent files).
|
||||
#[tauri::command]
|
||||
pub fn path_exists(path: String) -> bool {
|
||||
std::path::Path::new(&path).exists()
|
||||
}
|
||||
|
||||
// Reveal a file in the OS file manager (Explorer/Finder), highlighting it.
|
||||
#[tauri::command]
|
||||
pub async fn reveal_in_file_manager(app: tauri::AppHandle, path: String) -> Result<(), String> {
|
||||
app.opener()
|
||||
.reveal_item_in_dir(&path)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
#[test]
|
||||
fn path_exists_tracks_real_disk_state() {
|
||||
let file = std::env::temp_dir()
|
||||
.join(format!("stirling_path_exists_{}.tmp", std::process::id()));
|
||||
let path = file.to_string_lossy().to_string();
|
||||
|
||||
// Absent before creation.
|
||||
assert!(!path_exists(path.clone()));
|
||||
|
||||
// Present once written.
|
||||
writeln!(std::fs::File::create(&file).unwrap(), "x").unwrap();
|
||||
assert!(path_exists(path.clone()));
|
||||
|
||||
// Gone again after deletion (the case that prunes a recent).
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
assert!(!path_exists(path));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,7 @@ pub mod updater;
|
||||
pub mod window;
|
||||
|
||||
pub use backend::{cleanup_backend, get_backend_port, start_backend};
|
||||
pub use files::{
|
||||
add_opened_file, clear_opened_files, get_opened_files, path_exists, pop_opened_files,
|
||||
reveal_in_file_manager,
|
||||
};
|
||||
pub use files::{add_opened_file, clear_opened_files, get_opened_files, pop_opened_files};
|
||||
pub use window::{
|
||||
forward_files_to_window,
|
||||
open_files_in_new_window,
|
||||
|
||||
@@ -19,10 +19,8 @@ use commands::{
|
||||
get_opened_files,
|
||||
open_files_in_new_window,
|
||||
open_in_new_window,
|
||||
path_exists,
|
||||
pop_opened_files,
|
||||
pop_window_file_ids,
|
||||
reveal_in_file_manager,
|
||||
get_refresh_token,
|
||||
get_user_info,
|
||||
is_first_launch,
|
||||
@@ -169,8 +167,6 @@ pub fn run() {
|
||||
get_opened_files,
|
||||
pop_opened_files,
|
||||
clear_opened_files,
|
||||
path_exists,
|
||||
reveal_in_file_manager,
|
||||
open_in_new_window,
|
||||
open_files_in_new_window,
|
||||
pop_window_file_ids,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "Stirling PDF",
|
||||
"mainBinaryName": "Stirling-PDF",
|
||||
"version": "2.14.1",
|
||||
"version": "2.14.2",
|
||||
"identifier": "stirling.pdf.dev",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -19,7 +19,6 @@ import CloseIcon from "@mui/icons-material/Close";
|
||||
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
|
||||
import CloudDoneIcon from "@mui/icons-material/CloudDone";
|
||||
import LinkIcon from "@mui/icons-material/Link";
|
||||
import FolderOpenIcon from "@mui/icons-material/FolderOpen";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getFileSize, getFileDate } from "@app/utils/fileUtils";
|
||||
import { FileId, StirlingFileStub } from "@app/types/fileContext";
|
||||
@@ -36,10 +35,6 @@ import ShareManagementModal from "@app/components/shared/ShareManagementModal";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { absoluteWithBasePath } from "@app/constants/app";
|
||||
import { alert } from "@app/components/toast";
|
||||
import {
|
||||
desktopFileLinkingSupported,
|
||||
revealPathInFileManager,
|
||||
} from "@app/services/desktopFileLink";
|
||||
|
||||
interface FileListItemProps {
|
||||
file: StirlingFileStub;
|
||||
@@ -373,18 +368,6 @@ const FileListItem: React.FC<FileListItemProps> = ({
|
||||
</Menu.Item>
|
||||
)}
|
||||
|
||||
{desktopFileLinkingSupported && file.localFilePath && (
|
||||
<Menu.Item
|
||||
leftSection={<FolderOpenIcon style={{ fontSize: 16 }} />}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
void revealPathInFileManager(file.localFilePath!);
|
||||
}}
|
||||
>
|
||||
{t("fileManager.showInFolder", "Show in folder")}
|
||||
</Menu.Item>
|
||||
)}
|
||||
|
||||
{canUpload && (
|
||||
<Menu.Item
|
||||
leftSection={<CloudUploadIcon style={{ fontSize: 16 }} />}
|
||||
|
||||
@@ -5,12 +5,6 @@ import { StirlingFileStub, StirlingFile } from "@app/types/fileContext";
|
||||
import { FileId } from "@app/types/fileContext";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { useAppConfig } from "@app/contexts/AppConfigContext";
|
||||
import {
|
||||
pruneMissingRecentFiles,
|
||||
reconcileServerBackedRecents,
|
||||
hasLocalRecord,
|
||||
} from "@app/services/pruneMissingRecentFiles";
|
||||
import { desktopFileLinkingSupported } from "@app/services/desktopFileLink";
|
||||
|
||||
interface StoredFileResponse {
|
||||
id: number;
|
||||
@@ -111,10 +105,7 @@ export const useFileManager = () => {
|
||||
}
|
||||
|
||||
// Load only leaf files metadata (processed files that haven't been used as input for other tools)
|
||||
// On desktop, drop entries whose linked file no longer exists on disk.
|
||||
const stirlingFileStubs = await pruneMissingRecentFiles(
|
||||
await fileStorage.getLeafStirlingFileStubs(),
|
||||
);
|
||||
const stirlingFileStubs = await fileStorage.getLeafStirlingFileStubs();
|
||||
const remoteIdSet = new Set(
|
||||
stirlingFileStubs
|
||||
.map((stub) => stub.remoteStorageId)
|
||||
@@ -142,21 +133,7 @@ export const useFileManager = () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Desktop: a server-uploaded recent whose local disk original was
|
||||
// deleted drops its local copy, becoming a pure server file — it
|
||||
// leaves recents but stays under My Files, downloadable. Gated on the
|
||||
// server confirming it holds the file, so the last copy is never lost.
|
||||
let localStubs = stirlingFileStubs;
|
||||
const demotedIds = await reconcileServerBackedRecents(
|
||||
stirlingFileStubs,
|
||||
(id) => serverMap.has(id),
|
||||
);
|
||||
if (demotedIds.length > 0) {
|
||||
const removedSet = new Set(demotedIds);
|
||||
localStubs = stirlingFileStubs.filter((s) => !removedSet.has(s.id));
|
||||
}
|
||||
|
||||
const updatedLocalStubs = localStubs.map((stub) => {
|
||||
const updatedLocalStubs = stirlingFileStubs.map((stub) => {
|
||||
if (!stub.remoteStorageId) {
|
||||
return stub;
|
||||
}
|
||||
@@ -374,15 +351,8 @@ export const useFileManager = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Desktop recents show only files with a local IndexedDB record; files
|
||||
// that live ONLY on the server (ephemeral server-/shared- stubs, no IDB
|
||||
// row) belong in the My Files view, not here.
|
||||
const recentStubs = desktopFileLinkingSupported
|
||||
? combinedStubs.filter(hasLocalRecord)
|
||||
: combinedStubs;
|
||||
|
||||
// For now, only regular files - drafts will be handled separately in the future
|
||||
const sortedFiles = recentStubs.sort(
|
||||
const sortedFiles = combinedStubs.sort(
|
||||
(a, b) => (b.lastModified || 0) - (a.lastModified || 0),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// Seam for linking recent files to their real file on disk (desktop only).
|
||||
// Non-desktop builds resolve to this no-op default via the @app alias order,
|
||||
// so web/SaaS have no disk-linked recents to prune or reveal.
|
||||
|
||||
// False on web: the recent-file pruner and "Show in folder" action are skipped.
|
||||
export const desktopFileLinkingSupported = false;
|
||||
|
||||
// Assume present so the pruner never drops a recent file off the desktop app.
|
||||
export async function pathExistsOnDisk(_path: string): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
// No OS file manager to reveal into outside the desktop app.
|
||||
export async function revealPathInFileManager(_path: string): Promise<void> {}
|
||||
@@ -29,7 +29,6 @@ export interface StoredStirlingFileRecord extends BaseFileMetadata {
|
||||
thumbnail?: string;
|
||||
thumbnailStoredAt?: number; // Epoch ms - sliding 30-day TTL
|
||||
url?: string; // For compatibility with existing components
|
||||
localFilePath?: string; // Original disk path (desktop) - persisted so recents stay disk-linked across reloads
|
||||
// Cached classification labels — mirrors the stub field so the sidebar can
|
||||
// group by label without re-reading PDF bytes, and it survives versioning.
|
||||
// See StirlingFileStub.classificationLabels.
|
||||
@@ -133,7 +132,6 @@ class FileStorageService {
|
||||
data: arrayBuffer,
|
||||
thumbnail: stub.thumbnailUrl,
|
||||
thumbnailStoredAt: stub.thumbnailUrl ? Date.now() : undefined,
|
||||
localFilePath: stub.localFilePath,
|
||||
isLeaf: stub.isLeaf ?? true,
|
||||
remoteStorageId: stub.remoteStorageId,
|
||||
remoteStorageUpdatedAt: stub.remoteStorageUpdatedAt,
|
||||
@@ -264,7 +262,6 @@ class FileStorageService {
|
||||
lastModified: record.lastModified,
|
||||
quickKey: record.quickKey,
|
||||
thumbnailUrl: fresh ? record.thumbnail : undefined,
|
||||
localFilePath: record.localFilePath,
|
||||
isLeaf: record.isLeaf,
|
||||
remoteStorageId: record.remoteStorageId,
|
||||
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
|
||||
@@ -325,7 +322,6 @@ class FileStorageService {
|
||||
lastModified: record.lastModified,
|
||||
quickKey: record.quickKey,
|
||||
thumbnailUrl: fresh ? record.thumbnail : undefined,
|
||||
localFilePath: record.localFilePath,
|
||||
isLeaf: record.isLeaf,
|
||||
remoteStorageId: record.remoteStorageId,
|
||||
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
|
||||
@@ -418,7 +414,6 @@ class FileStorageService {
|
||||
lastModified: record.lastModified,
|
||||
quickKey: record.quickKey,
|
||||
thumbnailUrl: fresh ? record.thumbnail : undefined,
|
||||
localFilePath: record.localFilePath,
|
||||
isLeaf: record.isLeaf,
|
||||
remoteStorageId: record.remoteStorageId,
|
||||
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
import type { StirlingFileStub } from "@app/types/fileContext";
|
||||
import type { FileId } from "@app/types/file";
|
||||
|
||||
// Controllable seam + storage doubles.
|
||||
const desktopFileLink = vi.hoisted(() => ({
|
||||
desktopFileLinkingSupported: true,
|
||||
pathExistsOnDisk: vi.fn<(path: string) => Promise<boolean>>(),
|
||||
}));
|
||||
const deleteMultipleStirlingFiles = vi.hoisted(() =>
|
||||
vi.fn<(ids: FileId[]) => Promise<void>>(),
|
||||
);
|
||||
const updateFileMetadata = vi.hoisted(() =>
|
||||
vi.fn<(id: FileId, updates: object) => Promise<boolean>>(),
|
||||
);
|
||||
|
||||
vi.mock("@app/services/desktopFileLink", () => desktopFileLink);
|
||||
vi.mock("@app/services/fileStorage", () => ({
|
||||
fileStorage: { deleteMultipleStirlingFiles, updateFileMetadata },
|
||||
}));
|
||||
|
||||
import {
|
||||
pruneMissingRecentFiles,
|
||||
reconcileServerBackedRecents,
|
||||
hasLocalRecord,
|
||||
} from "@app/services/pruneMissingRecentFiles";
|
||||
|
||||
const stub = (overrides: Partial<StirlingFileStub> = {}): StirlingFileStub => ({
|
||||
id: "file-1" as FileId,
|
||||
name: "report.pdf",
|
||||
type: "application/pdf",
|
||||
size: 1024,
|
||||
lastModified: 0,
|
||||
isLeaf: true,
|
||||
originalFileId: "file-1",
|
||||
versionNumber: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
desktopFileLink.desktopFileLinkingSupported = true;
|
||||
desktopFileLink.pathExistsOnDisk.mockReset().mockResolvedValue(true);
|
||||
deleteMultipleStirlingFiles.mockReset().mockResolvedValue(undefined);
|
||||
updateFileMetadata.mockReset().mockResolvedValue(true);
|
||||
});
|
||||
|
||||
describe("pruneMissingRecentFiles (local-only files)", () => {
|
||||
test("deletes a pristine local-only file whose disk file is gone", async () => {
|
||||
const gone = stub({ id: "gone" as FileId, localFilePath: "/tmp/gone.pdf" });
|
||||
const kept = stub({ id: "kept" as FileId, localFilePath: "/tmp/kept.pdf" });
|
||||
desktopFileLink.pathExistsOnDisk.mockImplementation(
|
||||
async (p) => p === "/tmp/kept.pdf",
|
||||
);
|
||||
|
||||
const result = await pruneMissingRecentFiles([gone, kept]);
|
||||
|
||||
expect(result.map((s) => s.id)).toEqual(["kept"]);
|
||||
expect(deleteMultipleStirlingFiles).toHaveBeenCalledWith(["gone"]);
|
||||
expect(updateFileMetadata).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("keeps in-app-edited local files but detaches the dead link", async () => {
|
||||
const dirty = stub({
|
||||
id: "dirty" as FileId,
|
||||
localFilePath: "/tmp/dirty.pdf",
|
||||
isDirty: true,
|
||||
});
|
||||
const edited = stub({
|
||||
id: "edited" as FileId,
|
||||
localFilePath: "/tmp/edited.pdf",
|
||||
versionNumber: 2,
|
||||
toolHistory: [{ toolId: "compress" as never, timestamp: 1 }],
|
||||
});
|
||||
desktopFileLink.pathExistsOnDisk.mockResolvedValue(false);
|
||||
|
||||
const result = await pruneMissingRecentFiles([dirty, edited]);
|
||||
|
||||
expect(result.map((s) => s.id).sort()).toEqual(["dirty", "edited"]);
|
||||
expect(result.every((s) => s.localFilePath === undefined)).toBe(true);
|
||||
expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
|
||||
expect(updateFileMetadata).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("leaves server-backed files untouched (handled after the server fetch)", async () => {
|
||||
const remote = stub({
|
||||
id: "remote" as FileId,
|
||||
localFilePath: "/tmp/remote.pdf",
|
||||
remoteStorageId: 7,
|
||||
});
|
||||
desktopFileLink.pathExistsOnDisk.mockResolvedValue(false);
|
||||
|
||||
const result = await pruneMissingRecentFiles([remote]);
|
||||
|
||||
expect(result).toEqual([remote]);
|
||||
expect(desktopFileLink.pathExistsOnDisk).not.toHaveBeenCalled();
|
||||
expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
|
||||
expect(updateFileMetadata).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("ignores files with no disk link (e.g. web/browser uploads)", async () => {
|
||||
const memoryOnly = stub({ id: "mem" as FileId });
|
||||
desktopFileLink.pathExistsOnDisk.mockResolvedValue(false);
|
||||
|
||||
const result = await pruneMissingRecentFiles([memoryOnly]);
|
||||
|
||||
expect(result).toEqual([memoryOnly]);
|
||||
expect(desktopFileLink.pathExistsOnDisk).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("is a no-op when desktop file linking is unsupported (web)", async () => {
|
||||
desktopFileLink.desktopFileLinkingSupported = false;
|
||||
const gone = stub({ id: "gone" as FileId, localFilePath: "/tmp/gone.pdf" });
|
||||
|
||||
const result = await pruneMissingRecentFiles([gone]);
|
||||
|
||||
expect(result).toEqual([gone]);
|
||||
expect(desktopFileLink.pathExistsOnDisk).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasLocalRecord (desktop recents = local/IndexedDB only)", () => {
|
||||
test("keeps files with a real local IndexedDB id", () => {
|
||||
expect(hasLocalRecord(stub({ id: "uuid-abc" as FileId }))).toBe(true);
|
||||
// A locally-stored file that is ALSO uploaded still has a local record.
|
||||
expect(
|
||||
hasLocalRecord(stub({ id: "uuid-abc" as FileId, remoteStorageId: 5 })),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("excludes ephemeral server-only and shared-only stubs", () => {
|
||||
expect(hasLocalRecord(stub({ id: "server-42" as FileId }))).toBe(false);
|
||||
expect(hasLocalRecord(stub({ id: "shared-tok" as FileId }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconcileServerBackedRecents (server-uploaded files)", () => {
|
||||
const serverHas = (ids: number[]) => (id: number) => ids.includes(id);
|
||||
|
||||
test("demotes a server-confirmed file whose disk original is gone", async () => {
|
||||
const s = stub({
|
||||
id: "s1" as FileId,
|
||||
localFilePath: "/tmp/s1.pdf",
|
||||
remoteStorageId: 42,
|
||||
});
|
||||
desktopFileLink.pathExistsOnDisk.mockResolvedValue(false);
|
||||
|
||||
const removed = await reconcileServerBackedRecents([s], serverHas([42]));
|
||||
|
||||
expect(removed).toEqual(["s1"]);
|
||||
// The local copy is removed; the file lives on as a pure server file.
|
||||
expect(deleteMultipleStirlingFiles).toHaveBeenCalledWith(["s1"]);
|
||||
});
|
||||
|
||||
test("does NOT demote when the server can't confirm the file (avoids data loss)", async () => {
|
||||
const s = stub({
|
||||
id: "s1" as FileId,
|
||||
localFilePath: "/tmp/s1.pdf",
|
||||
remoteStorageId: 42,
|
||||
});
|
||||
desktopFileLink.pathExistsOnDisk.mockResolvedValue(false);
|
||||
|
||||
const removed = await reconcileServerBackedRecents([s], serverHas([]));
|
||||
|
||||
expect(removed).toEqual([]);
|
||||
expect(desktopFileLink.pathExistsOnDisk).not.toHaveBeenCalled();
|
||||
expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does NOT demote a file with unsaved local edits", async () => {
|
||||
const s = stub({
|
||||
id: "s1" as FileId,
|
||||
localFilePath: "/tmp/s1.pdf",
|
||||
remoteStorageId: 42,
|
||||
isDirty: true,
|
||||
});
|
||||
desktopFileLink.pathExistsOnDisk.mockResolvedValue(false);
|
||||
|
||||
const removed = await reconcileServerBackedRecents([s], serverHas([42]));
|
||||
|
||||
expect(removed).toEqual([]);
|
||||
expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does NOT demote when the disk file still exists", async () => {
|
||||
const s = stub({
|
||||
id: "s1" as FileId,
|
||||
localFilePath: "/tmp/s1.pdf",
|
||||
remoteStorageId: 42,
|
||||
});
|
||||
desktopFileLink.pathExistsOnDisk.mockResolvedValue(true);
|
||||
|
||||
const removed = await reconcileServerBackedRecents([s], serverHas([42]));
|
||||
|
||||
expect(removed).toEqual([]);
|
||||
expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("is a no-op off desktop", async () => {
|
||||
desktopFileLink.desktopFileLinkingSupported = false;
|
||||
const s = stub({
|
||||
id: "s1" as FileId,
|
||||
localFilePath: "/tmp/s1.pdf",
|
||||
remoteStorageId: 42,
|
||||
});
|
||||
|
||||
const removed = await reconcileServerBackedRecents([s], serverHas([42]));
|
||||
|
||||
expect(removed).toEqual([]);
|
||||
expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
import { StirlingFileStub, FileId } from "@app/types/fileContext";
|
||||
import { fileStorage } from "@app/services/fileStorage";
|
||||
import {
|
||||
desktopFileLinkingSupported,
|
||||
pathExistsOnDisk,
|
||||
} from "@app/services/desktopFileLink";
|
||||
|
||||
/**
|
||||
* True for a recents entry backed by a real local IndexedDB record, false for
|
||||
* the ephemeral `server-`/`shared-` stubs synthesised from server storage (which
|
||||
* have no IDB row). Desktop recents show only files with a local record; the
|
||||
* server-only ones belong in the My Files view.
|
||||
*/
|
||||
export function hasLocalRecord(stub: StirlingFileStub): boolean {
|
||||
return !stub.id.startsWith("server-") && !stub.id.startsWith("shared-");
|
||||
}
|
||||
|
||||
/**
|
||||
* A local-only recent is a pristine passthrough of its disk file — identical
|
||||
* bytes on disk and in IndexedDB — only if it's a v1 with no in-app edits. When
|
||||
* its disk file disappears there's nothing unique to keep, so it's deleted.
|
||||
* Otherwise (unsaved edits, or a later/tool version) the IndexedDB copy may be
|
||||
* the only one left, so it's KEPT with just the dead disk link detached.
|
||||
*/
|
||||
function isPristineLocalPassthrough(stub: StirlingFileStub): boolean {
|
||||
return (
|
||||
!stub.isDirty &&
|
||||
(stub.versionNumber ?? 1) === 1 &&
|
||||
(stub.toolHistory?.length ?? 0) === 0
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile LOCAL-ONLY desktop recents against the disk files they link to.
|
||||
* Server-backed recents are intentionally left untouched here — they're handled
|
||||
* after the server fetch by {@link reconcileServerBackedRecents}, which can
|
||||
* confirm the file still exists remotely before dropping the local copy.
|
||||
*
|
||||
* For each local-only stub whose `localFilePath` no longer exists on disk:
|
||||
* - pristine passthrough → removed from recents + IndexedDB.
|
||||
* - edited / dirty → KEPT, dead `localFilePath` cleared (no broken "Show
|
||||
* in folder"; Ctrl+S falls back to Save As).
|
||||
* No-op off the desktop app.
|
||||
*/
|
||||
export async function pruneMissingRecentFiles(
|
||||
stubs: StirlingFileStub[],
|
||||
): Promise<StirlingFileStub[]> {
|
||||
if (!desktopFileLinkingSupported) return stubs;
|
||||
|
||||
const linked = stubs.filter(
|
||||
(stub) => stub.localFilePath && !stub.remoteStorageId,
|
||||
);
|
||||
if (linked.length === 0) return stubs;
|
||||
|
||||
const present = await Promise.all(
|
||||
linked.map((stub) => pathExistsOnDisk(stub.localFilePath!)),
|
||||
);
|
||||
|
||||
const toDelete: FileId[] = [];
|
||||
const toDetach: FileId[] = [];
|
||||
linked.forEach((stub, i) => {
|
||||
if (present[i]) return;
|
||||
if (isPristineLocalPassthrough(stub)) toDelete.push(stub.id);
|
||||
else toDetach.push(stub.id);
|
||||
});
|
||||
|
||||
if (toDelete.length === 0 && toDetach.length === 0) return stubs;
|
||||
|
||||
if (toDelete.length > 0) {
|
||||
try {
|
||||
await fileStorage.deleteMultipleStirlingFiles(toDelete);
|
||||
} catch (error) {
|
||||
console.error("[pruneMissingRecentFiles] delete failed:", error);
|
||||
}
|
||||
}
|
||||
if (toDetach.length > 0) {
|
||||
await Promise.all(
|
||||
toDetach.map((id) =>
|
||||
fileStorage
|
||||
.updateFileMetadata(id, { localFilePath: undefined })
|
||||
.catch((error) =>
|
||||
console.error("[pruneMissingRecentFiles] detach failed:", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const deleteSet = new Set<FileId>(toDelete);
|
||||
const detachSet = new Set<FileId>(toDetach);
|
||||
return stubs
|
||||
.filter((stub) => !deleteSet.has(stub.id))
|
||||
.map((stub) =>
|
||||
detachSet.has(stub.id) ? { ...stub, localFilePath: undefined } : stub,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* When a server-uploaded recent's local disk original has been deleted, drop its
|
||||
* LOCAL copy so the file becomes a pure server file: it leaves the (local)
|
||||
* recents but remains under My Files and stays downloadable from the server.
|
||||
* Only files the server CONFIRMS it still holds (via `serverHasFile`) and with
|
||||
* no unsaved local edits are demoted, so the last copy is never lost.
|
||||
*
|
||||
* Returns the deleted local ids so the caller can drop them from the list this
|
||||
* pass. No-op off the desktop app.
|
||||
*/
|
||||
export async function reconcileServerBackedRecents(
|
||||
stubs: StirlingFileStub[],
|
||||
serverHasFile: (remoteStorageId: number) => boolean,
|
||||
): Promise<FileId[]> {
|
||||
if (!desktopFileLinkingSupported) return [];
|
||||
|
||||
const candidates = stubs.filter(
|
||||
(stub) =>
|
||||
typeof stub.remoteStorageId === "number" &&
|
||||
serverHasFile(stub.remoteStorageId) &&
|
||||
stub.localFilePath &&
|
||||
!stub.isDirty,
|
||||
);
|
||||
if (candidates.length === 0) return [];
|
||||
|
||||
const present = await Promise.all(
|
||||
candidates.map((stub) => pathExistsOnDisk(stub.localFilePath!)),
|
||||
);
|
||||
const gone = candidates.filter((_, i) => !present[i]);
|
||||
if (gone.length === 0) return [];
|
||||
|
||||
const removedIds = gone.map((stub) => stub.id);
|
||||
try {
|
||||
await fileStorage.deleteMultipleStirlingFiles(removedIds);
|
||||
} catch (error) {
|
||||
// If we couldn't remove the local copy, don't drop it from the list either.
|
||||
console.error("[reconcileServerBackedRecents] delete failed:", error);
|
||||
return [];
|
||||
}
|
||||
|
||||
return removedIds;
|
||||
}
|
||||
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
|
||||
|
||||
const BASE_NO_LOGIN_CONFIG: AppConfig = {
|
||||
enableAnalytics: true,
|
||||
appVersion: "2.14.1",
|
||||
appVersion: "2.14.2",
|
||||
serverCertificateEnabled: false,
|
||||
enableAlphaFunctionality: false,
|
||||
serverPort: 8080,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useOpenedFile } from "@app/hooks/useOpenedFile";
|
||||
import { fileOpenService } from "@app/services/fileOpenService";
|
||||
import { fileStorage } from "@app/services/fileStorage";
|
||||
import { useFileManagement } from "@app/contexts/file/fileHooks";
|
||||
import { createQuickKey } from "@app/types/fileContext";
|
||||
|
||||
@@ -81,18 +80,12 @@ export function useAppInitialization(): void {
|
||||
);
|
||||
|
||||
const addedFiles = await addFiles(filesArray, { selectFiles: true });
|
||||
await Promise.all(
|
||||
addedFiles.map(async (file) => {
|
||||
const localFilePath = quickKeyToPath.get(file.quickKey);
|
||||
if (!localFilePath) return;
|
||||
addedFiles.forEach((file) => {
|
||||
const localFilePath = quickKeyToPath.get(file.quickKey);
|
||||
if (localFilePath) {
|
||||
updateStirlingFileStub(file.fileId, { localFilePath });
|
||||
// Persist too: addFiles stored the record before we knew the path,
|
||||
// so the disk link would otherwise be lost on reload.
|
||||
await fileStorage.updateFileMetadata(file.fileId, {
|
||||
localFilePath,
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
console.log(
|
||||
`[Desktop] ${loadedFiles.length} opened file(s) added to FileContext`,
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
|
||||
// Desktop implementation of the file-link seam. Overrides the core no-op in
|
||||
// desktop builds (see @app alias order) so recent files stay tied to disk.
|
||||
|
||||
export const desktopFileLinkingSupported = true;
|
||||
|
||||
// True if the path still exists on disk. On any error we assume it exists so a
|
||||
// transient failure never prunes a valid recent file.
|
||||
export async function pathExistsOnDisk(path: string): Promise<boolean> {
|
||||
if (!isTauri()) return true;
|
||||
try {
|
||||
return await invoke<boolean>("path_exists", { path });
|
||||
} catch (error) {
|
||||
console.error("[desktopFileLink] path_exists failed:", error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Reveal the file in Explorer/Finder, highlighting it.
|
||||
export async function revealPathInFileManager(path: string): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
try {
|
||||
await invoke("reveal_in_file_manager", { path });
|
||||
} catch (error) {
|
||||
console.error("[desktopFileLink] reveal_in_file_manager failed:", error);
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
import "fake-indexeddb/auto";
|
||||
|
||||
// Stub ONLY the Tauri OS boundary. Everything below (real fileStorage on a real
|
||||
// IndexedDB, the real desktop desktopFileLink seam, the real pruner) runs for
|
||||
// real, so this exercises the full disk-linked-recents chain end to end.
|
||||
const { existsByPath, invoke } = vi.hoisted(() => ({
|
||||
existsByPath: new Map<string, boolean>(),
|
||||
invoke: vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
|
||||
if (cmd === "path_exists") {
|
||||
return existsByPath.get(args?.path as string) ?? false;
|
||||
}
|
||||
throw new Error(`unexpected command ${cmd}`);
|
||||
}),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/core", async (importActual) => {
|
||||
const actual = await importActual<typeof import("@tauri-apps/api/core")>();
|
||||
return { ...actual, isTauri: () => true, invoke };
|
||||
});
|
||||
|
||||
import { fileStorage } from "@app/services/fileStorage";
|
||||
import {
|
||||
pruneMissingRecentFiles,
|
||||
reconcileServerBackedRecents,
|
||||
} from "@app/services/pruneMissingRecentFiles";
|
||||
import {
|
||||
createStirlingFile,
|
||||
type StirlingFileStub,
|
||||
} from "@app/types/fileContext";
|
||||
import type { FileId } from "@app/types/file";
|
||||
|
||||
async function storeFile(
|
||||
id: string,
|
||||
overrides: Partial<StirlingFileStub> = {},
|
||||
): Promise<void> {
|
||||
const file = new File([`data-${id}`], `${id}.pdf`, {
|
||||
type: "application/pdf",
|
||||
});
|
||||
const stirlingFile = createStirlingFile(file, id as FileId);
|
||||
const stub: StirlingFileStub = {
|
||||
id: id as FileId,
|
||||
name: `${id}.pdf`,
|
||||
type: "application/pdf",
|
||||
size: file.size,
|
||||
lastModified: 0,
|
||||
quickKey: stirlingFile.quickKey,
|
||||
isLeaf: true,
|
||||
originalFileId: id,
|
||||
versionNumber: 1,
|
||||
...overrides,
|
||||
};
|
||||
await fileStorage.storeStirlingFile(stirlingFile, stub);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
existsByPath.clear();
|
||||
invoke.mockClear();
|
||||
// fake-indexeddb persists within a run; wipe the store for test isolation.
|
||||
const all = await fileStorage.getAllStirlingFileStubs();
|
||||
if (all.length > 0) {
|
||||
await fileStorage.deleteMultipleStirlingFiles(all.map((s) => s.id));
|
||||
}
|
||||
});
|
||||
|
||||
describe("desktop recent files ↔ disk link (real storage + seam)", () => {
|
||||
test("localFilePath round-trips through IndexedDB", async () => {
|
||||
await storeFile("rt", { localFilePath: "/docs/rt.pdf" });
|
||||
|
||||
const stubs = await fileStorage.getLeafStirlingFileStubs();
|
||||
const loaded = stubs.find((s) => s.id === "rt");
|
||||
|
||||
// Regression: before persisting localFilePath in the record, this was
|
||||
// undefined after a reload and the whole feature was inert.
|
||||
expect(loaded?.localFilePath).toBe("/docs/rt.pdf");
|
||||
});
|
||||
|
||||
test("localFilePath applied post-store (OS open-with / drag-drop path) persists", async () => {
|
||||
// useAppInitialization stores the opened file first, then applies the disk
|
||||
// path via updateFileMetadata — this is the drag-drop / "open with" path.
|
||||
await storeFile("dragged");
|
||||
await fileStorage.updateFileMetadata("dragged" as FileId, {
|
||||
localFilePath: "/docs/dragged.pdf",
|
||||
});
|
||||
|
||||
const stubs = await fileStorage.getLeafStirlingFileStubs();
|
||||
expect(stubs.find((s) => s.id === "dragged")?.localFilePath).toBe(
|
||||
"/docs/dragged.pdf",
|
||||
);
|
||||
});
|
||||
|
||||
test("prunes a recent whose disk file is gone and deletes it from storage", async () => {
|
||||
await storeFile("gone", { localFilePath: "/docs/gone.pdf" });
|
||||
await storeFile("kept", { localFilePath: "/docs/kept.pdf" });
|
||||
existsByPath.set("/docs/gone.pdf", false);
|
||||
existsByPath.set("/docs/kept.pdf", true);
|
||||
|
||||
const stubs = await fileStorage.getLeafStirlingFileStubs();
|
||||
const survivors = await pruneMissingRecentFiles(stubs);
|
||||
|
||||
expect(survivors.map((s) => s.id).sort()).toEqual(["kept"]);
|
||||
// Really removed from IndexedDB, not just filtered from the array.
|
||||
expect(await fileStorage.getStirlingFileStub("gone" as FileId)).toBeNull();
|
||||
expect(
|
||||
await fileStorage.getStirlingFileStub("kept" as FileId),
|
||||
).not.toBeNull();
|
||||
expect(invoke).toHaveBeenCalledWith("path_exists", {
|
||||
path: "/docs/gone.pdf",
|
||||
});
|
||||
});
|
||||
|
||||
test("prune leaves server-backed files alone (server reconciliation owns them)", async () => {
|
||||
await storeFile("onserver", {
|
||||
localFilePath: "/docs/onserver.pdf",
|
||||
remoteStorageId: 42,
|
||||
});
|
||||
existsByPath.set("/docs/onserver.pdf", false);
|
||||
|
||||
const survivors = await pruneMissingRecentFiles(
|
||||
await fileStorage.getLeafStirlingFileStubs(),
|
||||
);
|
||||
|
||||
// Untouched by the pre-fetch prune: still present, link intact.
|
||||
expect(survivors.find((s) => s.id === "onserver")?.localFilePath).toBe(
|
||||
"/docs/onserver.pdf",
|
||||
);
|
||||
expect(
|
||||
await fileStorage.getStirlingFileStub("onserver" as FileId),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
test("demotes a server-confirmed file whose disk original is gone (removed locally, kept on server)", async () => {
|
||||
await storeFile("onserver", {
|
||||
localFilePath: "/docs/onserver.pdf",
|
||||
remoteStorageId: 42,
|
||||
});
|
||||
existsByPath.set("/docs/onserver.pdf", false);
|
||||
|
||||
const removed = await reconcileServerBackedRecents(
|
||||
await fileStorage.getLeafStirlingFileStubs(),
|
||||
(id) => id === 42, // server confirms it holds file 42
|
||||
);
|
||||
|
||||
expect(removed).toEqual(["onserver"]);
|
||||
// Local copy really removed from IndexedDB — it becomes a pure server file
|
||||
// (shown under My Files, downloadable), so nothing is lost.
|
||||
expect(
|
||||
await fileStorage.getStirlingFileStub("onserver" as FileId),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("does NOT demote a server-backed file the server can't confirm (no data loss)", async () => {
|
||||
await storeFile("stale", {
|
||||
localFilePath: "/docs/stale.pdf",
|
||||
remoteStorageId: 99,
|
||||
});
|
||||
existsByPath.set("/docs/stale.pdf", false);
|
||||
|
||||
const removed = await reconcileServerBackedRecents(
|
||||
await fileStorage.getLeafStirlingFileStubs(),
|
||||
() => false, // server no longer has it
|
||||
);
|
||||
|
||||
expect(removed).toEqual([]);
|
||||
// Local copy preserved — it may be the only remaining copy.
|
||||
expect(
|
||||
await fileStorage.getStirlingFileStub("stale" as FileId),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
test("keeps an in-app-edited file whose disk path is gone, detaching the dead link", async () => {
|
||||
// A v2 with tool history: its edited bytes live only in IndexedDB once the
|
||||
// disk file is gone, so it must be KEPT (not deleted) — just detached.
|
||||
await storeFile("edited", {
|
||||
localFilePath: "/docs/edited.pdf",
|
||||
versionNumber: 2,
|
||||
toolHistory: [{ toolId: "compress" as never, timestamp: 1 }],
|
||||
});
|
||||
existsByPath.set("/docs/edited.pdf", false);
|
||||
|
||||
const survivors = await pruneMissingRecentFiles(
|
||||
await fileStorage.getLeafStirlingFileStubs(),
|
||||
);
|
||||
|
||||
expect(survivors.some((s) => s.id === "edited")).toBe(true);
|
||||
const stored = await fileStorage.getStirlingFileStub("edited" as FileId);
|
||||
expect(stored).not.toBeNull();
|
||||
expect(stored?.localFilePath).toBeUndefined();
|
||||
});
|
||||
|
||||
test("leaves web/browser-uploaded files (no disk link) untouched", async () => {
|
||||
// Files added via the <input type=file> fallback have no localFilePath, so
|
||||
// they are never disk-checked, detached, or pruned.
|
||||
await storeFile("weblink");
|
||||
existsByPath.set("/docs/anything.pdf", false);
|
||||
|
||||
const survivors = await pruneMissingRecentFiles(
|
||||
await fileStorage.getLeafStirlingFileStubs(),
|
||||
);
|
||||
|
||||
expect(survivors.some((s) => s.id === "weblink")).toBe(true);
|
||||
expect(
|
||||
await fileStorage.getStirlingFileStub("weblink" as FileId),
|
||||
).not.toBeNull();
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -48,7 +48,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
|
||||
|
||||
const BASE_NO_LOGIN_CONFIG: AppConfig = {
|
||||
enableAnalytics: true,
|
||||
appVersion: "2.14.1",
|
||||
appVersion: "2.14.2",
|
||||
serverCertificateEnabled: false,
|
||||
enableAlphaFunctionality: false,
|
||||
enableDesktopInstallSlide: true,
|
||||
|
||||
Reference in New Issue
Block a user