Compare commits

..
154 changed files with 6237 additions and 5742 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
pkgname=stirling-pdf-desktop
pkgver=2.14.2
pkgver=2.14.1
pkgrel=1
pkgdesc="Locally hosted, web-based PDF manipulation tool (Tauri desktop app, official Stirling PDF Inc build)"
arch=('x86_64')
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: Stirling PDF Inc <contact@stirlingpdf.com>
pkgname=stirling-pdf-server-bin
pkgver=2.14.2
pkgver=2.14.1
pkgrel=1
pkgdesc="Locally hosted, web-based PDF manipulation tool (server JAR, prebuilt)"
arch=('any')
+6 -23
View File
@@ -510,7 +510,6 @@ 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
@@ -532,26 +531,11 @@ 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 }
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 {
$proc = Start-Process msiexec.exe -ArgumentList '/a', $msi, '/qn', "TARGETDIR=$extractDir" -Wait -PassThru -NoNewWindow
if ($proc.ExitCode -eq 0) {
$innerExe = Get-ChildItem -Path $extractDir -Filter "stirling-pdf.exe" -Recurse -File | Select-Object -First 1
if ($innerExe) {
$sig = Get-AuthenticodeSignature -FilePath $innerExe.FullName
@@ -564,6 +548,9 @@ 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) {
@@ -813,11 +800,7 @@ jobs:
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
with:
tag_name: v${{ needs.determine-matrix.outputs.version }}
# 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
generate_release_notes: true
fail_on_unmatched_files: true
# Installers + updater payloads + manifest. .sig contents are embedded
# in latest.json so the .sig files themselves are not uploaded.
+92
View File
@@ -0,0 +1,92 @@
name: Sync Portal Docs
# Regenerates the portal Developer Docs manifest from the Stirling docs repo and
# opens a PR when it changes. Runs weekly, on manual dispatch, or when the docs
# repo fires a `docs-updated` repository_dispatch.
on:
schedule:
- cron: "0 6 * * 1"
workflow_dispatch:
inputs:
ref:
description: "Docs repo ref (branch or tag) to sync from"
required: false
default: "main"
repository_dispatch:
types: [docs-updated]
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: true
permissions:
contents: read
jobs:
sync:
name: Sync docs manifest
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
pull-requests: write
steps:
- name: Harden Runner
uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 # v2.19.3
with:
egress-policy: audit
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
persist-credentials: false
- name: Setup GitHub App Bot
id: setup-bot
uses: ./.github/actions/setup-bot
with:
app-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
- name: Set up Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: "22"
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
working-directory: frontend
env:
NPM_CONFIG_IGNORE_SCRIPTS: "true"
run: npm ci --ignore-scripts --audit=false --fund=false
- name: Regenerate docs manifest
working-directory: frontend
env:
DOCS_REF: ${{ github.event.inputs.ref || github.event.client_payload.ref || 'main' }}
GITHUB_TOKEN: ${{ steps.setup-bot.outputs.token }}
run: npm run docs:sync
- name: Create Pull Request
id: cpr
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
with:
token: ${{ steps.setup-bot.outputs.token }}
commit-message: "Sync portal docs from docs repo"
committer: ${{ steps.setup-bot.outputs.committer }}
author: ${{ steps.setup-bot.outputs.committer }}
signoff: true
branch: sync-portal-docs
base: main
title: "Sync portal docs from docs repo"
body: |
Auto-generated by ${{ steps.setup-bot.outputs.app-slug }}[bot].
Regenerates `frontend/editor/src/portal/generated/docsManifest.json`
from the Stirling docs repo via `npm run docs:sync`.
labels: documentation,github-actions,frontend
add-paths: frontend/editor/src/portal/generated/docsManifest.json
delete-branch: true
sign-commits: true
@@ -4,8 +4,6 @@ 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;
@@ -49,9 +47,6 @@ 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
*
@@ -166,16 +161,4 @@ 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,18 +230,6 @@ 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
*
@@ -390,7 +378,7 @@ public class TaskManager {
fileIds.add(rf.getFileId());
}
}
Map<String, String> meta = new HashMap<>(result.getMetadata());
Map<String, String> meta = new HashMap<>();
if (result.getNotes() != null && !result.getNotes().isEmpty()) {
meta.put("notesCount", Integer.toString(result.getNotes().size()));
}
@@ -144,10 +144,8 @@ public class TempFileCleanupService {
int directoriesDeletedCount = 0;
for (Path directory : registry.getTempDirectories()) {
try {
if (Files.exists(directory)
&& shouldDeleteRegisteredDirectory(directory, maxAgeMillis)) {
if (Files.exists(directory)) {
GeneralUtils.deleteDirectory(directory);
registry.unregisterDirectory(directory);
directoriesDeletedCount++;
log.debug("Cleaned up temporary directory: {}", directory);
}
@@ -277,21 +275,6 @@ public class TempFileCleanupService {
return totalDeletedCount.get();
}
private boolean shouldDeleteRegisteredDirectory(Path directory, long maxAgeMillis) {
if (maxAgeMillis <= 0) {
return true;
}
try {
long currentTime = System.currentTimeMillis();
long lastModified = Files.getLastModifiedTime(directory).toMillis();
return (currentTime - lastModified) > maxAgeMillis;
} catch (IOException e) {
log.debug("Could not check directory age, skipping cleanup: {}", directory, e);
return false;
}
}
/** Get the system temp directory path based on configuration or system property. */
private Path getSystemTempPath() {
String systemTempDir =
@@ -155,7 +155,6 @@ public class TempFileManager {
if (directory != null && Files.isDirectory(directory)) {
try {
GeneralUtils.deleteDirectory(directory);
registry.unregisterDirectory(directory);
log.debug("Deleted temp directory: {}", directory.toString());
} catch (IOException e) {
log.warn("Failed to delete temp directory: {}", directory.toString(), e);
@@ -85,18 +85,6 @@ public class TempFileRegistry {
return directory;
}
/**
* Unregister a temporary directory from the registry.
*
* @param directory The directory to unregister
*/
public void unregisterDirectory(Path directory) {
if (directory != null) {
tempDirectories.remove(directory);
log.debug("Unregistered temp directory: {}", directory.toString());
}
}
/**
* Register a third-party temporary file that requires special handling.
*
@@ -176,13 +176,11 @@ class TempFileCleanupServiceMoreTest {
class ScheduledCleanup {
@Test
@DisplayName("deletes stale registered temp directories and reports counts")
@DisplayName("deletes registered temp directories and reports counts")
void deletesRegisteredDirectories() throws IOException {
when(tempFileManager.cleanupOldTempFiles(anyLong())).thenReturn(2);
Path regDir = Files.createDirectories(tempDir.resolve("registeredDir"));
Files.createFile(regDir.resolve("inside.txt"));
Files.setLastModifiedTime(
regDir, FileTime.fromMillis(System.currentTimeMillis() - 2L * 60 * 60 * 1000));
Set<Path> dirs = new HashSet<>();
dirs.add(regDir);
when(registry.getTempDirectories()).thenReturn(dirs);
@@ -195,22 +193,6 @@ class TempFileCleanupServiceMoreTest {
verify(tempFileManager).cleanupOldTempFiles(anyLong());
}
@Test
@DisplayName("keeps a fresh registered temp directory")
void keepsFreshRegisteredDirectory() throws IOException {
when(tempFileManager.cleanupOldTempFiles(anyLong())).thenReturn(0);
Path regDir = Files.createDirectories(tempDir.resolve("freshRegisteredDir"));
Files.createFile(regDir.resolve("inside.txt"));
Set<Path> dirs = new HashSet<>();
dirs.add(regDir);
when(registry.getTempDirectories()).thenReturn(dirs);
lenient().when(registry.contains(any(File.class))).thenReturn(false);
withIsolatedUserHome(cleanupService::scheduledCleanup);
assertThat(Files.exists(regDir)).isTrue();
}
@Test
@DisplayName("skips a registered directory that no longer exists")
void skipsMissingRegisteredDirectory() {
@@ -96,8 +96,7 @@ 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.
# 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
spring.autoconfigure.exclude=org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration,org.springframework.boot.data.redis.autoconfigure.DataRedisReactiveAutoConfiguration
# Set up a consistent temporary directory location
java.io.tmpdir=${stirling.tempfiles.directory:${java.io.tmpdir}/stirling-pdf}
@@ -44,13 +44,10 @@ 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("${cluster.enabled:false}") boolean clusterEnabled) {
@Value("${stirling.security.credentialEncryptionKey:}") String configuredKey) {
this.configuredKey = configuredKey;
this.clusterEnabled = clusterEnabled;
}
@PostConstruct
@@ -67,14 +64,6 @@ 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();
}
@@ -43,10 +43,6 @@ public class IntegrationConfigService {
private final OwnershipService ownership;
private final SecretMasker secretMasker;
private final ResourceGrantRepository grantRepository;
// Bean-discovered extension points: features that understand a type contribute its config
// schema and report what still references a config, without this module depending on them.
private final List<IntegrationConfigValidator> validators;
private final List<IntegrationConfigUsageCheck> usageChecks;
// ---- commands ----
@@ -70,21 +66,13 @@ public class IntegrationConfigService {
? DefaultAccessPolicy.EXPLICIT_ONLY
: request.defaultAccess());
// TEAM scope may omit the team id: default to the caller's own team so clients (the
// portal) need not know it. assignOwnership still enforces admin-or-leader of that team.
Long ownerTeamId = request.ownerTeamId();
if (ownerTeamId == null && scope == OwnerScope.TEAM && currentUser.getTeam() != null) {
ownerTeamId = currentUser.getTeam().getId();
}
ownership.assignOwnership(
cfg,
scope,
ownerTeamId,
request.ownerTeamId(),
currentUser,
() -> lockedServerExists(cfg.getIntegrationType()));
Map<String, Object> config = secretMasker.sanitize(request.config());
validateConfig(cfg.getIntegrationType(), config);
cfg.setConfig(writeJson(config));
cfg.setConfig(writeJson(secretMasker.sanitize(request.config())));
return repository.save(cfg);
}
@@ -113,10 +101,8 @@ public class IntegrationConfigService {
cfg.setDefaultAccess(request.defaultAccess());
}
if (request.config() != null) {
Map<String, Object> merged =
secretMasker.merge(readJson(cfg.getConfig()), request.config());
validateConfig(cfg.getIntegrationType(), merged);
cfg.setConfig(writeJson(merged));
cfg.setConfig(
writeJson(secretMasker.merge(readJson(cfg.getConfig()), request.config())));
}
return repository.save(cfg);
}
@@ -127,15 +113,6 @@ public class IntegrationConfigService {
if (!ownership.canManage(TYPE, cfg, currentUser)) {
throw forbidden("You cannot manage this integration");
}
// Refuse to pull a connection out from under whatever still references it.
List<String> usages =
usageChecks.stream()
.flatMap(check -> check.usagesOf(cfg.getId()).stream())
.toList();
if (!usages.isEmpty()) {
throw new ResponseStatusException(
HttpStatus.CONFLICT, "Integration is in use by: " + String.join(", ", usages));
}
// Drop grants sharing this config so they do not dangle as dead rows.
grantRepository.deleteByResourceTypeAndResourceId(TYPE, String.valueOf(cfg.getId()));
repository.delete(cfg);
@@ -211,19 +188,6 @@ public class IntegrationConfigService {
// ---- integration-specific glue ----
/** Runs every registered validator for the type; unknown types save free-form. */
private void validateConfig(IntegrationType type, Map<String, Object> config) {
for (IntegrationConfigValidator validator : validators) {
if (validator.type() == type) {
try {
validator.validate(config == null ? Map.of() : config);
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
}
}
}
/** A non-admin can't create a personal config of a type an admin has locked at server scope. */
private boolean lockedServerExists(IntegrationType type) {
return repository.findByScope(OwnerScope.SERVER).stream()
@@ -1,15 +0,0 @@
package stirling.software.proprietary.integration.service;
import java.util.List;
/**
* Reports what still references an integration config, so deletion can be refused instead of
* pulling a connection out from under a live consumer. Implementations are beans discovered by
* {@link IntegrationConfigService} (e.g. the policy subsystem reporting sources and pipelines that
* reference a connection).
*/
public interface IntegrationConfigUsageCheck {
/** Human-readable labels of everything still using the config; empty when unreferenced. */
List<String> usagesOf(long configId);
}
@@ -1,23 +0,0 @@
package stirling.software.proprietary.integration.service;
import java.util.Map;
import stirling.software.proprietary.integration.model.IntegrationType;
/**
* Validates one integration type's config map at save time. Implementations are beans discovered by
* {@link IntegrationConfigService}, so the feature that understands a type (e.g. the policy S3
* backend) owns its schema without the integration module depending on it. Types with no registered
* validator save free-form.
*/
public interface IntegrationConfigValidator {
/** The type this validator understands. */
IntegrationType type();
/**
* Validates the config as it will be stored (secrets already sanitized/merged, so values are
* real, never the redaction mask). Throws {@link IllegalArgumentException} on bad config.
*/
void validate(Map<String, Object> config);
}
@@ -6,7 +6,6 @@ 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;
@@ -41,8 +40,6 @@ 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;
@@ -107,8 +104,6 @@ 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(
@@ -125,7 +120,6 @@ public class PolicyController {
throws IOException {
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocOutput(definition);
PolicyInputs inputs = toInputs(files);
PolicyRunHandle handle =
policyRunner.runAdHoc(definition, inputs, PolicyProgressListener.NOOP);
@@ -146,7 +140,6 @@ public class PolicyController {
throws IOException {
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocOutput(definition);
PolicyInputs inputs = toInputs(files);
SseEmitter emitter =
@@ -179,19 +172,10 @@ 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.ok(PolicyRunView.of(run));
if (run == null) {
return ResponseEntity.notFound().build();
}
// 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();
return ResponseEntity.ok(PolicyRunView.of(run));
}
@GetMapping("/runs")
@@ -204,26 +188,11 @@ public class PolicyController {
+ " collected, rather than orphaned on the backend. Ad-hoc runs (no"
+ " policy id) are excluded.")
public List<PolicyRunView> listRuns() {
// Local runs first (they carry live step state); keyed by runId to dedupe shared entries.
Map<String, PolicyRunView> byRunId = new LinkedHashMap<>();
runRegistry.all().stream()
return runRegistry.all().stream()
.filter(run -> run.getPolicyId() != null)
.filter(run -> ownedByCurrentUser(run.getRunId()))
.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());
.map(PolicyRunView::of)
.toList();
}
/**
@@ -561,24 +530,6 @@ public class PolicyController {
}
}
/**
* Authorization-check an ad-hoc run's output while the caller's principal is present (this
* request thread). The worker thread that later delivers carries no security context, so an S3
* output's connection-access check would be skipped there; without this gate a caller could
* reference another tenant's connection by id and write to it (confused deputy). Stored
* policies are covered by save-time {@link PolicyValidator#validate} instead.
*/
private void validateAdHocOutput(PipelineDefinition definition) {
if (definition.output() == null) {
return;
}
try {
policyValidator.validateOutput(definition.output());
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
}
/**
* Ad-hoc runs (AI / one-off pipelines) are still editor activity, so their supplied documents
* feed the same virtual editor source as stored editor policies, counted against the caller's
@@ -136,10 +136,6 @@ 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<>();
@@ -52,19 +52,7 @@ public class PolicyValidator {
InputSpec spec = source.toInputSpec();
inputSourceFor(spec).validate(spec);
}
validateOutput(policy.output());
}
/**
* Validate an output spec against its sink. Must be called on a request thread (caller's
* principal present) so an S3 output's connection is authorization-checked against the caller -
* ad-hoc runs are never persisted and so never hit {@link #validate(Policy)}, and the worker
* thread that later delivers has no principal, so this is their only access gate.
*
* @throws IllegalArgumentException if the type is unknown or the config is invalid/inaccessible
*/
public void validateOutput(OutputSpec output) {
outputSinkFor(output).validate(output);
outputSinkFor(policy.output()).validate(policy.output());
}
private PolicyTrigger triggerFor(TriggerConfig config) {
@@ -18,7 +18,6 @@ import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.s3.S3Config;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3ConnectionResolver;
import stirling.software.proprietary.policy.s3.S3Identities;
import software.amazon.awssdk.core.exception.SdkException;
@@ -37,14 +36,15 @@ import software.amazon.awssdk.services.s3.model.S3Object;
* Reads input files from an Amazon S3 (or S3-compatible) bucket; each listed object is its own unit
* of work, claimed through the {@link ResolveContext} ledger and tracked in place. Identity and
* version gate come from {@link S3Identities}, so the steady-state sweep never downloads content.
* Options: "connectionId" references the stored S3 connection (an {@code IntegrationConfig} owning
* bucket, region, endpoint, and credentials - resolved by {@link S3ConnectionResolver}); "prefix"
* (only keys starting with it are read) and "mode" are per-source, where mode is "consume"
* (default: a processed object is deleted once every policy that claimed it has settled
* successfully and it is still the version that ran; failures stay in place and are not retried
* until they change) or "snapshot" (stateless, every run sees the full set). Keys ending in "/"
* (folder placeholders) and keys with a dot-prefixed path segment are never picked up, mirroring
* the folder source's hidden-file rule.
* Options (see {@link S3Config}): "bucket" (required), "region" (default us-east-1), "prefix" (only
* keys starting with it are read), "endpoint" (S3-compatible stores such as MinIO; path-style
* addressing is used automatically), "accessKeyId" and "secretAccessKey" (required; requests are
* never signed with the server's own AWS identity), and "mode" which is "consume" (default: a
* processed object is deleted once every policy that claimed it has settled successfully and it is
* still the version that ran; failures stay in place and are not retried until they change) or
* "snapshot" (stateless, every run sees the full set). Keys ending in "/" (folder placeholders) and
* keys with a dot-prefixed path segment are never picked up, mirroring the folder source's
* hidden-file rule.
*/
@Slf4j
@Service
@@ -55,7 +55,6 @@ public class S3InputSource implements InputSource {
private static final String TYPE = "s3";
private final S3ConnectionPool connectionPool;
private final S3ConnectionResolver connectionResolver;
@Override
public String type() {
@@ -68,12 +67,12 @@ public class S3InputSource implements InputSource {
}
/**
* Fails fast at save time: an unknown/disabled/unusable connection, bad config shape, a private
* endpoint without the operator opt-in, or a bucket the connection cannot list.
* Fails fast at save time: bad config shape, a private endpoint without the operator opt-in, or
* a bucket the supplied credentials cannot list.
*/
@Override
public void validate(InputSpec spec) {
S3Config config = connectionResolver.resolve(spec.options());
S3Config config = S3Config.from(spec.options());
try {
connectionPool.clientFor(config).listObjectsV2(listRequest(config).maxKeys(1).build());
} catch (SdkException e) {
@@ -90,7 +89,7 @@ public class S3InputSource implements InputSource {
@Override
public List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {
S3Config config = connectionResolver.resolve(spec.options());
S3Config config = S3Config.from(spec.options());
S3Client client = connectionPool.clientFor(config);
// A listing failure propagates so the sweep reads it as "could not list" (which vetoes
// presence cleanup), never as "verifiably no objects".
@@ -1,9 +1,7 @@
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;
/**
@@ -36,33 +34,4 @@ 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);
}
}
@@ -27,7 +27,6 @@ import stirling.software.proprietary.policy.ledger.ProcessedLedger;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.s3.S3Config;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3ConnectionResolver;
import stirling.software.proprietary.policy.s3.S3Identities;
import software.amazon.awssdk.core.exception.SdkException;
@@ -60,7 +59,6 @@ public class S3OutputSink implements PolicyOutputSink {
private static final String TYPE = "s3";
private final S3ConnectionPool connectionPool;
private final S3ConnectionResolver connectionResolver;
private final ProcessedLedger processedLedger;
@Override
@@ -74,19 +72,19 @@ public class S3OutputSink implements PolicyOutputSink {
}
/**
* Connection resolution (including the saving user's right to use it) and endpoint guard only -
* no network probe, since write-only credentials (s3:PutObject without s3:ListBucket) are a
* legitimate setup for an output bucket and a listing probe would wrongly reject them.
* Config shape and endpoint guard only - no network probe, since write-only credentials
* (s3:PutObject without s3:ListBucket) are a legitimate setup for an output bucket and a
* listing probe would wrongly reject them.
*/
@Override
public void validate(OutputSpec spec) {
connectionPool.clientFor(connectionResolver.resolve(spec.options()));
connectionPool.clientFor(S3Config.from(spec.options()));
}
@Override
public List<ResultFile> deliver(
OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) throws IOException {
S3Config config = connectionResolver.resolve(spec.options());
S3Config config = S3Config.from(spec.options());
S3Client client = connectionPool.clientFor(config);
List<ResultFile> results = new ArrayList<>();
@@ -1,212 +0,0 @@
package stirling.software.proprietary.policy.s3;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
import stirling.software.proprietary.access.model.OwnerScope;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.source.SourceStore;
import stirling.software.proprietary.policy.store.PolicyStore;
import stirling.software.proprietary.security.repository.TeamRepository;
import tools.jackson.databind.ObjectMapper;
/**
* One-time, idempotent extraction of legacy embedded S3 credentials into stored connections:
* sources and policy outputs written before connections shipped carry bucket/credentials in their
* own options; this rewrites each to reference a (deduplicated) S3 {@link IntegrationConfig} and
* keeps only per-use options (prefix, mode). MUST be programmatic - the option JSON is encrypted at
* the application layer, so no SQL migration can read it.
*
* <p>Idempotent by construction: rewritten rows no longer embed credentials, so re-runs find
* nothing to do. Connections are deduplicated against both this run's extractions and existing S3
* connections; a concurrent multi-node boot can at worst create a redundant connection row, never
* corrupt a source. Ownership follows the owning row: team-scoped when the source/policy has a
* team, server-scoped otherwise (single-operator self-hosted).
*/
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class EmbeddedS3CredentialMigration {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final List<String> CONNECTION_OPTIONS =
List.of("bucket", "region", "endpoint", "accessKeyId", "secretAccessKey");
// Field separator for the dedup key: a unit-separator control char that cannot appear in a
// bucket/region/endpoint/credential, so distinct field sets can never collide.
private static final char DELIMITER = '\u001f';
private final SourceStore sourceStore;
private final PolicyStore policyStore;
private final IntegrationConfigRepository connections;
private final TeamRepository teamRepository;
@EventListener(ApplicationReadyEvent.class)
@Transactional
public void migrate() {
Map<String, IntegrationConfig> byCredentialKey = indexExistingConnections();
int migrated = 0;
for (Source source : sourceStore.all()) {
if (!"s3".equals(source.type()) || !embedsCredentials(source.options())) {
continue;
}
IntegrationConfig connection =
connectionFor(source.options(), source.teamId(), byCredentialKey);
sourceStore.save(withOptions(source, referencing(connection, source.options(), true)));
migrated++;
}
for (Policy policy : policyStore.all()) {
OutputSpec output = policy.output();
if (!"s3".equals(output.type()) || !embedsCredentials(output.options())) {
continue;
}
IntegrationConfig connection =
connectionFor(output.options(), policy.teamId(), byCredentialKey);
policyStore.save(
withOutput(
policy,
new OutputSpec(
output.type(),
referencing(connection, output.options(), false))));
migrated++;
}
if (migrated > 0) {
log.info("Extracted embedded S3 credentials from {} row(s) into connections", migrated);
}
}
private static boolean embedsCredentials(Map<String, Object> options) {
return options.get("accessKeyId") != null;
}
/** Reuses an existing connection with identical coordinates+credentials, else creates one. */
private IntegrationConfig connectionFor(
Map<String, Object> options, Long teamId, Map<String, IntegrationConfig> byKey) {
String key = credentialKey(options);
IntegrationConfig existing = byKey.get(key);
if (existing != null) {
return existing;
}
IntegrationConfig connection = new IntegrationConfig();
connection.setIntegrationType(IntegrationType.S3);
connection.setName(connectionName(options, byKey));
connection.setEnabled(true);
connection.setLocked(false);
connection.setDefaultAccess(DefaultAccessPolicy.EXPLICIT_ONLY);
Team team = teamId == null ? null : teamRepository.findById(teamId).orElse(null);
if (team != null) {
connection.setScope(OwnerScope.TEAM);
connection.setOwnerTeam(team);
} else {
// No team (teamless self-hosted, or a source whose team was since deleted): server
// scope, i.e. admin-owned. An orphaned-team source's non-admin editor would then need
// an admin to re-share the connection - acceptable for the narrow orphaned case.
connection.setScope(OwnerScope.SERVER);
}
Map<String, Object> config = new LinkedHashMap<>();
for (String option : CONNECTION_OPTIONS) {
Object value = options.get(option);
if (value != null && !value.toString().isBlank()) {
config.put(option, value);
}
}
connection.setConfig(OBJECT_MAPPER.writeValueAsString(config));
IntegrationConfig saved = connections.save(connection);
byKey.put(key, saved);
return saved;
}
/** The rewritten options: the connection reference plus per-use settings only. */
private static Map<String, Object> referencing(
IntegrationConfig connection, Map<String, Object> legacy, boolean keepMode) {
Map<String, Object> options = new LinkedHashMap<>();
options.put(S3ConnectionResolver.CONNECTION_ID_OPTION, connection.getId());
Object prefix = legacy.get("prefix");
if (prefix != null && !prefix.toString().isBlank()) {
options.put("prefix", prefix);
}
Object mode = legacy.get("mode");
if (keepMode && mode != null && !mode.toString().isBlank()) {
options.put("mode", mode);
}
return options;
}
private Map<String, IntegrationConfig> indexExistingConnections() {
Map<String, IntegrationConfig> byKey = new LinkedHashMap<>();
for (IntegrationConfig connection : connections.findAll()) {
if (connection.getIntegrationType() != IntegrationType.S3) {
continue;
}
try {
Map<String, Object> config =
OBJECT_MAPPER.readValue(connection.getConfig(), Map.class);
byKey.putIfAbsent(credentialKey(config), connection);
} catch (Exception e) {
log.debug(
"Skipping unreadable S3 connection {} while indexing: {}",
connection.getId(),
e.getMessage());
}
}
return byKey;
}
private static String credentialKey(Map<String, Object> options) {
StringBuilder key = new StringBuilder();
for (String option : CONNECTION_OPTIONS) {
Object value = options.get(option);
key.append(value == null ? "" : value.toString().trim()).append(DELIMITER);
}
return key.toString();
}
private static String connectionName(
Map<String, Object> options, Map<String, IntegrationConfig> byKey) {
String base = "S3: " + options.getOrDefault("bucket", "bucket");
long sameName = byKey.values().stream().filter(c -> c.getName().startsWith(base)).count();
return sameName == 0 ? base : base + " (" + (sameName + 1) + ")";
}
private static Source withOptions(Source source, Map<String, Object> options) {
return new Source(
source.id(),
source.name(),
source.type(),
options,
source.enabled(),
source.owner(),
source.teamId());
}
private static Policy withOutput(Policy policy, OutputSpec output) {
return new Policy(
policy.id(),
policy.name(),
policy.owner(),
policy.enabled(),
policy.trigger(),
policy.sourceIds(),
policy.steps(),
output,
policy.teamId());
}
}
@@ -1,56 +0,0 @@
package stirling.software.proprietary.policy.s3;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import stirling.software.proprietary.integration.service.IntegrationConfigUsageCheck;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.source.SourceStore;
import stirling.software.proprietary.policy.store.PolicyStore;
/**
* Reports the policy sources and pipeline outputs referencing an S3 connection, so the connection
* cannot be deleted out from under them (mirrors {@code SourceController}'s referenced-source
* delete guard). Scans in memory - fine at admin-dashboard scale, always consistent with the live
* stores.
*/
@Component
@RequiredArgsConstructor
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class PolicyS3ConnectionUsageCheck implements IntegrationConfigUsageCheck {
private final SourceStore sourceStore;
private final PolicyStore policyStore;
@Override
public List<String> usagesOf(long configId) {
List<String> usages = new ArrayList<>();
for (Source source : sourceStore.all()) {
if (references(source.options(), configId)) {
usages.add("source '" + source.name() + "'");
}
}
for (Policy policy : policyStore.all()) {
if (references(policy.output().options(), configId)) {
usages.add("pipeline '" + policy.name() + "'");
}
}
return usages;
}
private static boolean references(Map<String, Object> options, long configId) {
try {
Long reference = S3ConnectionResolver.connectionId(options);
return reference != null && reference == configId;
} catch (IllegalArgumentException unparseable) {
return false;
}
}
}
@@ -5,12 +5,10 @@ import java.net.URISyntaxException;
import java.util.Map;
/**
* The fully resolved connection settings the S3 input source and output sink run with - normally
* produced by {@link S3ConnectionResolver} merging a stored connection (bucket, region, endpoint,
* credentials) with per-use options (prefix, mode), or parsed directly from legacy options that
* still embed credentials. Credentials are required: there is deliberately no fallback to the
* server's own AWS credential chain, so user-supplied config can never borrow the host's identity.
* {@code snapshot} is input-only and ignored by the sink.
* Connection settings shared by the S3 input source and output sink, parsed from a spec's options
* map. Credentials are required: there is deliberately no fallback to the server's own AWS
* credential chain, so user-supplied config can never borrow the host's identity. {@code snapshot}
* is input-only and ignored by the sink.
*/
public record S3Config(
String bucket,
@@ -1,151 +0,0 @@
package stirling.software.proprietary.policy.s3;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.access.model.ResourceType;
import stirling.software.proprietary.access.service.OwnershipService;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.UserService;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
/**
* Turns a source's or output's options into a full {@link S3Config} by dereferencing its {@code
* connectionId} to a stored S3 {@link IntegrationConfig} (the connection owns bucket, region,
* endpoint, and credentials; the options own per-use settings such as prefix and mode). Options
* with no {@code connectionId} fall back to legacy embedded credentials, so rows written before
* connections shipped keep working until {@link EmbeddedS3CredentialMigration} rewrites them.
*
* <p>When an authenticated caller is present (save-time validation), they must be allowed to use
* the connection. Background sweeps and deliveries run with no caller and skip that check: the
* referencing source or policy was access-checked when it was saved.
*/
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class S3ConnectionResolver {
static final String CONNECTION_ID_OPTION = "connectionId";
private static final String PREFIX_OPTION = "prefix";
private static final String MODE_OPTION = "mode";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final IntegrationConfigRepository connections;
private final OwnershipService ownership;
private final UserService userService;
public S3Config resolve(Map<String, Object> options) {
Long connectionId = connectionId(options);
if (connectionId == null) {
// Legacy embedded credentials, pending migration.
return S3Config.from(options);
}
IntegrationConfig connection =
connections
.findById(connectionId)
.filter(cfg -> cfg.getIntegrationType() == IntegrationType.S3)
.filter(this::usableByCurrentUser)
// Existence and access collapse into one error: a caller must not be able
// to tell "no such connection" from "someone else's connection" and
// enumerate ids. The id/name are never echoed.
.orElseThrow(
() ->
new IllegalArgumentException(
"unknown or inaccessible s3 connection"));
if (!connection.isEnabled()) {
throw new IllegalArgumentException("s3 connection is disabled");
}
Map<String, Object> merged = new LinkedHashMap<>(connectionConfig(connection));
copyPerUseOption(options, merged, PREFIX_OPTION);
copyPerUseOption(options, merged, MODE_OPTION);
return S3Config.from(merged);
}
/** The {@code connectionId} option as a long, or null when the options are legacy-embedded. */
static Long connectionId(Map<String, Object> options) {
Object reference = options.get(CONNECTION_ID_OPTION);
if (reference == null || (reference instanceof String s && s.isBlank())) {
return null;
}
if (reference instanceof Number number) {
return number.longValue();
}
try {
return Long.valueOf(reference.toString().trim());
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"s3 'connectionId' is not a valid connection reference: " + reference);
}
}
/**
* Whether the current caller may use this connection. With no principal - a background sweep or
* delivery on a worker thread that carries no {@code SecurityContext} - access is treated as
* already established: stored policies are validated with the caller present at save time, and
* ad-hoc runs are validated on the request thread before dispatch (see {@code
* PolicyValidator#validateOutput}). A missing principal must therefore never be the ONLY thing
* standing between a caller and a connection, or the check becomes a confused deputy.
*/
private boolean usableByCurrentUser(IntegrationConfig connection) {
User user = currentUser();
return user == null || ownership.canUse(ResourceType.INTEGRATION_CONFIG, connection, user);
}
// Mirrors ResourceAccessSecurity's principal resolution; null when unauthenticated.
private User currentUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !auth.isAuthenticated()) {
return null;
}
Object principal = auth.getPrincipal();
if (principal instanceof User user) {
return user;
}
if (principal instanceof UserDetails userDetails) {
return userService.findByUsername(userDetails.getUsername()).orElse(null);
}
if (principal instanceof String username && !"anonymousUser".equals(username)) {
return userService.findByUsername(username).orElse(null);
}
return null;
}
private static Map<String, Object> connectionConfig(IntegrationConfig connection) {
String json = connection.getConfig();
if (json == null || json.isBlank()) {
return Map.of();
}
try {
return OBJECT_MAPPER.readValue(
json, new TypeReference<LinkedHashMap<String, Object>>() {});
} catch (Exception e) {
throw new IllegalArgumentException(
"s3 connection '" + connection.getName() + "' has unreadable config", e);
}
}
private static void copyPerUseOption(
Map<String, Object> options, Map<String, Object> merged, String key) {
Object value = options.get(key);
if (value != null && !value.toString().isBlank()) {
merged.put(key, value);
}
}
}
@@ -1,51 +0,0 @@
package stirling.software.proprietary.policy.s3;
import java.net.URI;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.cluster.s3.S3Clients;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.service.IntegrationConfigValidator;
/**
* The S3 connection schema, enforced when an S3 {@link IntegrationType} config is saved: bucket and
* credentials required, endpoint an http(s) URL that must not reach private addresses without the
* operator opt-in - the same rules {@link S3ConnectionPool} enforces before signing, moved to save
* time so a bad connection fails in the form rather than in a sweep.
*/
@Component
@RequiredArgsConstructor
@ConditionalOnBooleanProperty(name = "policies.enabled")
public class S3IntegrationValidator implements IntegrationConfigValidator {
private final ApplicationProperties applicationProperties;
@Override
public IntegrationType type() {
return IntegrationType.S3;
}
@Override
public void validate(Map<String, Object> config) {
S3Config parsed = S3Config.from(config);
if (parsed.endpoint() == null) {
return;
}
try {
S3Clients.validateEndpointHost(
URI.create(parsed.endpoint()),
applicationProperties.getPolicies().isAllowPrivateS3Endpoints(),
"S3 connection endpoint",
"set policies.allowPrivateS3Endpoints=true to opt in (e.g. for a local"
+ " MinIO).");
} catch (IllegalStateException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
}
@@ -1,52 +0,0 @@
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,6 +103,7 @@ 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
@@ -1,26 +0,0 @@
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);
}
@@ -3,10 +3,8 @@ 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;
@@ -19,8 +17,6 @@ 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;
@@ -30,23 +26,15 @@ 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,
DistributedLock distributedLock) {
ApplicationProperties applicationProperties) {
this.keyPersistenceService = keyPersistenceService;
this.jwtProperties = applicationProperties.getSecurity().getJwt();
this.distributedLock = distributedLock;
}
@Transactional
@@ -56,28 +44,7 @@ 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());
@@ -18,17 +18,15 @@ 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.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.PostConstruct;
@@ -36,39 +34,27 @@ 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,
JwtSigningKeyRepository keyRepository,
@Value("${cluster.enabled:false}") boolean clusterEnabled) {
ApplicationProperties applicationProperties, CacheManager cacheManager) {
this.jwtProperties = applicationProperties.getSecurity().getJwt();
this.cacheManager = cacheManager;
this.verifyingKeyCache = cacheManager.getCache("verifyingKeys");
this.keyRepository = keyRepository;
this.clusterEnabled = clusterEnabled;
}
@PostConstruct
@@ -77,86 +63,138 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {
log.info("JWT keystore is disabled - keys will be generated in memory");
return;
}
try {
importLegacyDiskKeysIfPresent();
loadKeysFromDb();
ensurePrivateKeyDirectoryExists();
loadExistingKeysFromDisk();
} catch (Exception e) {
log.error("Failed to initialize keystore, generating a fresh keypair", e);
generateAndStoreKeypair();
log.error("Failed to initialize keystore, using in-memory generation", e);
}
}
/**
* 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.
* 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.
*/
@Scheduled(fixedDelayString = "${stirling.security.jwt.activeKeyReloadMs:300000}")
public void reloadActiveKeyFromDb() {
if (!clusterEnabled || !isKeystoreEnabled()) {
return;
}
private void loadExistingKeysFromDisk() {
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());
}
}
Path keyDirectory = Path.of(InstallationPathConfig.getPrivateKeyPath());
/** 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");
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);
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());
}
@Transactional
private JwtVerificationKey generateAndStoreKeypair() {
JwtVerificationKey verifyingKey = null;
try {
KeyPair keyPair = generateRSAKeypair();
String keyId = generateKeyId();
String verifyingKey = encodePublicKey(keyPair.getPublic());
String signingKey =
Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
// 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;
storeKeyPair(keyId, keyPair);
verifyingKey = new JwtVerificationKey(keyId, encodePublicKey(keyPair.getPublic()));
verifyingKeyCache.put(keyId, verifyingKey);
activeKey = verifyingKey;
log.info("Generated and stored new JWT keypair: {}", keyId);
return verificationKey;
} catch (RuntimeException e) {
} catch (IOException e) {
log.error("Failed to generate and store keypair", e);
return null;
}
return verifyingKey;
}
@Override
@@ -169,29 +207,25 @@ public class KeyPersistenceService implements KeyPersistenceServiceInterface {
@Override
public Optional<KeyPair> getKeyPair(String keyId) {
if (!isKeystoreEnabled() || keyId == null) {
if (!isKeystoreEnabled()) {
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 {
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);
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);
return Optional.empty();
}
}
@@ -207,69 +241,44 @@ 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) {
return keyRepository.findByCreatedAtBefore(cutoffDate).stream()
.map(e -> new JwtVerificationKey(e.getKeyId(), e.getVerifyingKey()))
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;
})
.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"))
+ "-"
+ UUID.randomUUID().toString().substring(0, 8);
+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss"));
}
private KeyPair generateRSAKeypair() {
@@ -282,49 +291,125 @@ 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);
}
return decodePrivateKey(Files.readString(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);
}
/**
* 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());
return new KeyPair(keyFactory.generatePublic(publicKeySpec), privateKey);
// Generate public key
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
return new KeyPair(publicKey, privateKey);
}
private String encodePublicKey(PublicKey publicKey) {
return Base64.getEncoder().encodeToString(publicKey.getEncoded());
}
@Override
public PublicKey decodePublicKey(String encodedKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
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);
byte[] keyBytes = Base64.getDecoder().decode(encodedKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
}
}
@@ -13,9 +13,9 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
@@ -52,58 +52,7 @@ class IntegrationConfigServiceTest {
@Mock
private stirling.software.proprietary.access.repository.ResourceGrantRepository grantRepository;
@Mock private IntegrationConfigValidator validator;
@Mock private IntegrationConfigUsageCheck usageCheck;
private IntegrationConfigService service;
@BeforeEach
void setUp() {
service =
new IntegrationConfigService(
repository,
ownership,
secretMasker,
grantRepository,
List.of(validator),
List.of(usageCheck));
}
@Test
void createRejectsAConfigItsTypeValidatorRefuses() {
when(secretMasker.sanitize(any())).thenReturn(Map.of());
when(validator.type()).thenReturn(IntegrationType.API);
org.mockito.Mockito.doThrow(new IllegalArgumentException("api config needs a 'url'"))
.when(validator)
.validate(any());
assertThatThrownBy(
() ->
service.create(
request(IntegrationType.API, OwnerScope.USER, null),
user(7)))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void deleteRefusedWhileAnythingStillReferencesTheConfig() {
IntegrationConfig cfg = config(9L);
when(repository.findById(9L)).thenReturn(Optional.of(cfg));
when(ownership.canManage(any(), eq(cfg), any())).thenReturn(true);
when(usageCheck.usagesOf(9L)).thenReturn(List.of("source 'Claims intake'"));
assertThatThrownBy(() -> service.delete(9L, user(7)))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.CONFLICT));
verify(repository, org.mockito.Mockito.never()).delete(any(IntegrationConfig.class));
}
@InjectMocks private IntegrationConfigService service;
@Test
void createDelegatesOwnershipAndSanitizesConfig() {
@@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -27,8 +26,6 @@ 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;
@@ -80,7 +77,6 @@ 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>
@@ -109,8 +105,7 @@ class PolicyControllerTest {
policyTriggers,
applicationProperties,
tempFileManager,
jobOwnershipService,
jobStore);
jobOwnershipService);
}
private static stirling.software.proprietary.policy.trigger.PolicyTrigger trigger(
@@ -199,29 +194,6 @@ class PolicyControllerTest {
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
@DisplayName("rejects an ad-hoc output the caller cannot use, on the request thread")
void rejectsUnauthorizedAdHocOutput() {
// The confused-deputy guard: an S3 output referencing a connection the caller may not
// use is validated here (principal present) and refused before any worker dispatch.
PipelineDefinition definition =
new PipelineDefinition(
"pipe",
List.of(new PipelineStep("/api/v1/misc/compress-pdf", null)),
new OutputSpec("s3", Map.of("connectionId", 999)));
doThrow(new IllegalArgumentException("unknown or inaccessible s3 connection"))
.when(policyValidator)
.validateOutput(any());
assertThatThrownBy(() -> controller.run(definition, new PolicyRunFiles()))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.BAD_REQUEST));
verify(policyRunner, never()).runAdHoc(any(), any(), any());
}
}
@Nested
@@ -268,8 +240,6 @@ 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");
@@ -82,28 +82,6 @@ class PolicyValidatorTest {
assertTrue(ex.getMessage().contains("schedule"));
}
@Test
void validateOutputDelegatesToTheSink() {
when(outputSink.supports(any())).thenReturn(true);
OutputSpec output = new OutputSpec("s3", Map.of("connectionId", 1));
validator.validateOutput(output);
verify(outputSink).validate(output);
}
@Test
void validateOutputSurfacesAnInaccessibleConnection() {
when(outputSink.supports(any())).thenReturn(true);
doThrow(new IllegalArgumentException("unknown or inaccessible s3 connection"))
.when(outputSink)
.validate(any());
assertThrows(
IllegalArgumentException.class,
() -> validator.validateOutput(new OutputSpec("s3", Map.of("connectionId", 1))));
}
@Test
void rejectsAnUnknownTriggerType() {
when(trigger.type()).thenReturn("schedule");
@@ -23,7 +23,6 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
@@ -83,9 +82,7 @@ class S3InputSourceMinioTest {
// The MinIO endpoint resolves to loopback, so the operator opt-in must be on.
ApplicationProperties properties = new ApplicationProperties();
properties.getPolicies().setAllowPrivateS3Endpoints(true);
source =
new S3InputSource(
new S3ConnectionPool(properties), S3TestConnections.legacyResolver());
source = new S3InputSource(new S3ConnectionPool(properties));
ledger = new InProcessProcessedLedger();
ctx = new RecordingContext();
}
@@ -164,9 +161,7 @@ class S3InputSourceMinioTest {
@Test
void aPrivateEndpointIsRejectedWithoutTheOperatorOptIn() {
S3InputSource guarded =
new S3InputSource(
new S3ConnectionPool(new ApplicationProperties()),
S3TestConnections.legacyResolver());
new S3InputSource(new S3ConnectionPool(new ApplicationProperties()));
assertThatThrownBy(() -> guarded.validate(spec(Map.of())))
.isInstanceOf(IllegalArgumentException.class)
@@ -29,7 +29,6 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.exception.SdkClientException;
@@ -65,8 +64,7 @@ class S3InputSourceTest {
void setUp() {
source =
new S3InputSource(
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client),
S3TestConnections.legacyResolver());
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client));
ledger = new InProcessProcessedLedger();
ctx = new RecordingContext();
}
@@ -28,7 +28,6 @@ import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.model.InputSpec;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
@@ -91,8 +90,8 @@ class S3OutputSinkMinioTest {
properties.getPolicies().setAllowPrivateS3Endpoints(true);
S3ConnectionPool pool = new S3ConnectionPool(properties);
ledger = new InProcessProcessedLedger();
sink = new S3OutputSink(pool, S3TestConnections.legacyResolver(), ledger);
source = new S3InputSource(pool, S3TestConnections.legacyResolver());
sink = new S3OutputSink(pool, ledger);
source = new S3InputSource(pool);
}
@Test
@@ -32,7 +32,6 @@ import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
import stirling.software.proprietary.policy.ledger.ProcessedFileStatus;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.s3.S3ConnectionPool;
import stirling.software.proprietary.policy.s3.S3TestConnections;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.exception.SdkClientException;
@@ -67,7 +66,6 @@ class S3OutputSinkTest {
sink =
new S3OutputSink(
new S3ConnectionPool(new ApplicationProperties(), config -> s3Client),
S3TestConnections.legacyResolver(),
ledger);
}
@@ -1,212 +0,0 @@
package stirling.software.proprietary.policy.s3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
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.proprietary.access.model.OwnerScope;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.InProcessSourceStore;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
import stirling.software.proprietary.security.repository.TeamRepository;
/**
* Tests for {@link EmbeddedS3CredentialMigration}: legacy embedded credentials become deduplicated
* team-scoped connections, rewritten rows keep only per-use options, and re-runs are no-ops.
*/
@ExtendWith(MockitoExtension.class)
class EmbeddedS3CredentialMigrationTest {
@Mock private IntegrationConfigRepository connections;
@Mock private TeamRepository teamRepository;
private final InProcessSourceStore sourceStore = new InProcessSourceStore();
private final InProcessPolicyStore policyStore = new InProcessPolicyStore();
private EmbeddedS3CredentialMigration migration;
@BeforeEach
void setUp() {
migration =
new EmbeddedS3CredentialMigration(
sourceStore, policyStore, connections, teamRepository);
AtomicLong ids = new AtomicLong(100);
// Lenient: the nothing-to-migrate cases never create a connection.
lenient().when(connections.findAll()).thenReturn(List.of());
lenient()
.when(connections.save(any()))
.thenAnswer(
invocation -> {
IntegrationConfig saved = invocation.getArgument(0);
if (saved.getId() == null) {
saved.setId(ids.incrementAndGet());
}
return saved;
});
}
@Test
void extractsSharedCredentialsIntoOneTeamScopedConnection() {
Team team = new Team();
team.setId(7L);
when(teamRepository.findById(7L)).thenReturn(Optional.of(team));
Source source =
sourceStore.save(
new Source(
null,
"Claims intake",
"s3",
Map.of(
"bucket", "inbox",
"prefix", "incoming/",
"mode", "snapshot",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh"),
true,
"alice",
7L));
Policy policy =
policyStore.save(
new Policy(
null,
"Rotate",
"alice",
true,
null,
List.of(source.id()),
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
new OutputSpec(
"s3",
Map.of(
"bucket", "inbox",
"prefix", "processed/",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh")),
7L));
migration.migrate();
// Same bucket + credentials on both rows: exactly one connection extracted.
verify(connections, times(1)).save(any());
Map<String, Object> sourceOptions = sourceStore.get(source.id()).orElseThrow().options();
assertEquals(101L, sourceOptions.get("connectionId"));
assertEquals("incoming/", sourceOptions.get("prefix"));
assertEquals("snapshot", sourceOptions.get("mode"));
assertNull(sourceOptions.get("accessKeyId"));
assertNull(sourceOptions.get("secretAccessKey"));
assertNull(sourceOptions.get("bucket"));
Map<String, Object> outputOptions =
policyStore.get(policy.id()).orElseThrow().output().options();
assertEquals(101L, outputOptions.get("connectionId"));
assertEquals("processed/", outputOptions.get("prefix"));
assertNull(outputOptions.get("secretAccessKey"));
}
@Test
void connectionOwnershipFollowsTheSourceTeam() {
Team team = new Team();
team.setId(7L);
when(teamRepository.findById(7L)).thenReturn(Optional.of(team));
sourceStore.save(s3Source("teamed", 7L));
migration.migrate();
verify(connections)
.save(
org.mockito.ArgumentMatchers.argThat(
connection ->
connection.getScope() == OwnerScope.TEAM
&& connection.getOwnerTeam() == team));
}
@Test
void teamlessRowsBecomeServerScopedConnections() {
sourceStore.save(s3Source("solo", null));
migration.migrate();
verify(connections)
.save(
org.mockito.ArgumentMatchers.argThat(
connection -> connection.getScope() == OwnerScope.SERVER));
}
@Test
void aSecondRunFindsNothingToDo() {
sourceStore.save(s3Source("once", null));
migration.migrate();
migration.migrate();
// One connection from the first run; the rewritten source no longer embeds credentials.
verify(connections, times(1)).save(any());
}
@Test
void nonS3AndAlreadyMigratedRowsAreUntouched() {
Source folder =
sourceStore.save(
new Source(
null,
"Folder",
"folder",
Map.of("directory", "/in"),
true,
"alice",
null));
Source migrated =
sourceStore.save(
new Source(
null,
"Done already",
"s3",
Map.of("connectionId", 55L, "prefix", "in/"),
true,
"alice",
null));
migration.migrate();
verify(connections, times(0)).save(any());
assertEquals(
Map.of("directory", "/in"), sourceStore.get(folder.id()).orElseThrow().options());
assertEquals(
Map.of("connectionId", 55L, "prefix", "in/"),
sourceStore.get(migrated.id()).orElseThrow().options());
}
private static Source s3Source(String name, Long teamId) {
return new Source(
null,
name,
"s3",
Map.of(
"bucket", "inbox",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh"),
true,
"alice",
teamId);
}
}
@@ -1,52 +0,0 @@
package stirling.software.proprietary.policy.s3;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.source.InProcessSourceStore;
import stirling.software.proprietary.policy.source.Source;
import stirling.software.proprietary.policy.store.InProcessPolicyStore;
/** Tests for {@link PolicyS3ConnectionUsageCheck}'s reference scan across sources and outputs. */
class PolicyS3ConnectionUsageCheckTest {
private final InProcessSourceStore sourceStore = new InProcessSourceStore();
private final InProcessPolicyStore policyStore = new InProcessPolicyStore();
private final PolicyS3ConnectionUsageCheck check =
new PolicyS3ConnectionUsageCheck(sourceStore, policyStore);
@Test
void reportsSourcesAndOutputsReferencingTheConnection() {
sourceStore.save(
new Source(
null,
"Claims intake",
"s3",
Map.of("connectionId", 5L, "prefix", "in/"),
true,
"alice",
null));
policyStore.save(
new Policy(
null,
"Rotate",
"alice",
true,
null,
List.of(),
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
new OutputSpec("s3", Map.of("connectionId", "5")),
null));
assertThat(check.usagesOf(5))
.containsExactlyInAnyOrder("source 'Claims intake'", "pipeline 'Rotate'");
assertThat(check.usagesOf(6)).isEmpty();
}
}
@@ -1,149 +0,0 @@
package stirling.software.proprietary.policy.s3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import stirling.software.proprietary.access.service.OwnershipService;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.model.IntegrationType;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.service.UserService;
/**
* Tests for {@link S3ConnectionResolver}: connection dereferencing with per-use overrides, the
* legacy embedded fallback, and the save-time access check that background sweeps skip.
*/
@ExtendWith(MockitoExtension.class)
class S3ConnectionResolverTest {
@Mock private IntegrationConfigRepository connections;
@Mock private OwnershipService ownership;
@Mock private UserService userService;
@AfterEach
void clearSecurityContext() {
SecurityContextHolder.clearContext();
}
@Test
void resolvesAConnectionAndMergesPerUseOptions() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
S3Config config =
resolver()
.resolve(
Map.of(
"connectionId", 9L,
"prefix", "incoming/",
"mode", "snapshot"));
assertEquals("inbox", config.bucket());
assertEquals("AKIAEXAMPLE", config.accessKeyId());
assertEquals("incoming/", config.prefix());
assertTrue(config.snapshot());
}
@Test
void acceptsAStringConnectionReference() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
assertEquals("inbox", resolver().resolve(Map.of("connectionId", "9")).bucket());
}
@Test
void fallsBackToLegacyEmbeddedCredentials() {
S3Config config =
resolver()
.resolve(
Map.of(
"bucket", "legacy",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh"));
assertEquals("legacy", config.bucket());
}
@Test
void rejectsUnknownDisabledOrWrongTypeConnections() {
when(connections.findById(1L)).thenReturn(Optional.empty());
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 1L)));
when(connections.findById(2L)).thenReturn(Optional.of(s3Connection(2L, false)));
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 2L)));
IntegrationConfig mcp = s3Connection(3L, true);
mcp.setIntegrationType(IntegrationType.MCP);
when(connections.findById(3L)).thenReturn(Optional.of(mcp));
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 3L)));
}
@Test
void anAuthenticatedSaverMustBeAllowedToUseTheConnection() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
User saver = new User();
saver.setUsername("alice");
SecurityContextHolder.getContext()
.setAuthentication(
new UsernamePasswordAuthenticationToken(saver, null, java.util.List.of()));
when(ownership.canUse(any(), any(IntegrationConfig.class), eq(saver))).thenReturn(false);
// Denied reads the same as unknown and never echoes the connection name, so ids can't be
// enumerated by probing.
assertThrows(
IllegalArgumentException.class,
() -> resolver().resolve(Map.of("connectionId", 9L)));
try {
resolver().resolve(Map.of("connectionId", 9L));
} catch (IllegalArgumentException e) {
org.junit.jupiter.api.Assertions.assertFalse(
e.getMessage().contains("Claims bucket"),
"access-denied error must not leak the connection name");
}
}
@Test
void backgroundSweepsWithNoUserSkipTheAccessCheck() {
when(connections.findById(9L)).thenReturn(Optional.of(s3Connection(9L, true)));
// No authentication in the context: resolution succeeds without consulting ownership.
assertEquals("inbox", resolver().resolve(Map.of("connectionId", 9L)).bucket());
}
private S3ConnectionResolver resolver() {
return new S3ConnectionResolver(connections, ownership, userService);
}
private static IntegrationConfig s3Connection(long id, boolean enabled) {
IntegrationConfig connection = new IntegrationConfig();
connection.setId(id);
connection.setIntegrationType(IntegrationType.S3);
connection.setName("Claims bucket");
connection.setEnabled(enabled);
connection.setConfig(
"{\"bucket\":\"inbox\",\"accessKeyId\":\"AKIAEXAMPLE\","
+ "\"secretAccessKey\":\"shh\"}");
return connection;
}
}
@@ -1,71 +0,0 @@
package stirling.software.proprietary.policy.s3;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Map;
import org.junit.jupiter.api.Test;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.integration.model.IntegrationType;
/**
* Tests for {@link S3IntegrationValidator}: the S3 connection schema fails at save time - missing
* credentials, bad endpoints, and private endpoints without the operator opt-in.
*/
class S3IntegrationValidatorTest {
@Test
void acceptsACompleteConnection() {
assertThatCode(
() ->
validator(false)
.validate(
Map.of(
"bucket", "inbox",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh")))
.doesNotThrowAnyException();
}
@Test
void rejectsMissingCredentialsOrBucket() {
assertThatThrownBy(() -> validator(false).validate(Map.of("bucket", "inbox")))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(
() ->
validator(false)
.validate(
Map.of(
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void rejectsAPrivateEndpointWithoutTheOperatorOptIn() {
Map<String, Object> config =
Map.of(
"bucket", "inbox",
"accessKeyId", "AKIAEXAMPLE",
"secretAccessKey", "shh",
"endpoint", "http://localhost:9000");
assertThatThrownBy(() -> validator(false).validate(config))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("allowPrivateS3Endpoints");
assertThatCode(() -> validator(true).validate(config)).doesNotThrowAnyException();
}
@Test
void itOnlyClaimsTheS3Type() {
org.junit.jupiter.api.Assertions.assertEquals(IntegrationType.S3, validator(false).type());
}
private static S3IntegrationValidator validator(boolean allowPrivateEndpoints) {
ApplicationProperties properties = new ApplicationProperties();
properties.getPolicies().setAllowPrivateS3Endpoints(allowPrivateEndpoints);
return new S3IntegrationValidator(properties);
}
}
@@ -1,24 +0,0 @@
package stirling.software.proprietary.policy.s3;
import static org.mockito.Mockito.mock;
import stirling.software.proprietary.access.service.OwnershipService;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.security.service.UserService;
/** Test fixtures for S3 connection plumbing shared across the policy S3 tests. */
public final class S3TestConnections {
private S3TestConnections() {}
/**
* A resolver for tests whose options embed credentials directly (the legacy pass-through path),
* so its collaborators are never touched.
*/
public static S3ConnectionResolver legacyResolver() {
return new S3ConnectionResolver(
mock(IntegrationConfigRepository.class),
mock(OwnershipService.class),
mock(UserService.class));
}
}
@@ -1,102 +0,0 @@
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());
}
}
@@ -4,41 +4,45 @@ 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.verify;
import static org.mockito.Mockito.mockStatic;
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;
@Mock private JwtSigningKeyRepository keyRepository;
@TempDir Path tempDir;
private KeyPersistenceService keyPersistenceService;
private KeyPair testKeyPair;
@@ -54,128 +58,175 @@ class KeyPersistenceServiceInterfaceTest {
lenient().when(applicationProperties.getSecurity()).thenReturn(security);
lenient().when(security.getJwt()).thenReturn(jwtConfig);
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()));
lenient().when(jwtConfig.isEnableKeystore()).thenReturn(true); // Default value
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testKeystoreEnabled(boolean keystoreEnabled) {
when(jwtConfig.isEnableKeystore()).thenReturn(keystoreEnabled);
assertEquals(keystoreEnabled, keyPersistenceService.isKeystoreEnabled());
try (MockedStatic<InstallationPathConfig> mockedStatic =
mockStatic(InstallationPathConfig.class)) {
mockedStatic
.when(InstallationPathConfig::getPrivateKeyPath)
.thenReturn(tempDir.toString());
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
assertEquals(keystoreEnabled, keyPersistenceService.isKeystoreEnabled());
}
}
@Test
void generatesAndPersistsAKeyWhenNoneIsActive() {
// getActiveKey with no active key mints one and persists it - no disk involved.
JwtVerificationKey active = keyPersistenceService.getActiveKey();
void testGetActiveKeypairWhenNoActiveKeyExists() {
try (MockedStatic<InstallationPathConfig> mockedStatic =
mockStatic(InstallationPathConfig.class)) {
mockedStatic
.when(InstallationPathConfig::getPrivateKeyPath)
.thenReturn(tempDir.toString());
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
keyPersistenceService.initializeKeystore();
assertNotNull(active);
assertNotNull(active.getKeyId());
assertNotNull(active.getVerifyingKey());
verify(keyRepository).save(any(JwtSigningKeyEntity.class));
JwtVerificationKey result = keyPersistenceService.getActiveKey();
assertNotNull(result);
assertNotNull(result.getKeyId());
assertNotNull(result.getVerifyingKey());
}
}
@Test
void loadsTheMostRecentExistingKeyAsActive() {
when(keyRepository.count()).thenReturn(1L);
when(keyRepository.findAllByOrderByCreatedAtDesc())
.thenReturn(List.of(entityFrom("jwt-key-2026-07-13-000000-abcd1234")));
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());
keyPersistenceService.initializeKeystore();
JwtVerificationKey active = keyPersistenceService.getActiveKey();
JwtVerificationKey existingKey = new JwtVerificationKey(keyId, publicKeyBase64);
assertEquals("jwt-key-2026-07-13-000000-abcd1234", active.getKeyId());
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());
}
}
@Test
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)));
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());
Optional<KeyPair> result = keyPersistenceService.getKeyPair(keyId);
JwtVerificationKey signingKey = new JwtVerificationKey(keyId, publicKeyBase64);
assertTrue(result.isPresent());
assertNotNull(result.get().getPublic());
assertNotNull(result.get().getPrivate());
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());
}
}
@Test
void getKeyPairIsEmptyWhenTheKeyIsUnknown() {
when(keyRepository.findById("nope")).thenReturn(Optional.empty());
assertFalse(keyPersistenceService.getKeyPair("nope").isPresent());
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());
}
}
@Test
void getKeyPairIsEmptyWhenKeystoreDisabled() {
void testGetKeyPairWhenKeystoreDisabled() {
when(jwtConfig.isEnableKeystore()).thenReturn(false);
assertFalse(keyPersistenceService.getKeyPair("any-key").isPresent());
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());
}
}
@Test
void eligibleForCleanupIsSourcedFromTheDb() {
when(keyRepository.findByCreatedAtBefore(any())).thenReturn(List.of(entityFrom("old-key")));
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();
List<JwtVerificationKey> stale =
keyPersistenceService.getKeysEligibleForCleanup(java.time.LocalDateTime.now());
assertEquals(1, stale.size());
assertEquals("old-key", stale.get(0).getKeyId());
assertTrue(Files.exists(tempDir));
assertTrue(Files.isDirectory(tempDir));
}
}
@Test
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());
void testLoadExistingKeypairWithMissingPrivateKeyFile() throws Exception {
String keyId = "test-key-missing-file";
String publicKeyBase64 =
Base64.getEncoder().encodeToString(testKeyPair.getPublic().getEncoded());
when(keyRepository.findFirstByOrderByCreatedAtDesc())
.thenReturn(Optional.of(entityFrom("jwt-key-peer-new")));
JwtVerificationKey existingKey = new JwtVerificationKey(keyId, publicKeyBase64);
keyPersistenceService.reloadActiveKeyFromDb();
try (MockedStatic<InstallationPathConfig> mockedStatic =
mockStatic(InstallationPathConfig.class)) {
mockedStatic
.when(InstallationPathConfig::getPrivateKeyPath)
.thenReturn(tempDir.toString());
keyPersistenceService = new KeyPersistenceService(applicationProperties, cacheManager);
keyPersistenceService.initializeKeystore();
// 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());
JwtVerificationKey result = keyPersistenceService.getActiveKey();
assertNotNull(result);
assertNotNull(result.getKeyId());
assertNotNull(result.getVerifyingKey());
}
}
}
+1 -1
View File
@@ -91,7 +91,7 @@ springBoot {
allprojects {
group = 'stirling.software'
version = '2.14.2'
version = '2.14.1'
configurations.configureEach {
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
+1
View File
@@ -0,0 +1 @@
+2
View File
@@ -12,6 +12,8 @@ editor/public/mockServiceWorker.js
# Auto-generated OG/social-preview metadata (scripts/generate-og-metadata.mjs); regenerated verbatim.
editor/public/og-metadata.json
editor/src/core/data/ogImageMap.json
# Auto-generated portal docs manifest (scripts/sync-portal-docs.mts); regenerated verbatim.
editor/src/portal/generated/docsManifest.json
editor/public/pdfjs*/
editor/public/js/thirdParty/
editor/public/css/cookieconsent.css
@@ -6603,6 +6603,10 @@ title = "No components available"
description = "GA components are available on Pay-as-you-go; a few Beta components are enterprise-only. Locked cards show an upgrade nudge."
title = "Some components need a paid plan"
[portal.docs]
browse = "Browse docs"
viewSource = "View source on GitHub"
[portal.docs.authentication]
codeCaption = "every request"
eyebrow = "GETTING STARTED"
@@ -6688,11 +6692,19 @@ title = "Official SDKs"
beta = "Beta"
deprecated = "Deprecated"
[portal.docs.search]
empty = "No matching docs"
placeholder = "Search docs"
results = "{{count}} results"
[portal.docs.skills]
eyebrow = "SKILLS"
lead = "Bundled, named capabilities your agent invokes as a single tool. Each skill is a deterministic op chain with evals attached."
title = "Agent skills"
[portal.docs.toc]
title = "On this page"
[portal.docs.webhooks]
codeCaption = "document.processed"
eyebrow = "API REFERENCE"
@@ -7246,7 +7258,7 @@ storage = "Storage"
[portal.nav]
agent-builder = "Agent Builder"
components = "Components"
docs = "Developer Docs"
docs = "Documentation"
documents = "Documents"
editor = "Editor"
home = "Home"
@@ -6240,10 +6240,6 @@ muted = "muted"
nameLabel = "Name"
namePlaceholder = "e.g. Compliance escalation"
[portal.agentBuilder.status]
draft = "Draft"
published = "Published"
[portal.agentBuilder.tabs]
evals = "Evals"
scenarios = "Scenarios"
@@ -6467,7 +6463,7 @@ install = "Install"
usage = "Usage"
[portal.catalogue.detail.locked]
description = "{{name}} is included from the {{plan}}. Upgrade to embed it."
description = "{{name}} is included from the {{tier}} plan. Upgrade to embed it."
title = "Not available on your plan"
[portal.catalogue.detail.preview]
@@ -6534,34 +6530,9 @@ title = "No components available"
description = "GA components are available on Pay-as-you-go; a few Beta components are enterprise-only. Locked cards show an upgrade nudge."
title = "Some components need a paid plan"
[portal.connections]
createTitle = "New S3 connection"
delete = "Delete"
edit = "Edit"
editTitle = "Edit S3 connection"
subtitle = "Reusable S3 credentials that sources and pipeline outputs connect to."
[portal.connections.actions]
new = "New connection"
[portal.connections.empty]
description = "Add an S3 connection to reuse the same bucket and credentials across sources and pipeline outputs."
title = "No connections yet"
[portal.connections.picker]
cancel = "Cancel"
createNew = "New connection..."
placeholder = "Select a connection"
save = "Save connection"
[portal.connections.s3.fields]
name = "Connection name"
namePlaceholder = "e.g. Claims bucket"
[portal.connections.table]
bucket = "Bucket"
name = "Name"
region = "Region"
[portal.docs]
browse = "Browse docs"
viewSource = "View source on GitHub"
[portal.docs.authentication]
codeCaption = "every request"
@@ -6648,11 +6619,19 @@ title = "Official SDKs"
beta = "Beta"
deprecated = "Deprecated"
[portal.docs.search]
empty = "No matching docs"
placeholder = "Search docs"
results = "{{count}} results"
[portal.docs.skills]
eyebrow = "SKILLS"
lead = "Bundled, named capabilities your agent invokes as a single tool. Each skill is a deterministic op chain with evals attached."
title = "Agent skills"
[portal.docs.toc]
title = "On this page"
[portal.docs.webhooks]
codeCaption = "document.processed"
eyebrow = "API REFERENCE"
@@ -7317,7 +7296,7 @@ storage = "Storage"
[portal.nav]
agent-builder = "Agent Builder"
components = "Components"
docs = "Developer Docs"
docs = "Documentation"
documents = "Documents"
editor = "Editor"
home = "Home"
@@ -7374,6 +7353,10 @@ operations_one = "Operation ({{count}})"
operations_other = "Operations ({{count}})"
output = "Output"
removeStep = "Remove operation"
s3Configure = "Configure"
s3Done = "Done"
s3ModalTitle = "Amazon S3 output"
s3NotConfigured = "Not configured"
s3PrefixHelp = "Outputs are uploaded under this key prefix."
save = "Save changes"
scheduleEvery = "Run every"
@@ -7444,7 +7427,6 @@ manual = "Manual"
schedule = "Scheduled"
[portal.policies]
defaultName = "{{category}} Policy"
subtitle = "Standing automations that enforce a tool pipeline on every document. Each policy fires on upload or export, runs its tool chain, and saves the enforced version alongside the original."
title = "Policies"
@@ -8016,29 +7998,34 @@ primaryNav = "Primary navigation"
switchApp = "Switch app"
[portal.sources]
subtitle = "Reusable input connections that feed documents into Stirling. Configure a source once, then reference it from any number of pipelines."
subtitle = "Reusable input connections that feed documents into Stirling. Configure a connection once, then reference it from any number of policies. Click a row for its config and which policies use it."
title = "Sources"
[portal.sources.actions]
agentBuilder = "Agent Builder"
connectSource = "Connect source"
[portal.sources.builder]
back = "Back to sources"
cancel = "Cancel"
create = "Create source"
createTitle = "Connect a source"
delete = "Delete"
editTitle = "Edit source"
enabled = "Enabled"
save = "Save changes"
[portal.sources.delete]
body = "Delete \"{{name}}\"? This can't be undone. Policies that reference it would need to be updated."
cancel = "Cancel"
confirm = "Delete"
title = "Delete source?"
[portal.sources.detail]
closeAriaLabel = "Close detail"
delete = "Delete source"
docs24h = "Last 24h"
docs30d = "Last 30 days"
docsTotal = "Total seen"
docsTrend = "Documents over the last 30 days"
documents = "Documents"
edit = "Edit"
notReferenced = "Not referenced by any policy, so it's safe to delete."
pause = "Pause"
resume = "Resume"
subtitle = "{{type}} · {{status}}"
usedBy = "Used by"
[portal.sources.empty]
description = "Connect a folder (and, soon, cloud storage) so your policies have somewhere to pull documents from."
title = "No sources connected yet"
@@ -8054,15 +8041,10 @@ disabled = "Disabled"
unused = "Unused"
[portal.sources.table]
documents = "Documents"
source = "Source"
status = "Status"
usedBy = "Policies"
[portal.sources.tabs]
connections = "Connections"
sources = "Sources"
[portal.sources.types.editor]
description = "Documents your team has processed in the editor, across policy and AI runs."
label = "Editor"
@@ -8110,10 +8092,6 @@ label = "Access key ID"
label = "Bucket"
placeholder = "my-company-inbox"
[portal.sources.types.s3.fields.connection]
helperText = "The stored connection holding the bucket and credentials. Reused by every source and pipeline output that references it."
label = "Connection"
[portal.sources.types.s3.fields.endpoint]
helperText = "Leave blank for Amazon S3. Set to use an S3-compatible service such as MinIO."
label = "Custom endpoint"
@@ -8143,14 +8121,21 @@ label = "Secret access key"
label = "Source"
[portal.sources.wizard]
back = "Back"
cancel = "Cancel"
continue = "Continue"
editTitle = "Edit source"
name = "Name"
namePlaceholder = "e.g. Claims intake"
save = "Save changes"
subtitle = "Step {{current}} of {{total}} · {{label}}"
title = "Connect a source"
type = "Type"
[portal.tier]
enterprise = "Enterprise plan"
free = "Editor plan"
pro = "Processor plan"
[portal.sources.wizard.steps]
chooseType = "Choose type"
configure = "Configure"
review = "Review & connect"
[portal.usage]
managePayment = "Manage Payment"
@@ -10166,19 +10151,6 @@ resetPw = "Reset password"
suspend = "Suspend"
unlock = "Unlock account"
[users.activity]
daysAgo = "{{count}}d ago"
hoursAgo = "{{count}}h ago"
justNow = "Just now"
minutesAgo = "{{count}}m ago"
monthsAgo_one = "{{count}} month ago"
monthsAgo_other = "{{count}} months ago"
never = "Never"
weeksAgo_one = "{{count}} week ago"
weeksAgo_other = "{{count}} weeks ago"
yearsAgo_one = "{{count}} year ago"
yearsAgo_other = "{{count}} years ago"
[users.cap]
addProcessor = "+ Processor"
approver = "Approves policy"
@@ -10249,9 +10221,7 @@ by = "Invited by {{who}}"
cancel = "Cancel"
count = "{{count}} pending"
desc = "Invited people who haven't joined yet. They hold a seat until they accept."
expiresInDays_one = "Expires in {{count}} day"
expiresInDays_other = "Expires in {{count}} days"
expiresToday = "Expires today"
expires = "Expires"
title = "Pending invitations"
[users.loadError]
@@ -0,0 +1,159 @@
/**
* Sync the portal Developer Docs from the Stirling docs repo.
*
* Fetches the docs repo tarball, extracts `docs/**` in-process (no external tar
* binary, no per-file GitHub rate limits), shapes it with the pure transforms in
* src/portal/docs/manifest/transform.ts, and writes the committed manifest that
* the portal docs view renders. Re-run with `npm run docs:sync`.
*
* Env: DOCS_REPO, DOCS_REF, DOCS_ROOT override the defaults below.
*/
import { gunzipSync } from "node:zlib";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
// tsx/node16 can't resolve the @portal alias here, so import by relative .ts path.
// eslint-disable-next-line no-restricted-imports
import {
buildManifest,
type CategoryMap,
type RawDoc,
} from "../src/portal/docs/manifest/transform.ts";
const REPO = process.env.DOCS_REPO ?? "Stirling-Tools/Stirling-Tools.github.io";
const REF = process.env.DOCS_REF ?? "main";
const ROOT = process.env.DOCS_ROOT ?? "docs";
const SITE = "https://docs.stirlingpdf.com";
const HERE = dirname(fileURLToPath(import.meta.url));
const OUT = resolve(HERE, "../src/portal/generated/docsManifest.json");
/* ── Minimal tar reader (ustar + pax/GNU long names) ─────────────────────── */
interface TarEntry {
name: string;
type: string;
data: Buffer;
}
function readTar(buf: Buffer): TarEntry[] {
const entries: TarEntry[] = [];
let offset = 0;
let longName: string | null = null;
let paxPath: string | null = null;
const str = (start: number, len: number) => {
const slice = buf.subarray(start, start + len);
const end = slice.indexOf(0);
return slice.toString("utf8", 0, end === -1 ? len : end);
};
while (offset + 512 <= buf.length) {
const header = buf.subarray(offset, offset + 512);
// Two consecutive zero blocks mark the end of the archive.
if (header.every((b) => b === 0)) break;
const name = str(offset, 100);
const prefix = str(offset + 345, 155);
const sizeStr = str(offset + 124, 12).trim();
const size = parseInt(sizeStr, 8) || 0;
const type = String.fromCharCode(header[156]);
const dataStart = offset + 512;
const data = buf.subarray(dataStart, dataStart + size);
let fullName = prefix ? `${prefix}/${name}` : name;
if (longName) {
fullName = longName;
longName = null;
}
if (paxPath) {
fullName = paxPath;
paxPath = null;
}
if (type === "L") {
// GNU long name: the payload is the real name of the next entry.
longName = data.toString("utf8").replace(/\0+$/, "");
} else if (type === "x") {
// pax extended header: pull a `path=` record for the next entry.
const record = /(?:^|\n)\d+ path=([^\n]+)\n/.exec(data.toString("utf8"));
if (record) paxPath = record[1];
} else if (type === "0" || type === "\0" || type === "") {
entries.push({ name: fullName, type, data: Buffer.from(data) });
}
offset = dataStart + Math.ceil(size / 512) * 512;
}
return entries;
}
/* ── Fetch + shape ───────────────────────────────────────────────────────── */
async function main(): Promise<void> {
const url = `https://api.github.com/repos/${REPO}/tarball/${REF}`;
console.log(`Fetching ${REPO}@${REF} …`);
const res = await fetch(url, {
headers: {
Accept: "application/vnd.github+json",
"User-Agent": "stirling-portal-docs-sync",
...(process.env.GITHUB_TOKEN
? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` }
: {}),
},
});
if (!res.ok) {
throw new Error(
`GitHub tarball fetch failed: ${res.status} ${res.statusText}`,
);
}
const gz = Buffer.from(await res.arrayBuffer());
const entries = readTar(gunzipSync(gz));
// Strip the "<repo>-<sha>/" wrapper dir and keep only files under docs root.
const prefix = `${ROOT}/`;
const rawDocs: RawDoc[] = [];
const categories: CategoryMap = {};
for (const entry of entries) {
const rel = entry.name.replace(/^[^/]+\//, "");
if (!rel.startsWith(prefix)) continue;
const inner = rel.slice(prefix.length);
if (!inner) continue;
if (inner.endsWith("/_category_.json")) {
const dir = inner.slice(0, -"/_category_.json".length);
try {
categories[dir] = JSON.parse(entry.data.toString("utf8"));
} catch {
console.warn(` skipping unparseable _category_.json in ${dir}`);
}
} else if (/\.mdx?$/i.test(inner)) {
rawDocs.push({ relPath: inner, content: entry.data.toString("utf8") });
}
}
if (rawDocs.length === 0) {
throw new Error(`No markdown found under ${ROOT}/ — wrong repo/ref/root?`);
}
const manifest = buildManifest(rawDocs, categories, {
repo: REPO,
ref: REF,
root: ROOT,
siteBaseUrl: SITE,
});
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(OUT, JSON.stringify(manifest, null, 2) + "\n", "utf8");
const items = manifest.nav.reduce((n, s) => n + s.items.length, 0);
console.log(
`Wrote ${manifest.nav.length} sections, ${items} docs → ${OUT.replace(/.*[/\\]frontend[/\\]/, "frontend/")}`,
);
for (const s of manifest.nav) {
console.log(` ${s.icon} ${s.label} (${s.items.length})`);
}
}
main().catch((err) => {
console.error(err instanceof Error ? err.message : err);
process.exitCode = 1;
});
+3 -1
View File
@@ -4,7 +4,9 @@
"module": "node16",
"moduleResolution": "node16",
"types": ["node"],
"noEmit": true
"noEmit": true,
// sync-portal-docs.mts imports the shared transform by its .ts path (run via tsx).
"allowImportingTsExtensions": true
},
"include": ["./**/*.ts", "./**/*.mts"]
}
+1 -1
View File
@@ -2,7 +2,7 @@
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Stirling PDF",
"mainBinaryName": "Stirling-PDF",
"version": "2.14.2",
"version": "2.14.1",
"identifier": "stirling.pdf.dev",
"build": {
"frontendDist": "../dist",
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
appVersion: "2.14.2",
appVersion: "2.14.1",
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
serverPort: 8080,
+31 -42
View File
@@ -19,12 +19,6 @@ export interface TableProps<T> {
rowKey: (row: T) => string;
/** Makes rows interactive (hover + click + keyboard). */
onRowClick?: (row: T) => void;
/**
* Per-row gate for interactivity, checked only when {@link onRowClick} is set. A row for which
* this returns false is inert: no click/keyboard, and not announced as a button. Defaults to
* all rows interactive.
*/
isRowInteractive?: (row: T) => boolean;
/** Rendered in place of the body when there are no rows. */
empty?: ReactNode;
className?: string;
@@ -41,7 +35,6 @@ export function Table<T>({
rows,
rowKey,
onRowClick,
isRowInteractive,
empty,
className,
}: TableProps<T>) {
@@ -73,42 +66,38 @@ export function Table<T>({
</td>
</tr>
) : (
rows.map((row) => {
const rowInteractive =
interactive && (isRowInteractive?.(row) ?? true);
return (
<tr
key={rowKey(row)}
className={
rowInteractive
? "sui-table__row sui-table__row--interactive"
: "sui-table__row"
}
onClick={rowInteractive ? () => onRowClick?.(row) : undefined}
tabIndex={rowInteractive ? 0 : undefined}
role={rowInteractive ? "button" : undefined}
onKeyDown={
rowInteractive
? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onRowClick?.(row);
}
rows.map((row) => (
<tr
key={rowKey(row)}
className={
interactive
? "sui-table__row sui-table__row--interactive"
: "sui-table__row"
}
onClick={onRowClick ? () => onRowClick(row) : undefined}
tabIndex={interactive ? 0 : undefined}
role={interactive ? "button" : undefined}
onKeyDown={
interactive
? (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onRowClick?.(row);
}
: undefined
}
>
{columns.map((c) => (
<td
key={c.key}
className={`sui-table__td sui-table__td--${c.align ?? "left"}`}
>
{c.render(row)}
</td>
))}
</tr>
);
})
}
: undefined
}
>
{columns.map((c) => (
<td
key={c.key}
className={`sui-table__td sui-table__td--${c.align ?? "left"}`}
>
{c.render(row)}
</td>
))}
</tr>
))
)}
</tbody>
</table>
+16 -13
View File
@@ -1,3 +1,4 @@
import { lazy, Suspense } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { Home } from "@portal/views/Home";
import { Users } from "@portal/views/Users";
@@ -5,17 +6,21 @@ import { Documents } from "@portal/views/Documents";
import { Pipelines } from "@portal/views/Pipelines";
import { PipelineBuilder } from "@portal/views/PipelineBuilder";
import { Sources } from "@portal/views/Sources";
import { SourceBuilder } from "@portal/views/SourceBuilder";
import { AgentBuilder } from "@portal/views/AgentBuilder";
import { Policies } from "@portal/views/Policies";
import { Components } from "@portal/views/Components";
import { EditorAdmin } from "@portal/views/EditorAdmin";
import { Infrastructure } from "@portal/views/Infrastructure";
import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";
import { DeveloperDocs } from "@portal/views/DeveloperDocs";
import { Procurement } from "@portal/views/Procurement";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
// Lazy so the generated docs manifest (bundled JSON) lands in its own chunk.
const DeveloperDocs = lazy(() =>
import("@portal/views/DeveloperDocs").then((m) => ({
default: m.DeveloperDocs,
})),
);
// The portal mounts as a route-set under /processor/* in the editor app, so these
// child routes are relative to that base: strip the leading slash from the
// logical VIEW_PATHS, and home is the index route. Redirects use toPortalPath
@@ -37,21 +42,12 @@ export function ViewRouter() {
element={<PipelineBuilder />}
/>
<Route path={rel(VIEW_PATHS.sources)} element={<Sources />} />
<Route
path={`${rel(VIEW_PATHS.sources)}/new`}
element={<SourceBuilder />}
/>
<Route
path={`${rel(VIEW_PATHS.sources)}/:id`}
element={<SourceBuilder />}
/>
<Route
path={rel(VIEW_PATHS["agent-builder"])}
element={<AgentBuilder />}
/>
<Route path={rel(VIEW_PATHS.policies)} element={<Policies />} />
<Route path={rel(VIEW_PATHS.documents)} element={<Documents />} />
<Route path={rel(VIEW_PATHS.components)} element={<Components />} />
<Route path={rel(VIEW_PATHS.editor)} element={<EditorAdmin />} />
<Route
path={rel(VIEW_PATHS.infrastructure)}
@@ -59,7 +55,14 @@ export function ViewRouter() {
/>
<Route path={rel(VIEW_PATHS.usage)} element={<PortalBillingGate />} />
<Route path={rel(VIEW_PATHS.procurement)} element={<Procurement />} />
<Route path={rel(VIEW_PATHS.docs)} element={<DeveloperDocs />} />
<Route
path={rel(VIEW_PATHS.docs)}
element={
<Suspense fallback={null}>
<DeveloperDocs />
</Suspense>
}
/>
{/* Account-link is now a Settings panel; redirect legacy bookmarks home. */}
<Route
path="account-link"
-5
View File
@@ -99,11 +99,6 @@ export const AGENT_STATUS_TONE: Record<AgentStatus, "success" | "neutral"> = {
draft: "neutral",
};
export const AGENT_STATUS_LABEL: Record<AgentStatus, string> = {
published: "portal.agentBuilder.status.published",
draft: "portal.agentBuilder.status.draft",
};
/**
* Catalogue of tools an agent can be granted or denied. Surfaced as the chip
* palette in restricted mode so the deny list is picked from a known set
@@ -119,14 +119,13 @@ export interface EditorDeploymentResponse {
/* ──────────────────────────────────────────────────────────────────────── */
export interface TargetMeta {
icon: string;
tone: "neutral" | "blue" | "purple";
}
export const TARGET_META: Record<TargetKind, TargetMeta> = {
cloud: { icon: "☁", tone: "blue" },
docker: { icon: "▣", tone: "neutral" },
kubernetes: { icon: "⎈", tone: "purple" },
cloud: { tone: "blue" },
docker: { tone: "neutral" },
kubernetes: { tone: "purple" },
};
export const INSTANCE_STATUS_TONE: Record<
@@ -1,74 +0,0 @@
/**
* Integrations service layer: stored connections (S3 today; MCP/API later) that
* policy sources and pipeline outputs reference by id instead of embedding
* credentials. Secrets are write-only - reads return them masked, and sending
* the mask back on update keeps the stored value.
*/
import { apiClient } from "@portal/api/http";
export type IntegrationType = "S3" | "MCP" | "API";
export type OwnerScope = "USER" | "TEAM" | "SERVER";
/** Mirrors the backend IntegrationConfigResponse; `config` values are masked. */
export interface IntegrationConfig {
id: number;
integrationType: IntegrationType;
name: string;
scope: OwnerScope;
ownerUserId: number | null;
ownerTeamId: number | null;
enabled: boolean;
locked: boolean;
defaultAccess: string;
config: Record<string, unknown>;
canManage: boolean;
createdAt: string;
updatedAt: string;
}
/** Create/update body; omitted fields keep their stored values on update. */
export interface IntegrationConfigRequest {
integrationType?: IntegrationType;
name?: string;
scope?: OwnerScope;
ownerTeamId?: number | null;
enabled?: boolean;
config?: Record<string, unknown>;
}
export async function fetchIntegrations(): Promise<IntegrationConfig[]> {
return apiClient.local.json<IntegrationConfig[]>("/api/v1/integrations");
}
/** The S3 connections the caller may use, for source/output pickers. */
export async function fetchS3Connections(): Promise<IntegrationConfig[]> {
return (await fetchIntegrations()).filter(
(integration) => integration.integrationType === "S3",
);
}
export async function createIntegration(
body: IntegrationConfigRequest,
): Promise<IntegrationConfig> {
return apiClient.local.json<IntegrationConfig>("/api/v1/integrations", {
method: "POST",
body,
});
}
export async function updateIntegration(
id: number,
body: IntegrationConfigRequest,
): Promise<IntegrationConfig> {
return apiClient.local.json<IntegrationConfig>(
`/api/v1/integrations/${encodeURIComponent(id)}`,
{ method: "PUT", body },
);
}
export async function deleteIntegration(id: number): Promise<void> {
await apiClient.local.json<void>(
`/api/v1/integrations/${encodeURIComponent(id)}`,
{ method: "DELETE" },
);
}
+2 -17
View File
@@ -9,7 +9,6 @@
* approach the editor uses for its own catalogue view.
*/
import type { TFunction } from "i18next";
import { apiClient } from "@portal/api/http";
import { fromWirePolicy, toWirePolicy } from "@app/policies/codec";
import { runsToActivity, runsToStats } from "@app/policies/runs";
@@ -557,30 +556,17 @@ const DEFAULT_RETRY_DELAY = 5;
// POST /api/v1/policies endpoint. The real backend ignores unknown fields.
type CatalogueWireBody = WirePolicy & { categoryId: string };
/**
* The persisted policy name derived from its category, e.g. "Security Policy".
* `category.label` is an i18n key, so translate it before building the name;
* otherwise the raw key is persisted and surfaces in the UI (e.g. the Sources
* "Used by" pill).
*/
function policyDisplayName(entry: CatalogueEntry, t: TFunction): string {
return t("portal.policies.defaultName", {
category: t(entry.category.label),
});
}
/** Build a wire policy from a setup wizard result. */
export function buildWireFromSetup(
entry: CatalogueEntry,
result: PolicySetupResult,
t: TFunction,
enabled = true,
): CatalogueWireBody {
return {
categoryId: entry.category.id,
...toWirePolicy({
id: entry.policy?.state.backendId ?? "",
name: policyDisplayName(entry, t),
name: `${entry.category.label} Policy`,
enabled,
categoryId: entry.category.id,
sources: result.sources,
@@ -603,14 +589,13 @@ export function buildWireFromState(
entry: CatalogueEntry,
policy: DecoratedPolicy,
enabled: boolean,
t: TFunction,
): CatalogueWireBody {
const s = policy.state;
return {
categoryId: entry.category.id,
...toWirePolicy({
id: s.backendId ?? "",
name: policyDisplayName(entry, t),
name: `${entry.category.label} Policy`,
enabled,
categoryId: entry.category.id,
sources: s.sources,
@@ -1,138 +0,0 @@
import { apiClient } from "@portal/api/http";
import type { Tier } from "@portal/contexts/TierContext";
/*
* "Components" are embeddable React/Vue/Vanilla SDK widgets a developer drops
* into their own product — a PDF Viewer, an E-Sign flow, an AI Review panel —
* each metered per action (per render, per review, per signature). Every
* component carries its npm package, maturity, supported frameworks, per-action
* price, an install/usage snippet, and its key props.
*/
/* ──────────────────────────────────────────────────────────────────────── */
/* Types */
/* ──────────────────────────────────────────────────────────────────────── */
export type ComponentMaturity = "ga" | "beta";
export type Framework = "React" | "Vue" | "Vanilla";
/** The action a component bills against — surfaces in the price unit label. */
export type BillingUnit =
| "render"
| "review"
| "approval"
| "signature"
| "check"
| "event"
| "session";
export interface ComponentProp {
name: string;
/** TypeScript-ish type expression, shown verbatim in the API table. */
type: string;
required: boolean;
description: string;
}
export interface ComponentPricing {
/** Price per billed action in USD. */
pricePerAction: number;
unit: BillingUnit;
/** Free-tier monthly allowance before metering kicks in; 0 = none. */
freeQuota: number;
}
export interface SdkComponent {
id: string;
name: string;
/** Package suffix — full name is `@stirling/<package>`. */
package: string;
description: string;
maturity: ComponentMaturity;
frameworks: Framework[];
pricing: ComponentPricing;
/** Install command (npm). */
install: string;
/** Minimal usage snippet shown under the Code tab. */
usage: string;
props: ComponentProp[];
/**
* Embeds attributed to this component over the trailing 30 days — drives the
* per-card usage line. Zero for never-embedded components.
*/
embeds30d: number;
/**
* Tier at which the component becomes available. Components above the active
* tier render locked with an upgrade nudge. `pro` is the default floor.
*/
minTier: Tier;
}
export interface ComponentsSummary {
/** Count of GA (production-ready) components available to the tier. */
gaCount: number;
/** Count of Beta components available to the tier. */
betaCount: number;
/** Total embeds across all components this month. */
embedsThisMonth: number;
/** Month-to-date spend attributed to component actions, in USD. */
spendThisMonth: number;
}
export interface ComponentsResponse {
summary: ComponentsSummary;
components: SdkComponent[];
}
/* ──────────────────────────────────────────────────────────────────────── */
/* Presentation metadata (client-side product copy, not data) */
/* ──────────────────────────────────────────────────────────────────────── */
export interface MaturityMeta {
label: string;
tone: "success" | "info";
}
/** `label` values are i18n keys — render with t(). */
export const MATURITY_META: Record<ComponentMaturity, MaturityMeta> = {
ga: { label: "portal.components.maturity.ga", tone: "success" },
beta: { label: "portal.components.maturity.beta", tone: "info" },
};
/** Values are i18n keys — render with t(). */
export const BILLING_UNIT_LABEL: Record<BillingUnit, string> = {
render: "portal.components.billingUnit.render",
review: "portal.components.billingUnit.review",
approval: "portal.components.billingUnit.approval",
signature: "portal.components.billingUnit.signature",
check: "portal.components.billingUnit.check",
event: "portal.components.billingUnit.event",
session: "portal.components.billingUnit.session",
};
/** Format a price as the per-action string shown on cards, e.g. "$0.04 / review". */
export function formatPrice(
pricing: ComponentPricing,
t: (key: string) => string,
): string {
return `$${pricing.pricePerAction.toFixed(2)} / ${t(BILLING_UNIT_LABEL[pricing.unit])}`;
}
const TIER_RANK: Record<Tier, number> = { free: 0, pro: 1, enterprise: 2 };
/** Whether a component is usable at the given tier (vs locked/upgrade). */
export function isUnlocked(component: SdkComponent, tier: Tier): boolean {
return TIER_RANK[tier] >= TIER_RANK[component.minTier];
}
/* ──────────────────────────────────────────────────────────────────────── */
/* Endpoints */
/* ──────────────────────────────────────────────────────────────────────── */
/** GET /v1/components?tier=… — summary strip + the embeddable SDK catalogue. */
export async function fetchComponents(tier: Tier): Promise<ComponentsResponse> {
return apiClient.local.json<ComponentsResponse>(
`/v1/components?tier=${encodeURIComponent(tier)}`,
);
}
+9 -14
View File
@@ -1,7 +1,3 @@
// The bare i18next singleton (the same instance @app/i18n initializes at
// startup), imported directly so this data module doesn't pull i18n's
// init side effects into unit tests that mock react-i18next.
import i18n from "i18next";
import { apiClient } from "@portal/api/http";
import type { Tier } from "@portal/contexts/TierContext";
@@ -273,23 +269,22 @@ function roleIdFor(u: AdminUserSummaryDto): RoleId {
/** A member's last-seen time as plain language; "Never" when no session is tracked. */
function relativeTime(value: number | string | undefined): string {
if (value === undefined || value === null)
return i18n.t("users.activity.never");
if (value === undefined || value === null) return "Never";
const ts = typeof value === "string" ? Date.parse(value) : value;
if (!Number.isFinite(ts) || ts <= 0) return i18n.t("users.activity.never");
if (!Number.isFinite(ts) || ts <= 0) return "Never";
const mins = Math.max(0, Math.round((Date.now() - ts) / 60000));
if (mins < 1) return i18n.t("users.activity.justNow");
if (mins < 60) return i18n.t("users.activity.minutesAgo", { count: mins });
if (mins < 1) return "Just now";
if (mins < 60) return `${mins}m ago`;
const hours = Math.round(mins / 60);
if (hours < 24) return i18n.t("users.activity.hoursAgo", { count: hours });
if (hours < 24) return `${hours}h ago`;
const days = Math.round(hours / 24);
if (days < 7) return i18n.t("users.activity.daysAgo", { count: days });
if (days < 7) return `${days}d ago`;
const weeks = Math.round(days / 7);
if (weeks < 5) return i18n.t("users.activity.weeksAgo", { count: weeks });
if (weeks < 5) return weeks === 1 ? "1 week ago" : `${weeks} weeks ago`;
const months = Math.round(days / 30);
if (months < 12) return i18n.t("users.activity.monthsAgo", { count: months });
if (months < 12) return months <= 1 ? "1 month ago" : `${months} months ago`;
const years = Math.round(days / 365);
return i18n.t("users.activity.yearsAgo", { count: years });
return years <= 1 ? "1 year ago" : `${years} years ago`;
}
/** 0 / huge sentinel license values mean "no seat limit". */
@@ -15,7 +15,7 @@ import {
type CatalogueEntry,
type PoliciesResponse,
} from "@portal/api/policies";
import { policyIcon } from "@portal/components/policies/policyIcons";
import { PolicyCategoryBadge } from "@portal/components/policies/PolicyCategoryIcon";
import "@portal/components/PolicySummary.css";
/**
@@ -63,9 +63,7 @@ export function PolicySummary() {
header: t("portal.policySummary.column.policy"),
render: ({ entry }) => (
<div className="portal-policysum__cat">
<span className="portal-policysum__icon" aria-hidden>
{policyIcon(entry.category.icon)}
</span>
<PolicyCategoryBadge category={entry.category} />
<div className="portal-policysum__cat-text">
<strong>{t(entry.category.label)}</strong>
<span>{t(entry.category.desc)}</span>
@@ -26,7 +26,7 @@ export function ProcessingStatusStrip() {
style={{ background: TIER_INFO[tier].dotColor }}
aria-hidden
/>
{t(TIER_INFO[tier].labelKey)}
{TIER_INFO[tier].label}
</span>
<span className="portal-statusstrip__sep" aria-hidden>
·
@@ -1,11 +1,7 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { StatusBadge, Tabs, type TabItem } from "@app/ui";
import {
type Agent,
AGENT_STATUS_LABEL,
AGENT_STATUS_TONE,
} from "@portal/api/agents";
import { type Agent, AGENT_STATUS_TONE } from "@portal/api/agents";
import { ScenariosPanel } from "@portal/components/agent-builder/ScenariosPanel";
import { ToolsPanel } from "@portal/components/agent-builder/ToolsPanel";
import { EvalsPanel } from "@portal/components/agent-builder/EvalsPanel";
@@ -56,7 +52,7 @@ export function AgentBuilderPanel({
</div>
<div className="portal-agents__builder-meta">
<StatusBadge tone={AGENT_STATUS_TONE[agent.status]} size="sm">
{t(AGENT_STATUS_LABEL[agent.status])}
{agent.status}
</StatusBadge>
<code className="portal-agents__builder-version">
{agent.version}
@@ -1,9 +1,5 @@
import { useTranslation } from "react-i18next";
import {
type Agent,
AGENT_STATUS_LABEL,
AGENT_STATUS_TONE,
} from "@portal/api/agents";
import { type Agent, AGENT_STATUS_TONE } from "@portal/api/agents";
import { Button, StatusBadge } from "@app/ui";
import "@portal/views/AgentBuilder.css";
@@ -44,7 +40,7 @@ export function AgentSelector({
</span>
<span className="portal-agents__selector-meta">
<StatusBadge tone={AGENT_STATUS_TONE[a.status]} size="sm">
{t(AGENT_STATUS_LABEL[a.status])}
{a.status}
</StatusBadge>
<code className="portal-agents__selector-version">{a.version}</code>
</span>
@@ -1,10 +1,6 @@
import { useTranslation } from "react-i18next";
import { Button, StatusBadge } from "@app/ui";
import {
type Agent,
AGENT_STATUS_LABEL,
AGENT_STATUS_TONE,
} from "@portal/api/agents";
import { type Agent, AGENT_STATUS_TONE } from "@portal/api/agents";
import "@portal/views/AgentBuilder.css";
interface VersionsPanelProps {
@@ -56,7 +52,7 @@ export function VersionsPanel({ agent, historyUnlocked }: VersionsPanelProps) {
{v.version}
</code>
<StatusBadge tone={AGENT_STATUS_TONE[v.status]} size="sm">
{t(AGENT_STATUS_LABEL[v.status])}
{v.status}
</StatusBadge>
{isCurrent && (
<StatusBadge tone="info" size="sm" showDot={false}>
@@ -35,7 +35,11 @@ export function EnterpriseUpsell({ bare = false }: Props) {
)}
</p>
</div>
<Button size="sm" onClick={() => setActiveView("procurement")}>
<Button
size="sm"
variant="secondary"
onClick={() => setActiveView("procurement")}
>
{t("portal.billing.enterpriseUpsell.cta", "Explore Enterprise")}
</Button>
</div>
@@ -119,7 +119,7 @@
/* Free grant still offsetting spend — reads as a positive credit note, pulled up
under the "PDFs processed" line. */
.portal-billing__free-remaining {
color: var(--color-green-600, var(--color-green));
color: var(--color-green);
margin-top: -0.5rem;
}
@@ -171,7 +171,7 @@
}
.portal-billing__error {
color: var(--color-red, #b91c1c);
color: var(--color-red, var(--color-red-dark));
font-size: 0.875rem;
margin: 0.5rem 0;
}
@@ -228,11 +228,7 @@
.portal-billing__meter-fill {
height: 100%;
background: linear-gradient(
90deg,
var(--color-blue, #0a8bff),
var(--color-purple, #8b5cf6)
);
background: linear-gradient(90deg, var(--color-blue), var(--color-purple));
border-radius: 999px;
transition: width 200ms ease;
}
@@ -308,28 +304,28 @@
border-radius: 999px;
}
.payg-status[data-state="FULL"] {
background: #dcfce7;
color: #15803d;
background: var(--color-green-light);
color: var(--color-green-dark);
}
.payg-status[data-state="FULL"] .payg-status__dot {
background: #22c55e;
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.18);
background: var(--color-green);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-green) 18%, transparent);
}
.payg-status[data-state="WARNED"] {
background: #fef3c7;
color: #a16207;
background: var(--color-amber-light);
color: var(--color-amber-dark);
}
.payg-status[data-state="WARNED"] .payg-status__dot {
background: #eab308;
box-shadow: 0 0 0 3px rgba(234, 179, 8, 0.2);
background: var(--color-amber);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-amber) 20%, transparent);
}
.payg-status[data-state="DEGRADED"] {
background: #fee2e2;
color: #b91c1c;
background: var(--color-red-light);
color: var(--color-red-dark);
}
.payg-status[data-state="DEGRADED"] .payg-status__dot {
background: #ef4444;
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.2);
background: var(--color-red);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-red) 20%, transparent);
}
/* Segmented usage bar */
@@ -347,13 +343,13 @@
transition: width 0.5s cubic-bezier(0.16, 1, 0.3, 1);
}
.payg-bar__fill[data-state="FULL"] {
background: linear-gradient(90deg, #0a8bff, #38bdf8);
background: var(--color-blue);
}
.payg-bar__fill[data-state="WARNED"] {
background: linear-gradient(90deg, #f59e0b, #fbbf24);
background: var(--color-amber);
}
.payg-bar__fill[data-state="DEGRADED"] {
background: linear-gradient(90deg, #dc2626, #f87171);
background: var(--color-red);
}
/* ── Plan card (free state) ─────────────────────────────────────────────── */
@@ -394,7 +390,7 @@
.portal-billing__plan-features li::before {
content: "✓";
color: var(--color-green, #10b981);
color: var(--color-green);
position: absolute;
left: 0;
font-weight: 600;
@@ -457,15 +453,15 @@
}
.portal-billing__breakdown-fill--blue {
background: #0a8bff;
background: var(--color-blue);
}
.portal-billing__breakdown-fill--purple {
background: #8b5cf6;
background: var(--color-purple);
}
.portal-billing__breakdown-fill--teal {
background: #06b6d4;
background: var(--color-cat-extraction);
}
/* ── Cap control ────────────────────────────────────────────────────────── */
@@ -570,10 +566,10 @@
Same class names + structure so the visual is identical to the SaaS Plan
page; when the shared-component move lands, these dedupe to one stylesheet. */
.scc {
--scc-accent: #0a8bff;
--scc-accent-text: #0a8bff;
--scc-accent-soft: rgba(10, 139, 255, 0.12);
--scc-accent-border: rgba(10, 139, 255, 0.25);
--scc-accent: var(--color-blue);
--scc-accent-text: var(--color-blue);
--scc-accent-soft: color-mix(in srgb, var(--color-blue) 12%, transparent);
--scc-accent-border: color-mix(in srgb, var(--color-blue) 25%, transparent);
--scc-chip-bg: var(--color-bg-muted, #f8fafc);
--scc-chip-border: var(--color-border, #e2e8f0);
--scc-text-primary: var(--color-text-1, #0f172a);
@@ -585,11 +581,11 @@
gap: 14px;
margin-top: 0.75rem;
}
[data-mantine-color-scheme="dark"] .scc {
--scc-accent-text: #66b8ff;
--scc-accent-soft: rgba(10, 139, 255, 0.16);
--scc-chip-bg: #272d35;
--scc-chip-border: #3d444e;
[data-theme="dark"] .scc {
--scc-accent-text: var(--color-blue);
--scc-accent-soft: color-mix(in srgb, var(--color-blue) 16%, transparent);
--scc-chip-bg: var(--color-bg-muted);
--scc-chip-border: var(--color-border);
}
.scc-row {
@@ -736,9 +732,9 @@
white-space: nowrap;
}
.portal-billing__role-pill[data-leader="true"] {
background: rgba(10, 139, 255, 0.12);
color: #0a8bff;
border: 1px solid rgba(10, 139, 255, 0.25);
background: color-mix(in srgb, var(--color-blue) 12%, transparent);
color: var(--color-blue);
border: 1px solid color-mix(in srgb, var(--color-blue) 25%, transparent);
}
.portal-billing__role-pill[data-leader="false"] {
background: var(--color-bg-muted);
@@ -768,10 +764,10 @@
margin-bottom: 8px;
}
.portal-billing__planhead-lbl--free {
color: #10b981;
color: var(--color-green);
}
.portal-billing__planhead-lbl--meter {
color: #0a8bff;
color: var(--color-blue);
}
.portal-billing__planhead-title {
margin: 0;
@@ -839,7 +835,7 @@
.portal-billing__invoice-link:focus-visible {
outline: none;
border-color: var(--color-blue, #0a8bff);
border-color: var(--color-blue);
background: var(--color-bg-muted, #f1f5f9);
}
@@ -953,6 +949,12 @@
align-items: flex-start;
gap: 1rem;
}
/* Keep the CTA on one line at its natural width — in the narrow subscribed
column it was shrinking and clipping its label. */
.portal-billing__enterprise-head > .sui-btn {
flex-shrink: 0;
white-space: nowrap;
}
/* Bare variant — embeds in another card's column without its own surface. */
.portal-billing__enterprise-bare {
display: block;
@@ -988,13 +990,13 @@
height: 100%;
}
.portal-billing__segbar-seg--blue {
background: #0a8bff;
background: var(--color-blue);
}
.portal-billing__segbar-seg--purple {
background: #8b5cf6;
background: var(--color-purple);
}
.portal-billing__segbar-seg--teal {
background: #06b6d4;
background: var(--color-cat-extraction);
}
.portal-billing__seglegend {
display: flex;
@@ -1016,13 +1018,13 @@
flex-shrink: 0;
}
.portal-billing__dot--blue {
background: #0a8bff;
background: var(--color-blue);
}
.portal-billing__dot--purple {
background: #8b5cf6;
background: var(--color-purple);
}
.portal-billing__dot--teal {
background: #06b6d4;
background: var(--color-cat-extraction);
}
.portal-billing__seglegend-label {
font-weight: 600;
@@ -1,27 +0,0 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { componentsFor } from "@portal/mocks/sdkComponents";
import { ComponentCard } from "@portal/components/catalogue/ComponentCard";
const PRO = componentsFor("pro");
const GA = PRO.find((c) => c.maturity === "ga")!;
const BETA = PRO.find((c) => c.maturity === "beta")!;
const meta: Meta<typeof ComponentCard> = {
title: "Portal/Components/ComponentCard",
component: ComponentCard,
parameters: { layout: "padded" },
args: { component: GA, unlocked: true, onOpen: () => {} },
};
export default meta;
type Story = StoryObj<typeof ComponentCard>;
export const GeneralAvailability: Story = {};
export const Beta: Story = {
args: { component: BETA },
};
/** Sits above the tier — dimmed with a lock affordance. */
export const Locked: Story = {
args: { component: BETA, unlocked: false },
};
@@ -1,79 +0,0 @@
import { useTranslation } from "react-i18next";
import { Card, Chip, StatusBadge } from "@app/ui";
import {
type SdkComponent,
MATURITY_META,
formatPrice,
} from "@portal/api/sdkComponents";
import "@portal/views/Components.css";
interface ComponentCardProps {
component: SdkComponent;
/** False when the component sits above the active tier — renders locked. */
unlocked: boolean;
onOpen: (component: SdkComponent) => void;
}
/** A single catalogue tile: name, maturity, description, price and frameworks. */
export function ComponentCard({
component,
unlocked,
onOpen,
}: ComponentCardProps) {
const { t } = useTranslation();
const maturity = MATURITY_META[component.maturity];
return (
<Card
interactive
padding="default"
className={"portal-components__card" + (unlocked ? "" : " is-locked")}
role="button"
tabIndex={0}
aria-label={t("portal.catalogue.card.openAriaLabel", {
name: component.name,
})}
onClick={() => onOpen(component)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onOpen(component);
}
}}
>
<div className="portal-components__card-head">
<h3 className="portal-components__card-name">{component.name}</h3>
<StatusBadge tone={maturity.tone} size="sm" showDot={false}>
{t(maturity.label)}
</StatusBadge>
{!unlocked && (
<span
className="portal-components__lock"
aria-label={t("portal.catalogue.card.lockedAriaLabel")}
>
🔒
</span>
)}
</div>
<p className="portal-components__card-desc">{component.description}</p>
<div className="portal-components__card-meta">
<span className="portal-components__price">
{formatPrice(component.pricing, t)}
</span>
<span className="portal-components__pkg">
@stirling/{component.package}
</span>
</div>
<div className="portal-components__frameworks">
{component.frameworks.map((fw) => (
<Chip key={fw} size="sm">
{fw}
</Chip>
))}
</div>
</Card>
);
}
@@ -1,27 +0,0 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { componentsFor } from "@portal/mocks/sdkComponents";
import { ComponentDetailModal } from "@portal/components/catalogue/ComponentDetailModal";
const PRO = componentsFor("pro");
const VIEWER = PRO.find((c) => c.id === "viewer")!;
const TOOLKIT = PRO.find((c) => c.id === "toolkit")!;
const meta: Meta<typeof ComponentDetailModal> = {
title: "Portal/Components/ComponentDetailModal",
component: ComponentDetailModal,
parameters: { layout: "fullscreen" },
args: { component: VIEWER, unlocked: true, onClose: () => {} },
};
export default meta;
type Story = StoryObj<typeof ComponentDetailModal>;
export const Unlocked: Story = {};
/** Enterprise-only component opened on a lower tier — shows the upgrade nudge. */
export const Locked: Story = {
args: { component: TOOLKIT, unlocked: false },
};
export const Closed: Story = {
args: { component: null },
};
@@ -1,233 +0,0 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
Banner,
Button,
Chip,
CodeBlock,
Modal,
StatTile,
StatusBadge,
Tabs,
} from "@app/ui";
import {
type SdkComponent,
BILLING_UNIT_LABEL,
MATURITY_META,
formatPrice,
} from "@portal/api/sdkComponents";
import { TIER_INFO } from "@portal/contexts/TierContext";
import { ComponentPropsTable } from "@portal/components/catalogue/ComponentPropsTable";
import "@portal/views/Components.css";
type DetailTab = "overview" | "code" | "props" | "pricing";
const TAB_KEYS: DetailTab[] = ["overview", "code", "props", "pricing"];
interface ComponentDetailModalProps {
component: SdkComponent | null;
/** False when the open component sits above the active tier. */
unlocked: boolean;
onClose: () => void;
}
/**
* Detail overlay for a catalogue component: a live-preview placeholder plus
* Overview / Code / Props / Pricing tabs. Locked components swap the install
* CTA for an upgrade nudge.
*/
export function ComponentDetailModal({
component,
unlocked,
onClose,
}: ComponentDetailModalProps) {
const { t } = useTranslation();
const [tab, setTab] = useState<DetailTab>("overview");
// Reset to the first tab whenever a new component is opened.
const open = component !== null;
if (!component) {
return (
<Modal
open={false}
onClose={onClose}
ariaLabel={t("portal.catalogue.detail.ariaLabel")}
/>
);
}
const tabs = TAB_KEYS.map((key) => ({
key,
label: t(`portal.catalogue.detail.tabs.${key}`),
}));
const maturity = MATURITY_META[component.maturity];
const npm = `@stirling/${component.package}`;
return (
<Modal
key={component.id}
open={open}
onClose={() => {
onClose();
setTab("overview");
}}
width="xl"
title={
<span className="portal-components__modal-title">
{component.name}
<StatusBadge tone={maturity.tone} size="sm" showDot={false}>
{t(maturity.label)}
</StatusBadge>
</span>
}
subtitle={npm}
footer={
unlocked ? (
<div className="portal-components__modal-footer">
<span className="portal-components__price">
{formatPrice(component.pricing, t)}
</span>
<Button
size="sm"
// TODO(backend): open the package quickstart / provision a
// publishable key scoped to this component.
onClick={() => onClose()}
>
{t("portal.catalogue.detail.addToProject")}
</Button>
</div>
) : (
<Button
size="sm"
accent="premium"
// TODO(backend): route to the upgrade / contact-sales flow.
onClick={() => onClose()}
>
{t("portal.catalogue.detail.upgradeToUnlock")}
</Button>
)
}
>
{!unlocked && (
<Banner
tone="warning"
title={t("portal.catalogue.detail.locked.title")}
description={t("portal.catalogue.detail.locked.description", {
name: component.name,
plan: t(TIER_INFO[component.minTier].labelKey),
})}
/>
)}
{/* Live-preview sandbox — a styled placeholder until a real host mounts. */}
<div className="portal-components__preview" aria-hidden>
{/* TODO(backend)/host: mount the live <Sandbox> here, booting the
component against a demo document and the dev's publishable key. */}
<span className="portal-components__preview-badge">
{t("portal.catalogue.detail.preview.badge")}
</span>
<span className="portal-components__preview-note">
{t("portal.catalogue.detail.preview.note")}
</span>
</div>
<Tabs<DetailTab>
className="portal-components__tabs"
items={tabs}
activeKey={tab}
onChange={setTab}
variant="underline"
ariaLabel={t("portal.catalogue.detail.tabsAriaLabel")}
/>
<div className="portal-components__tab-body">
{tab === "overview" && (
<div className="portal-components__overview">
<p className="portal-components__overview-desc">
{component.description}
</p>
<div className="portal-components__frameworks">
{component.frameworks.map((fw) => (
<Chip key={fw} size="sm">
{fw}
</Chip>
))}
</div>
<div className="portal-components__stat-grid">
<StatTile
label={t("portal.catalogue.detail.stats.maturity")}
value={t(maturity.label)}
/>
<StatTile
label={t("portal.catalogue.detail.stats.price")}
value={formatPrice(component.pricing, t)}
/>
<StatTile
label={t("portal.catalogue.detail.stats.freeQuota")}
value={
component.pricing.freeQuota > 0
? t("portal.catalogue.detail.stats.freeQuotaValue", {
amount: component.pricing.freeQuota.toLocaleString(),
})
: t("portal.catalogue.detail.stats.none")
}
/>
<StatTile
label={t("portal.catalogue.detail.stats.embeds30d")}
value={component.embeds30d.toLocaleString()}
/>
</div>
</div>
)}
{tab === "code" && (
<div className="portal-components__code">
<CodeBlock
code={component.install}
lang="bash"
caption={t("portal.catalogue.detail.code.install")}
/>
<CodeBlock
code={component.usage}
lang="typescript"
caption={t("portal.catalogue.detail.code.usage")}
/>
</div>
)}
{tab === "props" && <ComponentPropsTable props={component.props} />}
{tab === "pricing" && (
<div className="portal-components__pricing">
<div className="portal-components__stat-grid">
<StatTile
label={t("portal.catalogue.detail.stats.perAction")}
value={formatPrice(component.pricing, t)}
/>
<StatTile
label={t("portal.catalogue.detail.stats.billedOn")}
value={t(BILLING_UNIT_LABEL[component.pricing.unit])}
/>
<StatTile
label={t("portal.catalogue.detail.stats.freeQuota")}
value={
component.pricing.freeQuota > 0
? t("portal.catalogue.detail.stats.freeQuotaValue", {
amount: component.pricing.freeQuota.toLocaleString(),
})
: t("portal.catalogue.detail.stats.none")
}
/>
</div>
<p className="portal-components__pricing-note">
{t("portal.catalogue.detail.pricing.note", {
unit: t(BILLING_UNIT_LABEL[component.pricing.unit]),
})}
</p>
</div>
)}
</div>
</Modal>
);
}
@@ -1,24 +0,0 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { componentsFor } from "@portal/mocks/sdkComponents";
import { ComponentGrid } from "@portal/components/catalogue/ComponentGrid";
const meta: Meta<typeof ComponentGrid> = {
title: "Portal/Components/ComponentGrid",
component: ComponentGrid,
parameters: { layout: "padded" },
args: { components: componentsFor("pro"), tier: "pro", onOpen: () => {} },
};
export default meta;
type Story = StoryObj<typeof ComponentGrid>;
export const Pro: Story = {};
/** Free locks every paid component — the whole grid shows upgrade nudges. */
export const Free: Story = {
args: { components: componentsFor("free"), tier: "free" },
};
/** Enterprise unlocks the enterprise-only Beta components. */
export const Enterprise: Story = {
args: { components: componentsFor("enterprise"), tier: "enterprise" },
};
@@ -1,30 +0,0 @@
import { type SdkComponent, isUnlocked } from "@portal/api/sdkComponents";
import type { Tier } from "@portal/contexts/TierContext";
import { ComponentCard } from "@portal/components/catalogue/ComponentCard";
import "@portal/views/Components.css";
interface ComponentGridProps {
components: SdkComponent[];
tier: Tier;
onOpen: (component: SdkComponent) => void;
}
/** Responsive grid of catalogue cards; locks components above the tier. */
export function ComponentGrid({
components,
tier,
onOpen,
}: ComponentGridProps) {
return (
<div className="portal-components__grid">
{components.map((c) => (
<ComponentCard
key={c.id}
component={c}
unlocked={isUnlocked(c, tier)}
onOpen={onOpen}
/>
))}
</div>
);
}
@@ -1,16 +0,0 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { componentsFor } from "@portal/mocks/sdkComponents";
import { ComponentPropsTable } from "@portal/components/catalogue/ComponentPropsTable";
const VIEWER = componentsFor("pro").find((c) => c.id === "viewer")!;
const meta: Meta<typeof ComponentPropsTable> = {
title: "Portal/Components/ComponentPropsTable",
component: ComponentPropsTable,
parameters: { layout: "padded" },
args: { props: VIEWER.props },
};
export default meta;
type Story = StoryObj<typeof ComponentPropsTable>;
export const Default: Story = {};
@@ -1,62 +0,0 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Chip, Table, type TableColumn } from "@app/ui";
import type { ComponentProp } from "@portal/api/sdkComponents";
import "@portal/views/Components.css";
interface ComponentPropsTableProps {
props: ComponentProp[];
}
/** Small Props/API reference shown under the detail modal's Props tab. */
export function ComponentPropsTable({ props: rows }: ComponentPropsTableProps) {
const { t } = useTranslation();
const columns = useMemo<TableColumn<ComponentProp>[]>(
() => [
{
key: "name",
header: t("portal.catalogue.props.columns.name"),
render: (p) => (
<span className="portal-components__prop-name">{p.name}</span>
),
},
{
key: "type",
header: t("portal.catalogue.props.columns.type"),
render: (p) => (
<code className="portal-components__prop-type">{p.type}</code>
),
},
{
key: "required",
header: t("portal.catalogue.props.columns.required"),
render: (p) =>
p.required ? (
<Chip size="sm" accent="warning">
{t("portal.catalogue.props.required")}
</Chip>
) : (
<span className="portal-components__muted">
{t("portal.catalogue.props.optional")}
</span>
),
},
{
key: "description",
header: t("portal.catalogue.props.columns.description"),
render: (p) => (
<span className="portal-components__prop-desc">{p.description}</span>
),
},
],
[t],
);
return (
<Table<ComponentProp>
columns={columns}
rows={rows}
rowKey={(p) => p.name}
/>
);
}
@@ -1,42 +0,0 @@
import { useTranslation } from "react-i18next";
import { MetricCard, MetricStrip } from "@app/ui";
import type { ComponentsResponse } from "@portal/api/sdkComponents";
/**
* Labels are product copy — they describe what each metric IS, not its value,
* so the strip's structure stays stable across loading / empty / ready states.
* Only values flow from the API.
*/
const KPI_LABEL_KEYS = [
"portal.catalogue.summary.componentsGa",
"portal.catalogue.summary.inBeta",
"portal.catalogue.summary.embedsThisMonth",
"portal.catalogue.summary.componentSpendMtd",
] as const;
interface ComponentsSummaryStripProps {
data: ComponentsResponse | null;
loading: boolean;
}
export function ComponentsSummaryStrip({
data,
loading,
}: ComponentsSummaryStripProps) {
const { t } = useTranslation();
const s = loading ? undefined : data?.summary;
const values: (string | number)[] = [
s?.gaCount ?? "—",
s?.betaCount ?? "—",
s ? s.embedsThisMonth.toLocaleString() : "—",
s ? `$${s.spendThisMonth.toLocaleString()}` : "—",
];
return (
<MetricStrip>
{KPI_LABEL_KEYS.map((labelKey, i) => (
<MetricCard key={labelKey} label={t(labelKey)} value={values[i]} />
))}
</MetricStrip>
);
}
@@ -1,8 +1,45 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { Button, Skeleton, StatusBadge } from "@app/ui";
import { useTranslation } from "react-i18next";
import type { DocsNavSection } from "@portal/api/docs";
/** Left-hand documentation nav tree; each leaf selects an in-page section. */
/**
* Left-hand documentation nav: a hierarchical accordion. Section ids encode their
* path ("functionality/security" is a child of "functionality"), so sub-sections
* nest under their parent. The root "Overview" section is static (always open, no
* toggle); every other section collapses, and only the branch leading to the
* active doc opens by default. (Search lives in DocsSearch above this.)
*/
// Matches the generator's ROOT_SECTION_ID: the intro section is never collapsible.
const STATIC_SECTION_ID = "overview";
interface NavNode {
section: DocsNavSection;
children: NavNode[];
}
/** Split "a/b/c" → "a/b"; null for a top-level id. */
function parentId(id: string): string | null {
const i = id.lastIndexOf("/");
return i === -1 ? null : id.slice(0, i);
}
/** Build the section tree from the flat, pre-sorted section list. */
function buildTree(sections: DocsNavSection[]): NavNode[] {
const byId = new Map<string, NavNode>(
sections.map((s) => [s.id, { section: s, children: [] }]),
);
const roots: NavNode[] = [];
for (const node of byId.values()) {
const pid = parentId(node.section.id);
const parent = pid ? byId.get(pid) : undefined;
if (parent) parent.children.push(node);
else roots.push(node);
}
return roots;
}
export function DocsNav({
sections,
active,
@@ -13,50 +50,125 @@ export function DocsNav({
onSelect: (id: string) => void;
}) {
const { t } = useTranslation();
// Per-section manual open/close, overriding the "active branch only" default.
const [toggled, setToggled] = useState<Record<string, boolean>>({});
const activeRef = useRef<HTMLButtonElement>(null);
const activeSectionId = useMemo(
() => sections.find((s) => s.items.some((i) => i.id === active))?.id,
[sections, active],
);
const tree = useMemo(() => buildTree(sections), [sections]);
// Keep the active item in view when navigating (e.g. via a cross-link).
useEffect(() => {
activeRef.current?.scrollIntoView?.({ block: "nearest" });
}, [active]);
const isOpen = (id: string): boolean => {
if (id === STATIC_SECTION_ID) return true;
// Default-open the branch containing the active doc (self or ancestor).
const onActivePath =
!!activeSectionId &&
(activeSectionId === id || activeSectionId.startsWith(id + "/"));
return toggled[id] ?? onActivePath;
};
const renderNode = (node: NavNode) => {
const { section, children } = node;
const isStatic = section.id === STATIC_SECTION_ID;
const open = isOpen(section.id);
return (
<div key={section.id} className="portal-docs__nav-group">
{isStatic ? (
<div className="portal-docs__nav-head">{section.label}</div>
) : (
<Button
variant="tertiary"
fullWidth
justify="between"
className="portal-docs__nav-head portal-docs__nav-head--button"
aria-expanded={open}
onClick={() =>
setToggled((prev) => ({ ...prev, [section.id]: !open }))
}
rightSection={
<span className="portal-docs__nav-count">
{section.items.length}
</span>
}
>
<span className="portal-docs__nav-head-main">
<span
className={
"portal-docs__nav-chevron" + (open ? " is-open" : "")
}
aria-hidden
>
▸
</span>
<span className="portal-docs__nav-headlabel">
{section.label}
</span>
</span>
</Button>
)}
{open && (
<>
{section.items.length > 0 && (
<ul className="portal-docs__nav-list">
{section.items.map((item) => {
const isActive = item.id === active;
return (
<li key={item.id}>
<Button
ref={isActive ? activeRef : undefined}
variant="tertiary"
justify="start"
fullWidth
className={
"portal-docs__nav-link" +
(isActive ? " is-active" : "")
}
aria-current={isActive ? "page" : undefined}
onClick={() => onSelect(item.id)}
>
<span className="portal-docs__nav-label">
{item.label}
</span>
{item.badge && (
<StatusBadge
tone={item.badge === "New" ? "success" : "info"}
size="sm"
>
{item.badge}
</StatusBadge>
)}
</Button>
</li>
);
})}
</ul>
)}
{children.length > 0 && (
<div className="portal-docs__nav-children">
{children.map(renderNode)}
</div>
)}
</>
)}
</div>
);
};
return (
<nav
className="portal-docs__nav"
aria-label={t("portal.docs.nav.ariaLabel")}
>
{sections.map((section) => (
<div key={section.id} className="portal-docs__nav-group">
<div className="portal-docs__nav-head">
<span className="portal-docs__nav-icon" aria-hidden>
{section.icon}
</span>
{section.label}
</div>
<ul className="portal-docs__nav-list">
{section.items.map((item) => {
const isActive = item.id === active;
return (
<li key={item.id}>
<Button
variant="tertiary"
justify="start"
fullWidth
className={
"portal-docs__nav-link" + (isActive ? " is-active" : "")
}
aria-current={isActive ? "page" : undefined}
onClick={() => onSelect(item.id)}
>
<span className="portal-docs__nav-label">{item.label}</span>
{item.badge && (
<StatusBadge
tone={item.badge === "New" ? "success" : "info"}
size="sm"
>
{item.badge}
</StatusBadge>
)}
</Button>
</li>
);
})}
</ul>
</div>
))}
{tree.map(renderNode)}
</nav>
);
}
@@ -64,14 +176,16 @@ export function DocsNav({
export function DocsNavSkeleton() {
return (
<nav className="portal-docs__nav" aria-hidden>
{Array.from({ length: 4 }).map((_, gi) => (
{Array.from({ length: 5 }).map((_, gi) => (
<div key={gi} className="portal-docs__nav-group">
<Skeleton width="7rem" height="0.75rem" />
<div className="portal-docs__nav-list">
{Array.from({ length: 3 }).map((_, li) => (
<Skeleton key={li} width="80%" height="0.875rem" />
))}
</div>
{gi === 0 && (
<div className="portal-docs__nav-list">
{Array.from({ length: 4 }).map((_, li) => (
<Skeleton key={li} width="80%" height="0.875rem" />
))}
</div>
)}
</div>
))}
</nav>
@@ -0,0 +1,137 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@app/ui";
import type { SearchResult, Segment } from "@portal/docs/search";
/** Render highlighted segments, wrapping matched runs in <mark>. */
function Highlighted({ segments }: { segments: Segment[] }) {
return (
<>
{segments.map((s, i) =>
s.hit ? (
<mark key={i} className="portal-docs__hl">
{s.text}
</mark>
) : (
<span key={i}>{s.text}</span>
),
)}
</>
);
}
/**
* Docs search box + results. While a query is active it shows a ranked list of
* matching docs — each with its section, a highlighted title, and a content
* snippet — that navigates on click (or Enter). Arrow keys move the selection.
*/
export function DocsSearch({
query,
onQueryChange,
results,
onSelect,
}: {
query: string;
onQueryChange: (q: string) => void;
results: SearchResult[];
onSelect: (docId: string) => void;
}) {
const { t } = useTranslation();
// -1 = nothing pre-selected; arrow keys drive this, the mouse uses CSS :hover.
const [activeIndex, setActiveIndex] = useState(-1);
const listRef = useRef<HTMLUListElement>(null);
const hasQuery = query.trim().length > 0;
useEffect(() => setActiveIndex(-1), [query]);
useEffect(() => {
listRef.current
?.querySelector<HTMLElement>('[data-active="true"]')
?.scrollIntoView?.({ block: "nearest" });
}, [activeIndex]);
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Escape") {
onQueryChange("");
return;
}
if (!results.length) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setActiveIndex((i) => Math.min(i + 1, results.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActiveIndex((i) => Math.max(i - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
const hit = results[activeIndex >= 0 ? activeIndex : 0];
if (hit) onSelect(hit.id);
}
};
return (
<div className="portal-docs__search">
<div className="portal-docs__search-box">
<span className="portal-docs__search-icon" aria-hidden>
⌕
</span>
<input
type="search"
className="portal-docs__search-input"
placeholder={t("portal.docs.search.placeholder")}
value={query}
onChange={(e) => onQueryChange(e.target.value)}
onKeyDown={onKeyDown}
aria-label={t("portal.docs.search.placeholder")}
/>
</div>
{hasQuery && (
<div className="portal-docs__results">
{results.length === 0 ? (
<p className="portal-docs__nav-empty">
{t("portal.docs.search.empty")}
</p>
) : (
<>
<div className="portal-docs__results-count">
{t("portal.docs.search.results", { count: results.length })}
</div>
<ul ref={listRef} className="portal-docs__results-list">
{results.map((r, i) => (
<li key={r.id}>
<Button
variant="tertiary"
fullWidth
justify="start"
className={
"portal-docs__result" +
(i === activeIndex ? " is-active" : "")
}
data-active={i === activeIndex}
onClick={() => onSelect(r.id)}
>
<span className="portal-docs__result-body">
<span className="portal-docs__result-head">
<span className="portal-docs__result-title">
<Highlighted segments={r.titleSegments} />
</span>
<span className="portal-docs__result-section">
{r.sectionLabel}
</span>
</span>
<span className="portal-docs__result-snippet">
<Highlighted segments={r.snippet} />
</span>
</span>
</Button>
</li>
))}
</ul>
</>
)}
</div>
)}
</div>
);
}
@@ -0,0 +1,80 @@
import { useEffect, useState, type RefObject } from "react";
import { useTranslation } from "react-i18next";
import type { Heading } from "@portal/docs/headings";
/**
* "On this page" table of contents. Lists the current doc's H2/H3 headings,
* scrolls the reading pane to a heading on click, and highlights the section
* currently in view (scroll-spy against the pane's scroll container).
*/
export function DocsToc({
headings,
scrollRef,
}: {
headings: Heading[];
scrollRef: RefObject<HTMLElement | null>;
}) {
const { t } = useTranslation();
const [active, setActive] = useState<string>(headings[0]?.slug ?? "");
useEffect(() => {
const root = scrollRef.current;
if (!root || headings.length === 0) return;
setActive(headings[0].slug);
const visible = new Set<string>();
const observer = new IntersectionObserver(
(entries) => {
for (const e of entries) {
if (e.isIntersecting) visible.add(e.target.id);
else visible.delete(e.target.id);
}
// The topmost heading currently within the active zone wins.
const current = headings.find((h) => visible.has(h.slug));
if (current) setActive(current.slug);
},
// Active zone = the top ~30% of the reading pane.
{ root, rootMargin: "0px 0px -70% 0px", threshold: 0 },
);
const els = headings
.map((h) => root.querySelector(`[id="${h.slug}"]`))
.filter((el): el is Element => el !== null);
els.forEach((el) => observer.observe(el));
return () => observer.disconnect();
}, [headings, scrollRef]);
const onSelect = (slug: string) => {
scrollRef.current
?.querySelector(`[id="${slug}"]`)
?.scrollIntoView({ block: "start", behavior: "smooth" });
setActive(slug);
};
return (
<nav className="portal-docs__toc" aria-label={t("portal.docs.toc.title")}>
<div className="portal-docs__toc-title">{t("portal.docs.toc.title")}</div>
<ul className="portal-docs__toc-list">
{headings.map((h) => (
<li key={h.slug}>
<a
href={`#${h.slug}`}
className={
"portal-docs__toc-link" +
(h.level === 3 ? " is-sub" : "") +
(active === h.slug ? " is-active" : "")
}
aria-current={active === h.slug ? "location" : undefined}
onClick={(e) => {
e.preventDefault();
onSelect(h.slug);
}}
>
{h.text}
</a>
</li>
))}
</ul>
</nav>
);
}
@@ -0,0 +1,131 @@
import { isValidElement, useState, type ReactNode } from "react";
import ReactMarkdown, {
defaultUrlTransform,
type Components,
} from "react-markdown";
import remarkGfm from "remark-gfm";
import { Button } from "@app/ui";
import { makeSlugger } from "@portal/docs/headings";
/** Flatten a heading's React children to plain text for its anchor id. */
function childText(node: ReactNode): string {
if (typeof node === "string" || typeof node === "number") return String(node);
if (Array.isArray(node)) return node.map(childText).join("");
if (isValidElement(node)) {
return childText((node.props as { children?: ReactNode }).children);
}
return "";
}
// Keep our internal `doc:` scheme; sanitize every other URL as react-markdown
// would by default (it strips unknown protocols, which would kill doc: links).
function urlTransform(url: string): string {
return url.startsWith("doc:") ? url : defaultUrlTransform(url);
}
/**
* Renders a doc's normalised markdown. Internal cross-doc links carry the
* `doc:` scheme (see the sync transform) and are intercepted here so they
* navigate within the portal instead of leaving the app.
*/
function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
return (
<Button
variant="tertiary"
size="sm"
className="portal-docs__md-copy"
onClick={() =>
void navigator.clipboard.writeText(text).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
})
}
>
{copied ? "✓ Copied" : "Copy"}
</Button>
);
}
function buildComponents(
onNavigate: (docId: string) => void,
slug: (text: string) => string,
): Components {
return {
h2: ({ children }) => <h2 id={slug(childText(children))}>{children}</h2>,
h3: ({ children }) => <h3 id={slug(childText(children))}>{children}</h3>,
a: ({ href, children }) => {
if (href?.startsWith("doc:")) {
const id = href.slice(4);
return (
<a
href={`#${id}`}
onClick={(e) => {
e.preventDefault();
onNavigate(id);
}}
>
{children}
</a>
);
}
const external = /^https?:/i.test(href ?? "");
return (
<a
href={href}
target={external ? "_blank" : undefined}
rel={external ? "noopener noreferrer" : undefined}
>
{children}
</a>
);
},
// Eager, not lazy: lazy-loading inside the docs' own scroll container isn't
// reliably triggered, and docs pages have only a handful of images.
img: ({ node: _node, ...props }) => (
<img {...props} className="portal-docs__md-img" />
),
pre: ({ children }) => {
const code = isValidElement(children)
? String(
(children.props as { children?: unknown }).children ?? "",
).replace(/\n$/, "")
: String(children ?? "");
return (
<div className="portal-docs__md-pre">
<pre>{children}</pre>
<CopyButton text={code} />
</div>
);
},
table: ({ children }) => (
<div className="portal-docs__md-tablewrap">
<table>{children}</table>
</div>
),
};
}
export function MarkdownDoc({
markdown,
onNavigate,
}: {
markdown: string;
onNavigate: (docId: string) => void;
}) {
// A fresh de-duping slugger per render; react-markdown invokes h2/h3 in
// document order, so ids line up with the TOC's extractHeadings slugs.
const slug = makeSlugger();
return (
<div className="portal-docs__md">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
urlTransform={urlTransform}
components={buildComponents(onNavigate, slug)}
>
{markdown}
</ReactMarkdown>
</div>
);
}
@@ -157,7 +157,7 @@ export function ReviewQueue({ documents, loading }: ReviewQueueProps) {
<Button
variant="secondary"
onClick={() =>
navigate(`${toPortalPath(VIEW_PATHS.sources)}/new`)
navigate(`${toPortalPath(VIEW_PATHS.sources)}?new`)
}
>
{t("portal.documents.queue.empty.connectSource")}
@@ -1,8 +1,21 @@
import { useTranslation } from "react-i18next";
import CloudQueueRounded from "@mui/icons-material/CloudQueueRounded";
import HubRounded from "@mui/icons-material/HubRounded";
import Inventory2Rounded from "@mui/icons-material/Inventory2Rounded";
import { Button, Card, CodeBlock, StatusBadge } from "@app/ui";
import { TARGET_META, type DeploymentTarget } from "@portal/api/editorDeploy";
import {
TARGET_META,
type DeploymentTarget,
type TargetKind,
} from "@portal/api/editorDeploy";
import { useTier } from "@portal/contexts/TierContext";
const TARGET_ICON: Record<TargetKind, typeof CloudQueueRounded> = {
cloud: CloudQueueRounded,
docker: Inventory2Rounded,
kubernetes: HubRounded,
};
const STATE_BADGE_TONE: Record<
DeploymentTarget["state"],
"success" | "info" | "neutral"
@@ -36,6 +49,7 @@ export function DeploymentTargets({ targets, onUpgrade }: Props) {
<div className="portal-editor__targets">
{targets.map((target) => {
const meta = TARGET_META[target.kind];
const Icon = TARGET_ICON[target.kind];
const locked = target.state === "locked";
return (
<Card
@@ -48,7 +62,7 @@ export function DeploymentTargets({ targets, onUpgrade }: Props) {
className={`portal-editor__target-icon portal-editor__target-icon--${meta.tone}`}
aria-hidden
>
{meta.icon}
<Icon style={{ fontSize: "1.2rem" }} />
</span>
<div className="portal-editor__target-titles">
<h3 className="portal-editor__target-name">{target.label}</h3>
@@ -1,12 +1,21 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import CastRounded from "@mui/icons-material/CastRounded";
import TerminalRounded from "@mui/icons-material/TerminalRounded";
import VpnKeyRounded from "@mui/icons-material/VpnKeyRounded";
import { Button, Card, Chip, CodeBlock } from "@app/ui";
import type { PairingMethod, PairingOption } from "@portal/api/editorDeploy";
const METHOD_ICON: Record<PairingMethod, string> = {
token: "🔑",
shortcode: "📺",
iac: "🧱",
const METHOD_ICON: Record<PairingMethod, typeof VpnKeyRounded> = {
token: VpnKeyRounded,
shortcode: CastRounded,
iac: TerminalRounded,
};
const METHOD_TONE: Record<PairingMethod, "blue" | "purple" | "green"> = {
token: "blue",
shortcode: "purple",
iac: "green",
};
interface Props {
@@ -36,6 +45,7 @@ export function PairingPanel({ pairings, onUpgrade }: Props) {
<div className="portal-editor__pairings">
{pairings.map((p) => {
const isCode = p.method === "iac";
const Icon = METHOD_ICON[p.method];
return (
<Card
key={p.method}
@@ -43,8 +53,11 @@ export function PairingPanel({ pairings, onUpgrade }: Props) {
className="portal-editor__pairing"
>
<div className="portal-editor__pairing-head">
<span className="portal-editor__pairing-icon" aria-hidden>
{METHOD_ICON[p.method]}
<span
className={`portal-editor__pairing-icon portal-editor__pairing-icon--${METHOD_TONE[p.method]}`}
aria-hidden
>
<Icon style={{ fontSize: "1.2rem" }} />
</span>
<div className="portal-editor__pairing-titles">
<h3 className="portal-editor__pairing-name">{p.label}</h3>
@@ -221,17 +221,6 @@ export function PoliciesIcon(props: IconProps) {
);
}
export function ComponentsIcon(props: IconProps) {
return (
<Svg {...props}>
<rect x="3" y="3" width="7" height="7" rx="1" />
<rect x="14" y="3" width="7" height="7" rx="1" />
<rect x="3" y="14" width="7" height="7" rx="1" />
<rect x="14" y="14" width="7" height="7" rx="1" />
</Svg>
);
}
export function AgentBuilderIcon(props: IconProps) {
return (
<Svg {...props}>
@@ -23,7 +23,7 @@ export function ApiKeyCard({ apiKey }: { apiKey: ApiKey }) {
rightSection={
<span className="portal-infra__key-head-right">
<StatusBadge tone={KEY_TONE[apiKey.status]} size="sm">
{t(KEY_LABEL[apiKey.status])}
{KEY_LABEL[apiKey.status]}
</StatusBadge>
<span
className={"portal-infra__chevron" + (open ? " is-open" : "")}
@@ -1,5 +1,8 @@
import { useState } from "react";
import { useState, type ComponentType, type CSSProperties } from "react";
import { useTranslation } from "react-i18next";
import ArrowForwardRounded from "@mui/icons-material/ArrowForwardRounded";
import CloudRounded from "@mui/icons-material/CloudRounded";
import StorageRounded from "@mui/icons-material/StorageRounded";
import {
Button,
Card,
@@ -20,13 +23,13 @@ import {
import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";
import { pct } from "@portal/components/infrastructure/infraFormat";
const PROVIDER_GLYPH: Record<
const PROVIDER_ICON: Record<
StorageConfig["providers"][number]["kind"],
string
ComponentType<{ style?: CSSProperties }>
> = {
stirling: "◆",
s3: "▣",
azure: "▤",
stirling: StorageRounded,
s3: CloudRounded,
azure: CloudRounded,
};
/** Storage fills past this fraction of quota are surfaced in red. */
@@ -143,35 +146,38 @@ export function StorageTab() {
sub={t("portal.infrastructure.storage.providers.subheading")}
/>
<ul className="portal-infra__providers">
{data.providers.map((p) => (
<li key={p.id} className="portal-infra__provider">
<span className="portal-infra__provider-glyph" aria-hidden>
{PROVIDER_GLYPH[p.kind]}
</span>
<span className="portal-infra__provider-text">
<span className="portal-infra__cell-strong">{p.name}</span>
<span className="portal-infra__muted">{p.detail}</span>
</span>
{p.connected ? (
<span className="portal-infra__provider-meta">
<span className="portal-infra__mono">
{t("portal.infrastructure.storage.gbValue", {
value: p.usedGb,
})}
</span>
<StatusBadge tone="success" size="sm">
{t("portal.infrastructure.storage.providers.connected")}
</StatusBadge>
{data.providers.map((p) => {
const ProviderIcon = PROVIDER_ICON[p.kind];
return (
<li key={p.id} className="portal-infra__provider">
<span className="portal-infra__provider-glyph" aria-hidden>
<ProviderIcon style={{ fontSize: "1.2rem" }} />
</span>
) : (
// TODO(backend): launch the provider OAuth/credential flow,
// then POST /v1/infrastructure/storage/providers/{id}/connect
<Button variant="secondary" size="sm">
{t("portal.infrastructure.storage.providers.connect")}
</Button>
)}
</li>
))}
<span className="portal-infra__provider-text">
<span className="portal-infra__cell-strong">{p.name}</span>
<span className="portal-infra__muted">{p.detail}</span>
</span>
{p.connected ? (
<span className="portal-infra__provider-meta">
<span className="portal-infra__mono">
{t("portal.infrastructure.storage.gbValue", {
value: p.usedGb,
})}
</span>
<StatusBadge tone="success" size="sm">
{t("portal.infrastructure.storage.providers.connected")}
</StatusBadge>
</span>
) : (
// TODO(backend): launch the provider OAuth/credential flow,
// then POST /v1/infrastructure/storage/providers/{id}/connect
<Button variant="secondary" size="sm">
{t("portal.infrastructure.storage.providers.connect")}
</Button>
)}
</li>
);
})}
</ul>
</Card>
@@ -205,7 +211,7 @@ export function StorageTab() {
</span>
</div>
<span className="portal-infra__lifecycle-arrow" aria-hidden>
→
<ArrowForwardRounded style={{ fontSize: "1.2rem" }} />
</span>
<div className="portal-infra__lifecycle-stage">
<span className="portal-infra__lifecycle-dot" />
@@ -217,7 +223,7 @@ export function StorageTab() {
</span>
</div>
<span className="portal-infra__lifecycle-arrow" aria-hidden>
→
<ArrowForwardRounded style={{ fontSize: "1.2rem" }} />
</span>
<div className="portal-infra__lifecycle-stage">
<span className="portal-infra__lifecycle-dot" />
@@ -0,0 +1,140 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import {
Button,
Chip,
type ChipAccent,
StatusBadge,
Table,
type TableColumn,
} from "@app/ui";
import type { CatalogueEntry, PolicyCategory } from "@portal/api/policies";
import { PolicyCategoryBadge } from "@portal/components/policies/PolicyCategoryIcon";
import "@portal/views/Policies.css";
interface PolicyCatalogueTableProps {
entries: CatalogueEntry[];
onOpen: (entry: CatalogueEntry) => void;
}
/** Tint the "enforces" chips with the same hue as the category's icon badge. */
const TONE_ACCENT: Record<PolicyCategory["tone"], ChipAccent> = {
blue: "default",
purple: "premium",
green: "success",
amber: "warning",
red: "danger",
neutral: "neutral",
};
/**
* The policy catalogue as a proper data table (Policy / Enforces / Applies to /
* Docs / Status), replacing the stacked full-width cards that read as "blocky".
* Same shared Table + StatusBadge + Chip primitives the Sources, Documents and
* Home policy tables use, so every list page in the portal now reads alike.
*/
export function PolicyCatalogueTable({
entries,
onOpen,
}: PolicyCatalogueTableProps) {
const { t } = useTranslation();
const columns = useMemo<TableColumn<CatalogueEntry>[]>(
() => [
{
key: "policy",
header: t("portal.policies.table.policy", "Policy"),
render: (entry) => (
<div className="portal-policies__cell">
<PolicyCategoryBadge category={entry.category} />
<strong className="portal-policies__cell-name">
{t(entry.category.label)}
</strong>
</div>
),
},
{
key: "enforces",
header: t("portal.policies.table.enforces", "Enforces"),
render: (entry) => (
<div className="portal-policies__rulechips">
{entry.config.rules.map((r) => (
<Chip key={r} accent={TONE_ACCENT[entry.category.tone]} size="sm">
{t(r)}
</Chip>
))}
</div>
),
},
{
key: "scope",
header: t("portal.policies.table.appliesTo", "Applies to"),
render: (entry) => (
<span className="portal-policies__muted">
{t(entry.config.scopeLabel)}
</span>
),
},
{
key: "docs",
header: t("portal.policies.table.docs", "Docs enforced"),
align: "right",
width: "8rem",
render: (entry) => (
<span className="portal-policies__docs">
{entry.policy ? entry.policy.stats.enforced.toLocaleString() : "—"}
</span>
),
},
{
key: "status",
header: t("portal.policies.table.status", "Status"),
align: "right",
width: "8.5rem",
render: (entry) => {
if (entry.category.comingSoon) {
// One consistent neutral chip for every "Upgrade to Enterprise" —
// the same action should read the same on every row.
return (
<Chip accent="neutral" size="sm">
{t("portal.policies.card.comingSoon")}
</Chip>
);
}
if (entry.policy) {
const paused = entry.policy.state.status === "paused";
return (
<StatusBadge
tone={paused ? "warning" : "success"}
size="sm"
pulse={!paused}
>
{paused
? t("portal.policies.status.paused")
: t("portal.policies.status.active")}
</StatusBadge>
);
}
return (
<Button size="sm" variant="secondary" onClick={() => onOpen(entry)}>
{t("portal.policySummary.action.setUp")}
</Button>
);
},
},
],
[t, onOpen],
);
return (
<Table<CatalogueEntry>
className="portal-policies__table"
columns={columns}
rows={entries}
rowKey={(e) => e.category.id}
onRowClick={(entry) =>
entry.category.comingSoon ? undefined : onOpen(entry)
}
/>
);
}
@@ -0,0 +1,43 @@
/* Tinted rounded icon badge for a policy category — colour comes from the
category tone. Lives with the component so every consumer (the Policies table
and the Home policy summary) gets the styling without importing a view CSS. */
.pcat-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--radius-lg);
}
.pcat-badge svg {
width: 1.15rem;
height: 1.15rem;
display: block;
}
.pcat-badge--blue {
background: var(--color-blue-light);
color: var(--color-blue);
}
.pcat-badge--purple {
background: var(--color-purple-light);
color: var(--color-purple);
}
.pcat-badge--green {
background: var(--color-green-light);
color: var(--color-green-dark);
}
.pcat-badge--amber {
background: var(--color-amber-light);
color: var(--color-amber-dark);
}
.pcat-badge--red {
background: var(--color-red-light);
color: var(--color-red);
}
.pcat-badge--neutral {
background: var(--color-bg-muted);
color: var(--color-text-3);
}
@@ -0,0 +1,62 @@
import type { PolicyCategory } from "@portal/api/policies";
import "@portal/components/policies/PolicyCategoryIcon.css";
/**
* Stroke-SVG icons for the policy catalogue, keyed by the category's string icon
* key. Replaces the old Unicode glyph map (▤ 🛡 ✓ …) so category rows use the
* same line-icon system as the rest of the portal instead of box-drawing
* characters. Unknown keys fall back to a neutral document mark (never a bare
* bullet — that was the "schedule"/"clock" key mismatch's tell).
*/
const PATHS: Record<string, string> = {
layers: "M12 3l9 5-9 5-9-5 9-5zM3 13l9 5 9-5M3 17l9 5 9-5",
shield: "M12 3l7 3v5c0 4-3 7-7 9-4-2-7-5-7-9V6l7-3z",
check: "M20 7L10 17l-5-5",
route:
"M6 4a2 2 0 100 4 2 2 0 000-4zM18 16a2 2 0 100 4 2 2 0 000-4zM6 8v6a4 4 0 004 4h4",
clock: "M12 7v5l3 2M12 21a9 9 0 100-18 9 9 0 000 18z",
schedule: "M12 7v5l3 2M12 21a9 9 0 100-18 9 9 0 000 18z",
file: "M14 3H7a1 1 0 00-1 1v16a1 1 0 001 1h10a1 1 0 001-1V7l-4-4zM14 3v4h4",
device:
"M5 4h14a1 1 0 011 1v10a1 1 0 01-1 1H5a1 1 0 01-1-1V5a1 1 0 011-1zM9 20h6",
globe:
"M12 21a9 9 0 100-18 9 9 0 000 18zM3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18",
cloud: "M7 18a4 4 0 010-8 5 5 0 019.6-1.3A3.5 3.5 0 0117 18H7z",
mail: "M4 6h16a1 1 0 011 1v10a1 1 0 01-1 1H4a1 1 0 01-1-1V7a1 1 0 011-1zM4 7l8 6 8-6",
folder: "M3 7h6l2 2h10v9a1 1 0 01-1 1H4a1 1 0 01-1-1V7z",
};
const TONE_CLASS: Record<PolicyCategory["tone"], string> = {
blue: "pcat-badge--blue",
purple: "pcat-badge--purple",
green: "pcat-badge--green",
amber: "pcat-badge--amber",
red: "pcat-badge--red",
neutral: "pcat-badge--neutral",
};
/** A tinted rounded badge holding the category's stroke icon. */
export function PolicyCategoryBadge({
category,
}: {
category: PolicyCategory;
}) {
const d = PATHS[category.icon] ?? PATHS.file;
return (
<span
className={`pcat-badge ${TONE_CLASS[category.tone] ?? TONE_CLASS.neutral}`}
aria-hidden
>
<svg viewBox="0 0 24 24" fill="none">
<path
d={d}
stroke="currentColor"
strokeWidth="1.7"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</span>
);
}
@@ -27,8 +27,8 @@ import {
import { fetchSources } from "@portal/api/sources";
import { useAsync } from "@portal/hooks/useAsync";
import { PolicyFieldRow } from "@portal/components/policies/PolicyFieldRow";
import { policyIcon } from "@portal/components/policies/policyIcons";
import { sourceTypeMeta } from "@portal/components/sources/sourceTypes";
import { PolicyCategoryBadge } from "@portal/components/policies/PolicyCategoryIcon";
import { SourceTypeIcon } from "@portal/components/sources/SourceTypeIcon";
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";
import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";
@@ -310,9 +310,7 @@ function PolicySetupWizardBody({
width="lg"
title={
<span className="portal-policies__wizard-title">
<span className="portal-policies__cat-icon" aria-hidden>
{policyIcon(category.icon)}
</span>
<PolicyCategoryBadge category={category} />
{isEdit
? t("portal.policies.wizard.title.edit", {
category: t(category.label),
@@ -496,7 +494,7 @@ function PolicySetupWizardBody({
onClick={() => toggleSource(src.id)}
>
<span className="portal-policies__source-icon" aria-hidden>
{sourceTypeMeta(src.type).icon}
<SourceTypeIcon type={src.type} />
</span>
<span className="portal-policies__source-text">
<span className="portal-policies__source-label">
@@ -75,7 +75,7 @@ export function DocumentLedger({
className="portal-proc__stage-label"
data-current={cur || undefined}
>
{t(group.label)}
{group.label}
</span>
{blurb && (
<span className="portal-proc__stage-hint">
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import CloseRounded from "@mui/icons-material/CloseRounded";
import { Button } from "@app/ui";
import type { ProcurementSnapshot } from "@portal/api/procurement";
import { CalendlyInline } from "@portal/components/procurement/CalendlyInline";
@@ -60,7 +61,7 @@ function SideModal({
onClick={onClose}
aria-label={t("portal.procurement.modal.close")}
>
✕
<CloseRounded style={{ fontSize: "1.2rem" }} />
</button>
<div className="portal-sidemodal__header">
<h3 className="portal-sidemodal__title">{title}</h3>
@@ -1,6 +1,7 @@
import { useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import CloseRounded from "@mui/icons-material/CloseRounded";
import "@portal/views/Procurement.css";
/** Keep keyboard focus inside an open dialog: focus it on open and wrap Tab at the edges. */
@@ -90,7 +91,7 @@ export function ProcurementModal({
onClick={onClose}
aria-label={t("portal.procurement.modal.close")}
>
✕
<CloseRounded style={{ fontSize: "1.2rem" }} />
</button>
<div className="portal-procmodal__header">
<h2 className="portal-procmodal__title">{title}</h2>
@@ -1,5 +1,6 @@
import { useEffect, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import CheckRounded from "@mui/icons-material/CheckRounded";
import { Button } from "@app/ui";
import {
DocumentsIcon,
@@ -526,7 +527,7 @@ function AddOn({
onClick={onClick}
>
<span className="portal-qb__addon-box" aria-hidden>
{on ? "✓" : ""}
{on ? <CheckRounded style={{ fontSize: "0.85rem" }} /> : ""}
</span>
<span>
<span className="portal-qb__addon-title">{title}</span>
@@ -7,7 +7,6 @@ import {
PoliciesIcon,
PipelinesIcon,
DocumentsIcon,
ComponentsIcon,
InfrastructureIcon,
UsageIcon,
DocsIcon,
@@ -20,10 +19,6 @@ export interface NavEntry {
externalUrl?: string;
}
// Developer docs has no built-in portal page yet, so the tab opens the hosted docs
// site in a new tab rather than routing to an empty page.
const DEVELOPER_DOCS_URL = "https://docs.stirlingpdf.com/";
// Sidebar nav groups. This is a flavor seam: the SaaS build shadows this file to
// drop sections not yet shipped there (see src/portal-saas/components/sidebarGroups).
export const GROUP_PRIMARY: NavEntry[] = [{ id: "home", icon: <HomeIcon /> }];
@@ -34,11 +29,10 @@ export const GROUP_OPERATIONAL: NavEntry[] = [
{ id: "policies", icon: <PoliciesIcon /> },
{ id: "pipelines", icon: <PipelinesIcon /> },
{ id: "documents", icon: <DocumentsIcon /> },
{ id: "components", icon: <ComponentsIcon /> },
];
export const GROUP_PLATFORM: NavEntry[] = [
{ id: "infrastructure", icon: <InfrastructureIcon /> },
{ id: "usage", icon: <UsageIcon /> },
{ id: "docs", icon: <DocsIcon />, externalUrl: DEVELOPER_DOCS_URL },
{ id: "docs", icon: <DocsIcon /> },
];
@@ -0,0 +1,16 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { ConnectWizard } from "@portal/components/sources/ConnectWizard";
const meta: Meta<typeof ConnectWizard> = {
title: "Portal/Sources/ConnectWizard",
component: ConnectWizard,
parameters: { layout: "fullscreen" },
args: { open: true, onClose: () => {}, onCreated: () => {} },
};
export default meta;
type Story = StoryObj<typeof ConnectWizard>;
/** Opens on the type-picker step; Continue/Back walk through the three steps. */
export const Open: Story = {};
export const Closed: Story = { args: { open: false } };
@@ -0,0 +1,192 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MantineProvider } from "@mantine/core";
import { HttpError } from "@portal/api/http";
import { ConnectWizard } from "@portal/components/sources/ConnectWizard";
function renderWithMantine(ui: React.ReactElement) {
return render(<MantineProvider>{ui}</MantineProvider>);
}
// Deterministic i18n: keys come back verbatim so the test never waits on the
// async TOML backend.
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => key,
i18n: { changeLanguage: vi.fn() },
}),
}));
// Mock the service layer so no real fetch is issued.
const createSource = vi.fn();
vi.mock("@portal/api/sources", () => ({
createSource: (...args: unknown[]) => createSource(...args),
}));
/** Step through the folder-source flow: choose type -> configure -> review. */
function stepToReview() {
// Step 0: folder is the default-selected type. Continue.
fireEvent.click(screen.getByText("portal.sources.wizard.continue"));
// Step 1: fill the required name + directory fields.
const inputs = screen.getAllByRole("textbox");
// First textbox is the name field, second is the folder's directory field.
fireEvent.change(inputs[0], { target: { value: "Claims intake" } });
fireEvent.change(inputs[1], { target: { value: "/data/incoming" } });
fireEvent.click(screen.getByText("portal.sources.wizard.continue"));
}
describe("ConnectWizard", () => {
beforeEach(() => {
createSource.mockReset();
});
it("creates a folder source with the configured options", async () => {
createSource.mockResolvedValue({ id: "src-1" });
const onCreated = vi.fn();
const onClose = vi.fn();
renderWithMantine(
<ConnectWizard open onClose={onClose} onCreated={onCreated} />,
);
stepToReview();
// Step 2: submit via the final "connect source" action.
fireEvent.click(screen.getByText("portal.sources.actions.connectSource"));
await waitFor(() => {
expect(createSource).toHaveBeenCalledTimes(1);
});
expect(createSource).toHaveBeenCalledWith({
name: "Claims intake",
type: "folder",
options: {
directory: "/data/incoming",
mode: "consume",
recursive: "false",
identity: "stat",
},
enabled: true,
});
await waitFor(() => {
expect(onCreated).toHaveBeenCalledTimes(1);
});
});
it("creates an s3 source with a masked secret in review", async () => {
createSource.mockResolvedValue({ id: "src-2" });
renderWithMantine(
<ConnectWizard open onClose={vi.fn()} onCreated={vi.fn()} />,
);
// Step 0: pick the S3 type card.
fireEvent.click(screen.getByText("portal.sources.types.s3.label"));
fireEvent.click(screen.getByText("portal.sources.wizard.continue"));
// Step 1: name, bucket, credentials. The secret renders as a password
// input, so it is not part of the textbox roles.
const inputs = screen.getAllByRole("textbox") as HTMLInputElement[];
fireEvent.change(inputs[0], { target: { value: "Claims bucket" } });
fireEvent.change(inputs[1], { target: { value: "claims-inbox" } });
fireEvent.change(inputs[4], { target: { value: "AKIAEXAMPLE" } });
const secret = document.querySelector(
'input[type="password"]',
) as HTMLInputElement;
fireEvent.change(secret, { target: { value: "shh-secret" } });
fireEvent.click(screen.getByText("portal.sources.wizard.continue"));
// Step 2: the secret is masked in review, never echoed.
expect(screen.queryByText("shh-secret")).not.toBeInTheDocument();
expect(screen.getByText("********")).toBeInTheDocument();
fireEvent.click(screen.getByText("portal.sources.actions.connectSource"));
await waitFor(() => {
expect(createSource).toHaveBeenCalledTimes(1);
});
expect(createSource).toHaveBeenCalledWith({
name: "Claims bucket",
type: "s3",
options: {
bucket: "claims-inbox",
region: "us-east-1",
prefix: "",
accessKeyId: "AKIAEXAMPLE",
secretAccessKey: "shh-secret",
endpoint: "",
mode: "consume",
},
enabled: true,
});
});
it("edits an existing source: prefilled, skips type, submits with its id", async () => {
createSource.mockResolvedValue({ id: "s1" });
const onCreated = vi.fn();
renderWithMantine(
<ConnectWizard
open
source={{
id: "s1",
name: "James",
type: "folder",
options: { directory: "'/data/in'", mode: "consume" },
enabled: true,
}}
onClose={vi.fn()}
onCreated={onCreated}
/>,
);
// Edit opens on the configure step with name + directory prefilled.
const inputs = screen.getAllByRole("textbox") as HTMLInputElement[];
expect(inputs[0].value).toBe("James");
expect(inputs[1].value).toBe("'/data/in'");
// Fix the stray quotes, continue to review, save.
fireEvent.change(inputs[1], { target: { value: "/data/in" } });
fireEvent.click(screen.getByText("portal.sources.wizard.continue"));
fireEvent.click(screen.getByText("portal.sources.wizard.save"));
await waitFor(() => {
expect(createSource).toHaveBeenCalledTimes(1);
});
// Options absent from the stored source are submitted at their defaults.
expect(createSource).toHaveBeenCalledWith({
id: "s1",
name: "James",
type: "folder",
options: {
directory: "/data/in",
mode: "consume",
recursive: "false",
identity: "stat",
},
enabled: true,
});
await waitFor(() => {
expect(onCreated).toHaveBeenCalledTimes(1);
});
});
it("renders the inline error message when create fails", async () => {
createSource.mockRejectedValue(
new HttpError(400, "Bad Request", {
detail: "Directory is not readable",
}),
);
renderWithMantine(
<ConnectWizard open onClose={vi.fn()} onCreated={vi.fn()} />,
);
stepToReview();
fireEvent.click(screen.getByText("portal.sources.actions.connectSource"));
expect(
await screen.findByText("Directory is not readable"),
).toBeInTheDocument();
});
});
@@ -0,0 +1,303 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import CheckRounded from "@mui/icons-material/CheckRounded";
import {
Banner,
Button,
FormField,
Input,
Modal,
Select,
StatTile,
} from "@app/ui";
import { errorMessage } from "@portal/api/http";
import { createSource, type Source } from "@portal/api/sources";
import { creatableSourceTypes } from "@portal/components/sources/creatableSourceTypes";
import {
defaultOptions,
type CreatableSourceType,
} from "@portal/components/sources/sourceTypes";
import { SourceTypeIcon } from "@portal/components/sources/SourceTypeIcon";
import "@portal/views/Sources.css";
const OFFERED_TYPES = creatableSourceTypes();
const DEFAULT_TYPE = OFFERED_TYPES[0];
/** Wizard steps. Editing skips type selection (the type is fixed once created). */
type StepId = "type" | "configure" | "review";
const CREATE_STEPS: StepId[] = ["type", "configure", "review"];
const EDIT_STEPS: StepId[] = ["configure", "review"];
interface ConnectWizardProps {
open: boolean;
onClose: () => void;
/** Called after a source is created or updated so the page can refetch. */
onCreated: () => void;
/** When set, the wizard edits this existing source instead of creating one. */
source?: Source;
}
/** The creatable-type metadata for a source's stored type, falling back to the first offered. */
function typeFor(type: string | undefined): CreatableSourceType {
return OFFERED_TYPES.find((t) => t.type === type) ?? DEFAULT_TYPE;
}
/** Source options coerced to strings for the form, defaulted from the type's fields. */
function optionsFor(
type: CreatableSourceType,
options: Record<string, unknown> | undefined,
): Record<string, string> {
const out = defaultOptions(type);
for (const [key, value] of Object.entries(options ?? {})) {
out[key] = value == null ? "" : String(value);
}
return out;
}
/**
* Guided flow for connecting a source (choose type -> configure -> review) or
* editing an existing one (configure -> review, type fixed). On submit a blank
* id creates and a set id updates, matching the backend's POST contract.
*/
export function ConnectWizard({
open,
onClose,
onCreated,
source,
}: ConnectWizardProps) {
const { t } = useTranslation();
const isEdit = source !== undefined;
const steps = isEdit ? EDIT_STEPS : CREATE_STEPS;
const [stepIndex, setStepIndex] = useState(0);
const [type, setType] = useState<CreatableSourceType>(() =>
typeFor(source?.type),
);
const [name, setName] = useState(source?.name ?? "");
const [options, setOptions] = useState<Record<string, string>>(() =>
optionsFor(typeFor(source?.type), source?.options),
);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Re-seed the form whenever the wizard opens (or its target source changes) so
// editing prefills the current config and a reopened create starts clean.
useEffect(() => {
if (!open) return;
const ct = typeFor(source?.type);
setStepIndex(0);
setType(ct);
setName(source?.name ?? "");
setOptions(optionsFor(ct, source?.options));
setSubmitting(false);
setError(null);
}, [open, source]);
const stepId = steps[stepIndex];
const isLast = stepIndex === steps.length - 1;
function chooseType(next: CreatableSourceType) {
setType(next);
setOptions(defaultOptions(next));
}
const requiredFilled = type.fields.every(
(f) => !f.required || (options[f.key] ?? "").trim() !== "",
);
const canContinue =
stepId === "configure" ? name.trim() !== "" && requiredFilled : true;
async function advance() {
if (!isLast) {
setStepIndex((i) => i + 1);
return;
}
setSubmitting(true);
setError(null);
try {
const fields = {
name: name.trim(),
type: type.type,
options,
enabled: source?.enabled ?? true,
};
await createSource(isEdit ? { ...fields, id: source.id } : fields);
onCreated();
onClose();
} catch (e) {
setError(errorMessage(e));
} finally {
setSubmitting(false);
}
}
const stepLabels: Record<StepId, string> = {
type: t("portal.sources.wizard.steps.chooseType"),
configure: t("portal.sources.wizard.steps.configure"),
review: t("portal.sources.wizard.steps.review"),
};
return (
<Modal
open={open}
onClose={onClose}
width="lg"
title={
isEdit
? t("portal.sources.wizard.editTitle")
: t("portal.sources.wizard.title")
}
subtitle={t("portal.sources.wizard.subtitle", {
current: stepIndex + 1,
total: steps.length,
label: stepLabels[stepId],
})}
footer={
<div className="portal-sources__wizard-footer">
<Button
variant="tertiary"
size="sm"
disabled={submitting}
onClick={() =>
stepIndex === 0 ? onClose() : setStepIndex((i) => i - 1)
}
>
{stepIndex === 0
? t("portal.sources.wizard.cancel")
: t("portal.sources.wizard.back")}
</Button>
<Button
size="sm"
onClick={advance}
loading={submitting}
disabled={!canContinue}
rightSection={!isLast ? <span aria-hidden>→</span> : undefined}
>
{!isLast
? t("portal.sources.wizard.continue")
: isEdit
? t("portal.sources.wizard.save")
: t("portal.sources.actions.connectSource")}
</Button>
</div>
}
>
<ol className="portal-sources__steps" aria-hidden>
{steps.map((id, i) => (
<li
key={id}
className={
"portal-sources__step" +
(i === stepIndex ? " is-active" : i < stepIndex ? " is-done" : "")
}
>
<span className="portal-sources__step-mark">
{i < stepIndex ? (
<CheckRounded style={{ fontSize: "0.9rem" }} />
) : (
i + 1
)}
</span>
{stepLabels[id]}
</li>
))}
</ol>
{stepId === "type" && (
<div className="portal-sources__type-grid">
{OFFERED_TYPES.map((ct) => (
<Button
key={ct.type}
variant="tertiary"
className={
"portal-sources__type-card" +
(type.type === ct.type ? " is-selected" : "")
}
onClick={() => chooseType(ct)}
>
<span className="portal-sources__type-icon" aria-hidden>
<SourceTypeIcon type={ct.type} />
</span>
<span className="portal-sources__type-name">
{t(ct.labelKey)}
</span>
</Button>
))}
</div>
)}
{stepId === "configure" && (
<div className="portal-sources__wizard-body">
<FormField label={t("portal.sources.wizard.name")} required>
<Input
value={name}
placeholder={t("portal.sources.wizard.namePlaceholder")}
onChange={(e) => setName(e.target.value)}
/>
</FormField>
{type.fields.map((field) => (
<FormField
key={field.key}
label={t(field.labelKey)}
helperText={
field.helperTextKey ? t(field.helperTextKey) : undefined
}
required={field.required}
>
{field.control === "select" ? (
<Select
value={options[field.key] ?? ""}
options={(field.options ?? []).map((o) => ({
value: o.value,
label: t(o.labelKey),
}))}
onChange={(value) =>
setOptions((o) => ({ ...o, [field.key]: value ?? "" }))
}
/>
) : (
<Input
type={field.control === "password" ? "password" : undefined}
value={options[field.key] ?? ""}
placeholder={
field.placeholderKey ? t(field.placeholderKey) : undefined
}
onChange={(e) =>
setOptions((o) => ({ ...o, [field.key]: e.target.value }))
}
/>
)}
</FormField>
))}
</div>
)}
{stepId === "review" && (
<div className="portal-sources__wizard-body">
<div className="portal-sources__stat-grid">
<StatTile
label={t("portal.sources.wizard.name")}
value={name || "—"}
/>
<StatTile
label={t("portal.sources.wizard.type")}
value={t(type.labelKey)}
/>
{type.fields.map((field) => (
<StatTile
key={field.key}
label={t(field.labelKey)}
value={
field.control === "password" && options[field.key]
? "********"
: options[field.key] || "—"
}
/>
))}
</div>
{error && <Banner tone="danger" description={error} />}
</div>
)}
</Modal>
);
}

Some files were not shown because too many files have changed in this diff Show More