Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
011ae4dd08 | ||
|
|
c4c06cfd7d |
@@ -95,7 +95,6 @@ tasks:
|
||||
vars:
|
||||
PORT: '{{.PORTAL_PORT}}'
|
||||
BACKEND_URL: 'http://localhost:{{.BACKEND_PORT}}'
|
||||
MOCKS: 'false'
|
||||
OPEN: "true"
|
||||
|
||||
dev:portal:all:
|
||||
@@ -118,32 +117,6 @@ tasks:
|
||||
BACKEND_URL: 'http://localhost:{{.BACKEND_PORT}}'
|
||||
# Point the portal's "Editor" app switcher at the editor we spawn here.
|
||||
EDITOR_URL: 'http://localhost:{{.EDITOR_PORT}}/'
|
||||
MOCKS: 'false'
|
||||
OPEN: "true"
|
||||
- task: frontend:dev
|
||||
vars:
|
||||
PORT: '{{.EDITOR_PORT}}'
|
||||
BACKEND_URL: 'http://localhost:{{.BACKEND_PORT}}'
|
||||
|
||||
dev:portal:all:saas:
|
||||
desc: "Start SaaS backend + developer portal + editor concurrently on free ports"
|
||||
vars:
|
||||
PORTS:
|
||||
sh: '{{if eq OS "windows"}}{{.FIND_FREE_PORT_PS}} 8080 5173 5174{{else}}{{.FIND_FREE_PORT_SH}} 8080 5173 5174{{end}}'
|
||||
BACKEND_PORT: '{{index (splitList "\n" .PORTS) 0}}'
|
||||
PORTAL_PORT: '{{index (splitList "\n" .PORTS) 1}}'
|
||||
EDITOR_PORT: '{{index (splitList "\n" .PORTS) 2}}'
|
||||
deps:
|
||||
- task: backend:dev:saas
|
||||
vars:
|
||||
PORT: '{{.BACKEND_PORT}}'
|
||||
POLICIES_ENABLED: "true"
|
||||
- task: frontend:dev:portal
|
||||
vars:
|
||||
PORT: '{{.PORTAL_PORT}}'
|
||||
BACKEND_URL: 'http://localhost:{{.BACKEND_PORT}}'
|
||||
EDITOR_URL: 'http://localhost:{{.EDITOR_PORT}}/'
|
||||
MOCKS: 'false'
|
||||
OPEN: "true"
|
||||
- task: frontend:dev
|
||||
vars:
|
||||
|
||||
+2
-14
@@ -3,12 +3,9 @@ package stirling.software.SPDF.controller.api;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.pdfbox.cos.COSDictionary;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.PDPageTree;
|
||||
@@ -264,19 +261,10 @@ public class RearrangePagesPDFController {
|
||||
log.info("newPageOrder = {}", newPageOrder);
|
||||
log.info("totalPages = {}", totalPages);
|
||||
|
||||
// Snapshot desired pages before mutating the tree; clone repeats (e.g. DUPLICATE)
|
||||
// so each slot is a distinct node, not one PDPage under multiple /Kids.
|
||||
// Snapshot the desired pages before mutating the source document's page tree.
|
||||
List<PDPage> newPages = new ArrayList<>(newPageOrder.size());
|
||||
Set<Integer> seenIndices = new HashSet<>();
|
||||
for (Integer idx : newPageOrder) {
|
||||
PDPage page = document.getPage(idx);
|
||||
if (!seenIndices.add(idx)) {
|
||||
// Duplicate index: distinct page node sharing content/resources.
|
||||
COSDictionary clonedDict = new COSDictionary();
|
||||
clonedDict.addAll(page.getCOSObject());
|
||||
page = new PDPage(clonedDict);
|
||||
}
|
||||
newPages.add(page);
|
||||
newPages.add(document.getPage(idx));
|
||||
}
|
||||
|
||||
// Rearrange in-place on the source document rather than copying pages into a
|
||||
|
||||
-31
@@ -9,7 +9,6 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.pdfbox.Loader;
|
||||
@@ -303,11 +302,6 @@ class RearrangePagesPDFControllerTest {
|
||||
assertNotNull(response);
|
||||
// 2 pages * 3 duplicates = 6 final pages
|
||||
assertEquals(6, realDoc.getNumberOfPages());
|
||||
// Each duplicate must be a distinct page node in the saved output; a shared
|
||||
// node under multiple /Kids is an invalid tree readers reject as cyclic.
|
||||
List<Object> savedPages = reloadAndSnapshot(response);
|
||||
assertEquals(6, savedPages.size());
|
||||
assertEquals(6, new HashSet<>(savedPages).size());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,29 +323,4 @@ class RearrangePagesPDFControllerTest {
|
||||
assertEquals(4, realDoc.getNumberOfPages());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRearrangePages_SideStitchBooklet_RepeatedPaddingPagesAreDistinctNodes()
|
||||
throws IOException {
|
||||
MockMultipartFile file = createMockPdf();
|
||||
RearrangePagesRequest request = new RearrangePagesRequest();
|
||||
request.setFileInput(file);
|
||||
request.setPageNumbers("");
|
||||
request.setCustomMode("SIDE_STITCH_BOOKLET_SORT");
|
||||
|
||||
// 6 pages is not a multiple of 4, so booklet padding repeats the last page index
|
||||
// several times; each repeat must be a distinct page node, not one shared node.
|
||||
try (PDDocument realDoc = buildRealPdf(6)) {
|
||||
when(pdfDocumentFactory.load(file)).thenReturn(realDoc);
|
||||
|
||||
ResponseEntity<Resource> response = controller.rearrangePages(request);
|
||||
|
||||
assertNotNull(response);
|
||||
assertEquals(200, response.getStatusCode().value());
|
||||
assertEquals(8, realDoc.getNumberOfPages());
|
||||
List<Object> savedPages = reloadAndSnapshot(response);
|
||||
assertEquals(8, savedPages.size());
|
||||
assertEquals(8, new HashSet<>(savedPages).size());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package stirling.software.proprietary.access.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import stirling.software.proprietary.access.service.DefaultTeamLeadLookup;
|
||||
import stirling.software.proprietary.access.service.TeamLeadLookup;
|
||||
|
||||
/** Access-layer bean wiring. */
|
||||
@Configuration
|
||||
public class AccessConfig {
|
||||
|
||||
/** No-op {@link TeamLeadLookup} unless another bean is defined. */
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(TeamLeadLookup.class)
|
||||
TeamLeadLookup defaultTeamLeadLookup() {
|
||||
return new DefaultTeamLeadLookup();
|
||||
}
|
||||
}
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
package stirling.software.proprietary.access.controller;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.access.model.AccessPermission;
|
||||
import stirling.software.proprietary.access.model.PrincipalType;
|
||||
import stirling.software.proprietary.access.model.ResourceGrant;
|
||||
import stirling.software.proprietary.access.model.ResourceType;
|
||||
import stirling.software.proprietary.access.service.ResourceAccessService;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
/** Admin endpoints to grant/revoke access to gated resources (the portal, integration configs). */
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/access")
|
||||
@RequiredArgsConstructor
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@Tag(name = "Access Control", description = "Manage resource access grants (portal, integrations)")
|
||||
public class ResourceGrantController {
|
||||
|
||||
private final ResourceAccessService accessService;
|
||||
|
||||
@GetMapping("/grants")
|
||||
public ResponseEntity<?> list(
|
||||
@RequestParam ResourceType resourceType,
|
||||
@RequestParam(required = false, defaultValue = "") String resourceId) {
|
||||
List<ResourceGrant> grants = accessService.listGrants(resourceType, resourceId);
|
||||
return ResponseEntity.ok(grants.stream().map(this::toDto).toList());
|
||||
}
|
||||
|
||||
@PostMapping("/grants")
|
||||
public ResponseEntity<?> create(
|
||||
@RequestBody GrantRequest request, @AuthenticationPrincipal User admin) {
|
||||
if (request.resourceType() == null
|
||||
|| request.principalType() == null
|
||||
|| request.principalId() == null) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"resourceType, principalType and principalId are required"));
|
||||
}
|
||||
AccessPermission permission =
|
||||
request.permission() == null ? AccessPermission.USE : request.permission();
|
||||
// PORTAL is a singleton resource; its grants always target the whole type.
|
||||
String resourceId =
|
||||
request.resourceType() == ResourceType.PORTAL ? "" : request.resourceId();
|
||||
ResourceGrant grant =
|
||||
accessService.grant(
|
||||
request.resourceType(),
|
||||
resourceId,
|
||||
request.principalType(),
|
||||
request.principalId(),
|
||||
permission,
|
||||
admin);
|
||||
return ResponseEntity.ok(toDto(grant));
|
||||
}
|
||||
|
||||
@DeleteMapping("/grants/{id}")
|
||||
public ResponseEntity<?> delete(@PathVariable Long id) {
|
||||
accessService.revoke(id);
|
||||
return ResponseEntity.ok(Map.of("message", "Grant revoked"));
|
||||
}
|
||||
|
||||
private Map<String, Object> toDto(ResourceGrant g) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", g.getId());
|
||||
m.put("resourceType", g.getResourceType());
|
||||
m.put("resourceId", g.getResourceId());
|
||||
m.put("principalType", g.getPrincipalType());
|
||||
m.put("principalId", g.getPrincipalId());
|
||||
m.put("permission", g.getPermission());
|
||||
m.put("createdAt", g.getCreatedAt());
|
||||
return m;
|
||||
}
|
||||
|
||||
/** Request body for creating a grant. */
|
||||
public record GrantRequest(
|
||||
ResourceType resourceType,
|
||||
String resourceId,
|
||||
PrincipalType principalType,
|
||||
Long principalId,
|
||||
AccessPermission permission) {}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package stirling.software.proprietary.access.model;
|
||||
|
||||
/** Permission level a grant confers. MANAGE implies USE. */
|
||||
public enum AccessPermission {
|
||||
USE,
|
||||
MANAGE
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package stirling.software.proprietary.access.model;
|
||||
|
||||
/**
|
||||
* Fallback policy applied when no explicit {@link ResourceGrant} matches. Admins (org owners)
|
||||
* always pass regardless of this policy.
|
||||
*/
|
||||
public enum DefaultAccessPolicy {
|
||||
// Every authenticated user in the deployment (org) may use the resource.
|
||||
ORG_ALL,
|
||||
// Only org admins and team leaders. This is the default for the portal.
|
||||
ADMINS_AND_TEAM_LEADS,
|
||||
// Nobody but the owner, admins, and explicit grantees.
|
||||
EXPLICIT_ONLY
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package stirling.software.proprietary.access.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
/** Base for a resource owned by a user, a team, or the server, with grant-based access. */
|
||||
@MappedSuperclass
|
||||
@Getter
|
||||
@Setter
|
||||
public abstract class OwnedResource {
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "scope", nullable = false, length = 32)
|
||||
private OwnerScope scope;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "owner_user_id")
|
||||
private User ownerUser;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "owner_team_id")
|
||||
private Team ownerTeam;
|
||||
|
||||
@Column(name = "enabled", nullable = false)
|
||||
private boolean enabled = true;
|
||||
|
||||
// Server resource that users cannot override with their own of the same kind.
|
||||
@Column(name = "locked", nullable = false)
|
||||
private boolean locked = false;
|
||||
|
||||
// Who, besides owner/admin/grantees, may use this resource.
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "default_access", nullable = false, length = 32)
|
||||
private DefaultAccessPolicy defaultAccess = DefaultAccessPolicy.EXPLICIT_ONLY;
|
||||
|
||||
/** Subclass primary key. */
|
||||
public abstract Long getId();
|
||||
|
||||
public Long getOwnerUserId() {
|
||||
return ownerUser != null ? ownerUser.getId() : null;
|
||||
}
|
||||
|
||||
public Long getOwnerTeamId() {
|
||||
return ownerTeam != null ? ownerTeam.getId() : null;
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package stirling.software.proprietary.access.model;
|
||||
|
||||
/** Ownership scope of an {@link OwnedResource}: a single user, a team, or the whole server. */
|
||||
public enum OwnerScope {
|
||||
USER,
|
||||
TEAM,
|
||||
SERVER
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package stirling.software.proprietary.access.model;
|
||||
|
||||
/** Who a {@link ResourceGrant} is granted to. Org-wide access is expressed via default policy. */
|
||||
public enum PrincipalType {
|
||||
USER,
|
||||
TEAM
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package stirling.software.proprietary.access.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Index;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.UniqueConstraint;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
/** Grants a user or team access to a resource. Owner and admin access are implicit. */
|
||||
@Entity
|
||||
@Table(
|
||||
name = "resource_grants",
|
||||
uniqueConstraints =
|
||||
@UniqueConstraint(
|
||||
name = "uk_resource_grant",
|
||||
columnNames = {
|
||||
"resource_type",
|
||||
"resource_id",
|
||||
"principal_type",
|
||||
"principal_id",
|
||||
"permission"
|
||||
}),
|
||||
indexes = {
|
||||
@Index(name = "idx_resource_grants_lookup", columnList = "resource_type,resource_id"),
|
||||
@Index(
|
||||
name = "idx_resource_grants_principal",
|
||||
columnList = "principal_type,principal_id")
|
||||
})
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class ResourceGrant implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "resource_grant_id")
|
||||
private Long id;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "resource_type", nullable = false, length = 64)
|
||||
private ResourceType resourceType;
|
||||
|
||||
// Empty string (never null) for a whole-type grant such as the portal.
|
||||
@Column(name = "resource_id", nullable = false, length = 255)
|
||||
private String resourceId = "";
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "principal_type", nullable = false, length = 32)
|
||||
private PrincipalType principalType;
|
||||
|
||||
@Column(name = "principal_id", nullable = false)
|
||||
private Long principalId;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "permission", nullable = false, length = 32)
|
||||
private AccessPermission permission;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "granted_by_user_id")
|
||||
private User grantedBy;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package stirling.software.proprietary.access.model;
|
||||
|
||||
/** Types of resources whose access can be gated by {@link ResourceGrant}. */
|
||||
public enum ResourceType {
|
||||
// The admin portal / processor (frontend/portal). Singleton resource (empty resourceId).
|
||||
PORTAL,
|
||||
// A stored S3/MCP/API integration configuration.
|
||||
INTEGRATION_CONFIG
|
||||
}
|
||||
-28
@@ -1,28 +0,0 @@
|
||||
package stirling.software.proprietary.access.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import stirling.software.proprietary.access.model.PrincipalType;
|
||||
import stirling.software.proprietary.access.model.ResourceGrant;
|
||||
import stirling.software.proprietary.access.model.ResourceType;
|
||||
|
||||
@Repository
|
||||
public interface ResourceGrantRepository extends JpaRepository<ResourceGrant, Long> {
|
||||
|
||||
List<ResourceGrant> findByResourceTypeAndResourceId(
|
||||
ResourceType resourceType, String resourceId);
|
||||
|
||||
List<ResourceGrant> findByResourceTypeAndPrincipalTypeAndPrincipalId(
|
||||
ResourceType resourceType, PrincipalType principalType, Long principalId);
|
||||
|
||||
void deleteByResourceTypeAndResourceId(ResourceType resourceType, String resourceId);
|
||||
|
||||
boolean existsByResourceTypeAndResourceIdAndPrincipalTypeAndPrincipalId(
|
||||
ResourceType resourceType,
|
||||
String resourceId,
|
||||
PrincipalType principalType,
|
||||
Long principalId);
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package stirling.software.proprietary.access.security;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.access.service.ResourceAccessService;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
|
||||
/** {@code @PreAuthorize} bean for portal-access checks. Active in self-hosted and saas. */
|
||||
@Component("resourceAccess")
|
||||
@RequiredArgsConstructor
|
||||
public class ResourceAccessSecurity {
|
||||
|
||||
private final ResourceAccessService accessService;
|
||||
private final UserService userService;
|
||||
|
||||
public boolean canUsePortal() {
|
||||
User user = currentUser();
|
||||
return user != null && accessService.canAccessPortal(user);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
/** No-op {@link TeamLeadLookup}: always false. */
|
||||
public class DefaultTeamLeadLookup implements TeamLeadLookup {
|
||||
|
||||
@Override
|
||||
public boolean isAnyTeamLeader(User user) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLeaderOfTeam(User user, Long teamId) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
-116
@@ -1,116 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.common.model.enumeration.Role;
|
||||
import stirling.software.proprietary.access.model.OwnedResource;
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.access.model.ResourceType;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.TeamRepository;
|
||||
|
||||
/** Ownership and access checks for {@link OwnedResource}, backed by the resource-grant ACL. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional(readOnly = true)
|
||||
public class OwnershipService {
|
||||
|
||||
private final ResourceAccessService accessService;
|
||||
private final TeamLeadLookup teamLeadLookup;
|
||||
private final TeamRepository teamRepository;
|
||||
|
||||
/** Whether the user may use the resource. */
|
||||
public boolean canUse(ResourceType type, OwnedResource resource, User user) {
|
||||
if (!resource.isEnabled()) {
|
||||
return isAdmin(user) || isOwner(resource, user);
|
||||
}
|
||||
return accessService.canUseResource(
|
||||
type,
|
||||
String.valueOf(resource.getId()),
|
||||
resource.getOwnerUserId(),
|
||||
resource.getDefaultAccess(),
|
||||
user);
|
||||
}
|
||||
|
||||
/** Whether the user may manage the resource. */
|
||||
public boolean canManage(ResourceType type, OwnedResource resource, User user) {
|
||||
return accessService.canManageResource(
|
||||
type, String.valueOf(resource.getId()), resource.getOwnerUserId(), user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorizes the scope and assigns ownership; {@code lockedOverrideBlocks} guards USER scope.
|
||||
*/
|
||||
public void assignOwnership(
|
||||
OwnedResource resource,
|
||||
OwnerScope scope,
|
||||
Long teamId,
|
||||
User user,
|
||||
BooleanSupplier lockedOverrideBlocks) {
|
||||
resource.setScope(scope);
|
||||
switch (scope) {
|
||||
case USER -> {
|
||||
if (lockedOverrideBlocks.getAsBoolean() && !isAdmin(user)) {
|
||||
throw forbidden(
|
||||
"This is locked to the server configuration by an administrator");
|
||||
}
|
||||
resource.setOwnerUser(user);
|
||||
}
|
||||
case SERVER -> {
|
||||
if (!isAdmin(user)) {
|
||||
throw forbidden("Only administrators can create server-owned resources");
|
||||
}
|
||||
}
|
||||
case TEAM -> {
|
||||
if (teamId == null) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST, "ownerTeamId is required");
|
||||
}
|
||||
Team team =
|
||||
teamRepository
|
||||
.findById(teamId)
|
||||
.orElseThrow(() -> notFound("Team not found"));
|
||||
if (!isAdmin(user) && !teamLeadLookup.isLeaderOfTeam(user, team.getId())) {
|
||||
throw forbidden("Only admins or team leaders can create team-owned resources");
|
||||
}
|
||||
resource.setOwnerTeam(team);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Resource ids of the given type the user or their team holds a grant on. */
|
||||
public Set<String> grantedResourceIds(ResourceType type, User user) {
|
||||
return accessService.grantedResourceIds(type, user);
|
||||
}
|
||||
|
||||
public boolean isAdmin(User user) {
|
||||
return user.getAuthorities().stream()
|
||||
.anyMatch(a -> Role.ADMIN.getRoleId().equals(a.getAuthority()));
|
||||
}
|
||||
|
||||
public boolean isOwner(OwnedResource resource, User user) {
|
||||
if (resource.getOwnerUserId() != null && resource.getOwnerUserId().equals(user.getId())) {
|
||||
return true;
|
||||
}
|
||||
// Team-owned: the lead of the owning team owns it.
|
||||
return resource.getOwnerTeamId() != null
|
||||
&& teamLeadLookup.isLeaderOfTeam(user, resource.getOwnerTeamId());
|
||||
}
|
||||
|
||||
private ResponseStatusException forbidden(String message) {
|
||||
return new ResponseStatusException(HttpStatus.FORBIDDEN, message);
|
||||
}
|
||||
|
||||
private ResponseStatusException notFound(String message) {
|
||||
return new ResponseStatusException(HttpStatus.NOT_FOUND, message);
|
||||
}
|
||||
}
|
||||
-188
@@ -1,188 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.enumeration.Role;
|
||||
import stirling.software.proprietary.access.model.AccessPermission;
|
||||
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
|
||||
import stirling.software.proprietary.access.model.PrincipalType;
|
||||
import stirling.software.proprietary.access.model.ResourceGrant;
|
||||
import stirling.software.proprietary.access.model.ResourceType;
|
||||
import stirling.software.proprietary.access.repository.ResourceGrantRepository;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
/** Resolves access to gated resources: owner, then admin, then grant, then default policy. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@Transactional(readOnly = true)
|
||||
public class ResourceAccessService {
|
||||
|
||||
private final ResourceGrantRepository grantRepository;
|
||||
private final TeamLeadLookup teamLeadLookup;
|
||||
|
||||
@Value("${security.portal.defaultAccess:ADMINS_AND_TEAM_LEADS}")
|
||||
private DefaultAccessPolicy portalDefaultPolicy;
|
||||
|
||||
// ---- public checks ----
|
||||
|
||||
/** Whether the user may use the portal / processor. */
|
||||
public boolean canAccessPortal(User user) {
|
||||
return canUseResource(ResourceType.PORTAL, "", null, portalDefaultPolicy, user);
|
||||
}
|
||||
|
||||
/** Whether the user may use a resource, falling back to its default policy. */
|
||||
public boolean canUseResource(
|
||||
ResourceType type,
|
||||
String resourceId,
|
||||
Long ownerUserId,
|
||||
DefaultAccessPolicy defaultPolicy,
|
||||
User user) {
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
if (isOwner(ownerUserId, user) || isAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
if (hasGrant(type, normalize(resourceId), user, AccessPermission.USE)) {
|
||||
return true;
|
||||
}
|
||||
return matchesDefault(defaultPolicy, user);
|
||||
}
|
||||
|
||||
/** Whether the user may manage (edit/delete/share) a resource. No default-policy fallback. */
|
||||
public boolean canManageResource(
|
||||
ResourceType type, String resourceId, Long ownerUserId, User user) {
|
||||
if (user == null) {
|
||||
return false;
|
||||
}
|
||||
if (isOwner(ownerUserId, user) || isAdmin(user)) {
|
||||
return true;
|
||||
}
|
||||
return hasGrant(type, normalize(resourceId), user, AccessPermission.MANAGE);
|
||||
}
|
||||
|
||||
// ---- grant management ----
|
||||
|
||||
@Transactional
|
||||
public ResourceGrant grant(
|
||||
ResourceType type,
|
||||
String resourceId,
|
||||
PrincipalType principalType,
|
||||
Long principalId,
|
||||
AccessPermission permission,
|
||||
User grantedBy) {
|
||||
String rid = normalize(resourceId);
|
||||
ResourceGrant grant =
|
||||
grantRepository.findByResourceTypeAndResourceId(type, rid).stream()
|
||||
.filter(
|
||||
g ->
|
||||
g.getPrincipalType() == principalType
|
||||
&& g.getPrincipalId().equals(principalId))
|
||||
.findFirst()
|
||||
.orElseGet(ResourceGrant::new);
|
||||
grant.setResourceType(type);
|
||||
grant.setResourceId(rid);
|
||||
grant.setPrincipalType(principalType);
|
||||
grant.setPrincipalId(principalId);
|
||||
grant.setPermission(permission);
|
||||
if (grantedBy != null) {
|
||||
grant.setGrantedBy(grantedBy);
|
||||
}
|
||||
return grantRepository.save(grant);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void revoke(Long grantId) {
|
||||
grantRepository.deleteById(grantId);
|
||||
}
|
||||
|
||||
public List<ResourceGrant> listGrants(ResourceType type, String resourceId) {
|
||||
return grantRepository.findByResourceTypeAndResourceId(type, normalize(resourceId));
|
||||
}
|
||||
|
||||
/** Resource ids of the given type that this user (or their team) holds any grant on. */
|
||||
public Set<String> grantedResourceIds(ResourceType type, User user) {
|
||||
if (user == null) {
|
||||
return Set.of();
|
||||
}
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (ResourceGrant g :
|
||||
grantRepository.findByResourceTypeAndPrincipalTypeAndPrincipalId(
|
||||
type, PrincipalType.USER, user.getId())) {
|
||||
ids.add(g.getResourceId());
|
||||
}
|
||||
if (user.getTeam() != null) {
|
||||
for (ResourceGrant g :
|
||||
grantRepository.findByResourceTypeAndPrincipalTypeAndPrincipalId(
|
||||
type, PrincipalType.TEAM, user.getTeam().getId())) {
|
||||
ids.add(g.getResourceId());
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
// ---- internals ----
|
||||
|
||||
private boolean hasGrant(
|
||||
ResourceType type, String resourceId, User user, AccessPermission required) {
|
||||
Long teamId = user.getTeam() != null ? user.getTeam().getId() : null;
|
||||
for (ResourceGrant g : grantRepository.findByResourceTypeAndResourceId(type, resourceId)) {
|
||||
if (!permissionSatisfies(g.getPermission(), required)) {
|
||||
continue;
|
||||
}
|
||||
if (g.getPrincipalType() == PrincipalType.USER
|
||||
&& g.getPrincipalId().equals(user.getId())) {
|
||||
return true;
|
||||
}
|
||||
if (g.getPrincipalType() == PrincipalType.TEAM
|
||||
&& teamId != null
|
||||
&& g.getPrincipalId().equals(teamId)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// MANAGE implies USE.
|
||||
private boolean permissionSatisfies(AccessPermission held, AccessPermission required) {
|
||||
if (required == AccessPermission.USE) {
|
||||
return held == AccessPermission.USE || held == AccessPermission.MANAGE;
|
||||
}
|
||||
return held == AccessPermission.MANAGE;
|
||||
}
|
||||
|
||||
private boolean matchesDefault(DefaultAccessPolicy policy, User user) {
|
||||
if (policy == null) {
|
||||
return false;
|
||||
}
|
||||
return switch (policy) {
|
||||
case ORG_ALL -> true;
|
||||
// Admins already pass above; only team leads here.
|
||||
case ADMINS_AND_TEAM_LEADS -> teamLeadLookup.isAnyTeamLeader(user);
|
||||
case EXPLICIT_ONLY -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean isOwner(Long ownerUserId, User user) {
|
||||
return ownerUserId != null && ownerUserId.equals(user.getId());
|
||||
}
|
||||
|
||||
private boolean isAdmin(User user) {
|
||||
return user.getAuthorities().stream()
|
||||
.anyMatch(a -> Role.ADMIN.getRoleId().equals(a.getAuthority()));
|
||||
}
|
||||
|
||||
private String normalize(String resourceId) {
|
||||
return resourceId == null ? "" : resourceId;
|
||||
}
|
||||
}
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Masks, merges and sanitizes secret values in a config map, recursing into nested maps/lists. */
|
||||
@Component
|
||||
public class SecretMasker {
|
||||
|
||||
public static final String MASK = "********";
|
||||
|
||||
// Cap recursion so a pathologically nested payload cannot overflow the stack.
|
||||
private static final int MAX_DEPTH = 32;
|
||||
|
||||
private static final Set<String> SENSITIVE_HINTS =
|
||||
Set.of(
|
||||
"secret",
|
||||
"password",
|
||||
"token",
|
||||
"apikey",
|
||||
"accesskey",
|
||||
"credential",
|
||||
"privatekey");
|
||||
|
||||
/** Replace sensitive values with the mask (recursively) for safe display. */
|
||||
public Map<String, Object> mask(Map<String, Object> config) {
|
||||
return mask(config, 0);
|
||||
}
|
||||
|
||||
/** Drop sensitive blank/masked values from an incoming create payload. */
|
||||
public Map<String, Object> sanitize(Map<String, Object> config) {
|
||||
return sanitize(config, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge an update over the stored map, keeping stored secrets where the incoming is redacted.
|
||||
*/
|
||||
public Map<String, Object> merge(Map<String, Object> stored, Map<String, Object> incoming) {
|
||||
return merge(stored, incoming, 0);
|
||||
}
|
||||
|
||||
private Map<String, Object> mask(Map<String, Object> config, int depth) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Object> e : config.entrySet()) {
|
||||
out.put(e.getKey(), maskValue(e.getKey(), e.getValue(), depth));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private Map<String, Object> sanitize(Map<String, Object> config, int depth) {
|
||||
if (config == null) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Object> e : config.entrySet()) {
|
||||
if (isSensitive(e.getKey()) && isRedacted(e.getValue(), depth)) {
|
||||
continue;
|
||||
}
|
||||
out.put(
|
||||
e.getKey(),
|
||||
e.getValue() instanceof Map<?, ?> m && depth < MAX_DEPTH
|
||||
? sanitize(castMap(m), depth + 1)
|
||||
: e.getValue());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private Map<String, Object> merge(
|
||||
Map<String, Object> stored, Map<String, Object> incoming, int depth) {
|
||||
Map<String, Object> out = new LinkedHashMap<>(stored);
|
||||
for (Map.Entry<String, Object> e : incoming.entrySet()) {
|
||||
String key = e.getKey();
|
||||
Object value = e.getValue();
|
||||
if (isSensitive(key)) {
|
||||
if (!isRedacted(value, depth)) {
|
||||
out.put(key, value); // a real new secret replaces the stored one
|
||||
}
|
||||
continue; // redacted (blank / mask) -> keep stored
|
||||
}
|
||||
if (depth < MAX_DEPTH
|
||||
&& out.get(key) instanceof Map<?, ?> s
|
||||
&& value instanceof Map<?, ?> i) {
|
||||
out.put(key, merge(castMap(s), castMap(i), depth + 1));
|
||||
} else {
|
||||
out.put(key, value);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// A sensitive key masks its whole value; recurse into non-sensitive containers.
|
||||
private Object maskValue(String key, Object value, int depth) {
|
||||
if (isSensitive(key)) {
|
||||
if (value == null || (value instanceof String s && s.isBlank())) {
|
||||
return value;
|
||||
}
|
||||
return MASK;
|
||||
}
|
||||
if (depth >= MAX_DEPTH) {
|
||||
// Too deep to descend; mask containers rather than risk leaking an unmasked secret.
|
||||
return value instanceof Map<?, ?> || value instanceof List<?> ? MASK : value;
|
||||
}
|
||||
if (value instanceof Map<?, ?> m) {
|
||||
return mask(castMap(m), depth + 1);
|
||||
}
|
||||
if (value instanceof List<?> list) {
|
||||
List<Object> out = new ArrayList<>();
|
||||
for (Object item : list) {
|
||||
out.add(item instanceof Map<?, ?> m ? mask(castMap(m), depth + 1) : item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private boolean isSensitive(String key) {
|
||||
String lower = key.toLowerCase(Locale.ROOT);
|
||||
return SENSITIVE_HINTS.stream().anyMatch(lower::contains);
|
||||
}
|
||||
|
||||
/** Blank, the mask placeholder, or any structure that still contains the mask. */
|
||||
private boolean isRedacted(Object value, int depth) {
|
||||
if (value == null) {
|
||||
return true;
|
||||
}
|
||||
if (value instanceof String s) {
|
||||
return s.isBlank() || MASK.equals(s);
|
||||
}
|
||||
if (depth >= MAX_DEPTH) {
|
||||
return false;
|
||||
}
|
||||
if (value instanceof Map<?, ?> m) {
|
||||
return m.values().stream().anyMatch(v -> isRedacted(v, depth + 1));
|
||||
}
|
||||
if (value instanceof List<?> list) {
|
||||
return list.stream().anyMatch(v -> isRedacted(v, depth + 1));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> castMap(Map<?, ?> map) {
|
||||
return (Map<String, Object>) map;
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
/** Resolves whether a user leads a team. */
|
||||
public interface TeamLeadLookup {
|
||||
|
||||
/** Whether the user leads at least one team. */
|
||||
boolean isAnyTeamLeader(User user);
|
||||
|
||||
/** Whether the user leads the given team. */
|
||||
boolean isLeaderOfTeam(User user, Long teamId);
|
||||
}
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
package stirling.software.proprietary.integration.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.proprietary.integration.dto.IntegrationConfigRequest;
|
||||
import stirling.software.proprietary.integration.dto.IntegrationConfigResponse;
|
||||
import stirling.software.proprietary.integration.service.IntegrationConfigService;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
/** CRUD for S3/MCP/API integration configs. Secrets are never returned. */
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/integrations")
|
||||
@RequiredArgsConstructor
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@Tag(name = "Integrations", description = "Manage S3/MCP/API integration configurations")
|
||||
public class IntegrationConfigController {
|
||||
|
||||
private final IntegrationConfigService service;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<IntegrationConfigResponse>> list(
|
||||
@AuthenticationPrincipal User user) {
|
||||
requireUser(user);
|
||||
return ResponseEntity.ok(
|
||||
service.listVisible(user).stream().map(c -> service.toResponse(c, user)).toList());
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<IntegrationConfigResponse> create(
|
||||
@RequestBody IntegrationConfigRequest request, @AuthenticationPrincipal User user) {
|
||||
requireUser(user);
|
||||
return ResponseEntity.ok(service.toResponse(service.create(request, user), user));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<IntegrationConfigResponse> get(
|
||||
@PathVariable Long id, @AuthenticationPrincipal User user) {
|
||||
requireUser(user);
|
||||
return ResponseEntity.ok(service.toResponse(service.getForUse(id, user), user));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ResponseEntity<IntegrationConfigResponse> update(
|
||||
@PathVariable Long id,
|
||||
@RequestBody IntegrationConfigRequest request,
|
||||
@AuthenticationPrincipal User user) {
|
||||
requireUser(user);
|
||||
return ResponseEntity.ok(service.toResponse(service.update(id, request, user), user));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> delete(@PathVariable Long id, @AuthenticationPrincipal User user) {
|
||||
requireUser(user);
|
||||
service.delete(id, user);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private void requireUser(User user) {
|
||||
if (user == null) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authentication required");
|
||||
}
|
||||
}
|
||||
}
|
||||
-135
@@ -1,135 +0,0 @@
|
||||
package stirling.software.proprietary.integration.crypto;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.configuration.InstallationPathConfig;
|
||||
|
||||
/**
|
||||
* AES-256-GCM for stored credentials. Key from property, env var, or an auto-generated key file.
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class CredentialEncryption {
|
||||
|
||||
private static final String ALGORITHM = "AES";
|
||||
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
|
||||
private static final int GCM_TAG_BITS = 128;
|
||||
private static final int IV_BYTES = 12;
|
||||
private static final String KEY_FILE = "credential-encryption.key";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private static volatile SecretKey key;
|
||||
|
||||
private final String configuredKey;
|
||||
|
||||
public CredentialEncryption(
|
||||
@Value("${stirling.security.credentialEncryptionKey:}") String configuredKey) {
|
||||
this.configuredKey = configuredKey;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void init() {
|
||||
key = resolveKey();
|
||||
log.info("Credential encryption initialised (AES-256-GCM)");
|
||||
}
|
||||
|
||||
private SecretKey resolveKey() {
|
||||
String configured = configuredKey;
|
||||
if (configured == null || configured.isBlank()) {
|
||||
configured = System.getenv("STIRLING_CREDENTIAL_ENCRYPTION_KEY");
|
||||
}
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
return new SecretKeySpec(Base64.getDecoder().decode(configured.trim()), ALGORITHM);
|
||||
}
|
||||
return loadOrCreateKeyFile();
|
||||
}
|
||||
|
||||
private SecretKey loadOrCreateKeyFile() {
|
||||
Path path = Path.of(InstallationPathConfig.getConfigPath(), KEY_FILE);
|
||||
try {
|
||||
if (Files.exists(path)) {
|
||||
String encoded = Files.readString(path).trim();
|
||||
return new SecretKeySpec(Base64.getDecoder().decode(encoded), ALGORITHM);
|
||||
}
|
||||
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
|
||||
generator.init(256);
|
||||
SecretKey generated = generator.generateKey();
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, Base64.getEncoder().encodeToString(generated.getEncoded()));
|
||||
log.warn(
|
||||
"Generated a new credential encryption key at {}. Back this file up: losing it"
|
||||
+ " makes stored integration secrets unrecoverable.",
|
||||
path);
|
||||
return generated;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Unable to initialise credential encryption key", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String encrypt(String plaintext) {
|
||||
if (plaintext == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] iv = new byte[IV_BYTES];
|
||||
RANDOM.nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, requireKey(), new GCMParameterSpec(GCM_TAG_BITS, iv));
|
||||
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] combined = new byte[iv.length + ciphertext.length];
|
||||
System.arraycopy(iv, 0, combined, 0, iv.length);
|
||||
System.arraycopy(ciphertext, 0, combined, iv.length, ciphertext.length);
|
||||
return Base64.getEncoder().encodeToString(combined);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("Failed to encrypt credential", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String decrypt(String stored) {
|
||||
if (stored == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] combined = Base64.getDecoder().decode(stored);
|
||||
byte[] iv = Arrays.copyOfRange(combined, 0, IV_BYTES);
|
||||
byte[] ciphertext = Arrays.copyOfRange(combined, IV_BYTES, combined.length);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, requireKey(), new GCMParameterSpec(GCM_TAG_BITS, iv));
|
||||
return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("Failed to decrypt credential", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static SecretKey requireKey() {
|
||||
SecretKey current = key;
|
||||
if (current == null) {
|
||||
throw new IllegalStateException("Credential encryption not initialised");
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/** For tests. */
|
||||
static void initialiseForTesting(SecretKey testKey) {
|
||||
key = testKey;
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package stirling.software.proprietary.integration.crypto;
|
||||
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
/** Transparently encrypts/decrypts a string column at rest via {@link CredentialEncryption}. */
|
||||
@Converter
|
||||
public class EncryptedStringConverter implements AttributeConverter<String, String> {
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(String attribute) {
|
||||
return CredentialEncryption.encrypt(attribute);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertToEntityAttribute(String dbData) {
|
||||
return CredentialEncryption.decrypt(dbData);
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package stirling.software.proprietary.integration.dto;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
|
||||
/** Create/update payload for an integration config. Sensitive config values left blank are kept. */
|
||||
public record IntegrationConfigRequest(
|
||||
IntegrationType integrationType,
|
||||
String name,
|
||||
OwnerScope scope,
|
||||
Long ownerTeamId,
|
||||
Boolean enabled,
|
||||
Boolean locked,
|
||||
DefaultAccessPolicy defaultAccess,
|
||||
Map<String, Object> config) {}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package stirling.software.proprietary.integration.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.integration.model.IntegrationType;
|
||||
|
||||
/** Integration config view. Sensitive config values are masked. */
|
||||
public record IntegrationConfigResponse(
|
||||
Long id,
|
||||
IntegrationType integrationType,
|
||||
String name,
|
||||
OwnerScope scope,
|
||||
Long ownerUserId,
|
||||
Long ownerTeamId,
|
||||
boolean enabled,
|
||||
boolean locked,
|
||||
DefaultAccessPolicy defaultAccess,
|
||||
Map<String, Object> config,
|
||||
boolean canManage,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt) {}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
package stirling.software.proprietary.integration.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Convert;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Index;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import stirling.software.proprietary.access.model.OwnedResource;
|
||||
import stirling.software.proprietary.integration.crypto.EncryptedStringConverter;
|
||||
|
||||
/** A named S3/MCP/API integration config; scope and ownership live on {@link OwnedResource}. */
|
||||
@Entity
|
||||
@Table(
|
||||
name = "integration_configs",
|
||||
indexes = {
|
||||
@Index(name = "idx_integration_configs_owner", columnList = "owner_user_id"),
|
||||
@Index(name = "idx_integration_configs_type", columnList = "integration_type"),
|
||||
@Index(name = "idx_integration_configs_scope", columnList = "scope")
|
||||
})
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class IntegrationConfig extends OwnedResource implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "integration_config_id")
|
||||
private Long id;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "integration_type", nullable = false, length = 32)
|
||||
private IntegrationType integrationType;
|
||||
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
|
||||
// Type-specific fields as an AES-GCM encrypted JSON blob.
|
||||
@Convert(converter = EncryptedStringConverter.class)
|
||||
@Column(name = "config_encrypted", columnDefinition = "text")
|
||||
private String config;
|
||||
|
||||
@CreationTimestamp
|
||||
@Column(name = "created_at", updatable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@UpdateTimestamp
|
||||
@Column(name = "updated_at")
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package stirling.software.proprietary.integration.model;
|
||||
|
||||
/** Kind of external integration a stored config describes. */
|
||||
public enum IntegrationType {
|
||||
S3,
|
||||
MCP,
|
||||
API
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package stirling.software.proprietary.integration.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.integration.model.IntegrationConfig;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
@Repository
|
||||
public interface IntegrationConfigRepository extends JpaRepository<IntegrationConfig, Long> {
|
||||
|
||||
List<IntegrationConfig> findByOwnerUser(User ownerUser);
|
||||
|
||||
List<IntegrationConfig> findByOwnerTeam(Team ownerTeam);
|
||||
|
||||
List<IntegrationConfig> findByScope(OwnerScope scope);
|
||||
}
|
||||
-226
@@ -1,226 +0,0 @@
|
||||
package stirling.software.proprietary.integration.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
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.access.model.ResourceType;
|
||||
import stirling.software.proprietary.access.service.OwnershipService;
|
||||
import stirling.software.proprietary.access.service.SecretMasker;
|
||||
import stirling.software.proprietary.integration.dto.IntegrationConfigRequest;
|
||||
import stirling.software.proprietary.integration.dto.IntegrationConfigResponse;
|
||||
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 tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
/** CRUD for {@link IntegrationConfig}; delegates ownership and masking to shared services. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@Transactional(readOnly = true)
|
||||
public class IntegrationConfigService {
|
||||
|
||||
private static final ResourceType TYPE = ResourceType.INTEGRATION_CONFIG;
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
private final IntegrationConfigRepository repository;
|
||||
private final OwnershipService ownership;
|
||||
private final SecretMasker secretMasker;
|
||||
|
||||
// ---- commands ----
|
||||
|
||||
@Transactional
|
||||
public IntegrationConfig create(IntegrationConfigRequest request, User currentUser) {
|
||||
OwnerScope scope = request.scope() == null ? OwnerScope.USER : request.scope();
|
||||
IntegrationConfig cfg = new IntegrationConfig();
|
||||
cfg.setIntegrationType(require(request.integrationType(), "integrationType"));
|
||||
cfg.setName(require(request.name(), "name"));
|
||||
cfg.setEnabled(request.enabled() == null || request.enabled());
|
||||
cfg.setLocked(request.locked() != null && request.locked());
|
||||
cfg.setDefaultAccess(
|
||||
request.defaultAccess() == null
|
||||
? DefaultAccessPolicy.EXPLICIT_ONLY
|
||||
: request.defaultAccess());
|
||||
|
||||
ownership.assignOwnership(
|
||||
cfg,
|
||||
scope,
|
||||
request.ownerTeamId(),
|
||||
currentUser,
|
||||
() -> lockedServerExists(cfg.getIntegrationType()));
|
||||
cfg.setConfig(writeJson(secretMasker.sanitize(request.config())));
|
||||
return repository.save(cfg);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public IntegrationConfig update(Long id, IntegrationConfigRequest request, User currentUser) {
|
||||
IntegrationConfig cfg = load(id);
|
||||
if (!ownership.canManage(TYPE, cfg, currentUser)) {
|
||||
throw forbidden("You cannot manage this integration");
|
||||
}
|
||||
if (cfg.isLocked() && !ownership.isAdmin(currentUser)) {
|
||||
throw forbidden("This integration is locked by an administrator");
|
||||
}
|
||||
if (request.name() != null) {
|
||||
cfg.setName(request.name());
|
||||
}
|
||||
if (request.enabled() != null) {
|
||||
cfg.setEnabled(request.enabled());
|
||||
}
|
||||
if (request.locked() != null && request.locked() != cfg.isLocked()) {
|
||||
if (!ownership.isAdmin(currentUser)) {
|
||||
throw forbidden("Only administrators can change the locked flag");
|
||||
}
|
||||
cfg.setLocked(request.locked());
|
||||
}
|
||||
if (request.defaultAccess() != null) {
|
||||
cfg.setDefaultAccess(request.defaultAccess());
|
||||
}
|
||||
if (request.config() != null) {
|
||||
cfg.setConfig(
|
||||
writeJson(secretMasker.merge(readJson(cfg.getConfig()), request.config())));
|
||||
}
|
||||
return repository.save(cfg);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(Long id, User currentUser) {
|
||||
IntegrationConfig cfg = load(id);
|
||||
if (!ownership.canManage(TYPE, cfg, currentUser)) {
|
||||
throw forbidden("You cannot manage this integration");
|
||||
}
|
||||
repository.delete(cfg);
|
||||
}
|
||||
|
||||
// ---- queries ----
|
||||
|
||||
public IntegrationConfig getForUse(Long id, User currentUser) {
|
||||
IntegrationConfig cfg = load(id);
|
||||
if (!ownership.canUse(TYPE, cfg, currentUser)) {
|
||||
throw forbidden("You cannot access this integration");
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* All configs the user owns, plus server/team configs and grant-shared configs they may use.
|
||||
*/
|
||||
public List<IntegrationConfig> listVisible(User currentUser) {
|
||||
Map<Long, IntegrationConfig> byId = new LinkedHashMap<>();
|
||||
for (IntegrationConfig c : repository.findByOwnerUser(currentUser)) {
|
||||
byId.put(c.getId(), c);
|
||||
}
|
||||
for (IntegrationConfig c : repository.findByScope(OwnerScope.SERVER)) {
|
||||
if (ownership.canUse(TYPE, c, currentUser)) {
|
||||
byId.put(c.getId(), c);
|
||||
}
|
||||
}
|
||||
if (currentUser.getTeam() != null) {
|
||||
for (IntegrationConfig c : repository.findByOwnerTeam(currentUser.getTeam())) {
|
||||
if (ownership.canUse(TYPE, c, currentUser)) {
|
||||
byId.put(c.getId(), c);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (String rid : ownership.grantedResourceIds(TYPE, currentUser)) {
|
||||
if (rid == null || rid.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
Long cid;
|
||||
try {
|
||||
cid = Long.valueOf(rid);
|
||||
} catch (NumberFormatException e) {
|
||||
continue;
|
||||
}
|
||||
if (byId.containsKey(cid)) {
|
||||
continue;
|
||||
}
|
||||
repository
|
||||
.findById(cid)
|
||||
.filter(c -> ownership.canUse(TYPE, c, currentUser))
|
||||
.ifPresent(c -> byId.put(c.getId(), c));
|
||||
}
|
||||
return new ArrayList<>(byId.values());
|
||||
}
|
||||
|
||||
public IntegrationConfigResponse toResponse(IntegrationConfig cfg, User user) {
|
||||
return new IntegrationConfigResponse(
|
||||
cfg.getId(),
|
||||
cfg.getIntegrationType(),
|
||||
cfg.getName(),
|
||||
cfg.getScope(),
|
||||
cfg.getOwnerUserId(),
|
||||
cfg.getOwnerTeamId(),
|
||||
cfg.isEnabled(),
|
||||
cfg.isLocked(),
|
||||
cfg.getDefaultAccess(),
|
||||
secretMasker.mask(readJson(cfg.getConfig())),
|
||||
ownership.canManage(TYPE, cfg, user),
|
||||
cfg.getCreatedAt(),
|
||||
cfg.getUpdatedAt());
|
||||
}
|
||||
|
||||
// ---- integration-specific glue ----
|
||||
|
||||
/** 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()
|
||||
.anyMatch(c -> c.getIntegrationType() == type && c.isLocked());
|
||||
}
|
||||
|
||||
private IntegrationConfig load(Long id) {
|
||||
return repository
|
||||
.findById(id)
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND, "Integration not found"));
|
||||
}
|
||||
|
||||
private String writeJson(Map<String, Object> config) {
|
||||
try {
|
||||
return OBJECT_MAPPER.writeValueAsString(config == null ? Map.of() : config);
|
||||
} catch (Exception e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid config payload");
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> readJson(String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(
|
||||
json, new TypeReference<LinkedHashMap<String, Object>>() {});
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to parse integration config JSON", e);
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T require(T value, String field) {
|
||||
if (value == null || (value instanceof String s && s.isBlank())) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, field + " is required");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private ResponseStatusException forbidden(String message) {
|
||||
return new ResponseStatusException(HttpStatus.FORBIDDEN, message);
|
||||
}
|
||||
}
|
||||
+2
-6
@@ -33,10 +33,8 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
|
||||
"stirling.software.proprietary.storage.repository",
|
||||
"stirling.software.proprietary.workflow.repository",
|
||||
"stirling.software.proprietary.policy.store",
|
||||
"stirling.software.proprietary.policy.source",
|
||||
"stirling.software.proprietary.accountlink",
|
||||
"stirling.software.proprietary.access.repository",
|
||||
"stirling.software.proprietary.integration.repository"
|
||||
"stirling.software.proprietary.policy.source"
|
||||
})
|
||||
@EntityScan({
|
||||
"stirling.software.proprietary.security.model",
|
||||
@@ -44,10 +42,8 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
|
||||
"stirling.software.proprietary.storage.model",
|
||||
"stirling.software.proprietary.workflow.model",
|
||||
"stirling.software.proprietary.policy.store",
|
||||
"stirling.software.proprietary.policy.source",
|
||||
"stirling.software.proprietary.accountlink",
|
||||
"stirling.software.proprietary.access.model",
|
||||
"stirling.software.proprietary.integration.model"
|
||||
"stirling.software.proprietary.policy.source"
|
||||
})
|
||||
public class DatabaseConfig {
|
||||
|
||||
|
||||
-3
@@ -28,7 +28,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.constants.JwtConstants;
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.access.service.ResourceAccessService;
|
||||
import stirling.software.proprietary.audit.AuditEventType;
|
||||
import stirling.software.proprietary.audit.AuditLevel;
|
||||
import stirling.software.proprietary.audit.Audited;
|
||||
@@ -65,7 +64,6 @@ public class AuthController {
|
||||
private final ApplicationProperties.Security securityProperties;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final AiUserDataService aiUserDataService;
|
||||
private final ResourceAccessService resourceAccessService;
|
||||
|
||||
/**
|
||||
* Login endpoint - replaces Supabase signInWithPassword
|
||||
@@ -630,7 +628,6 @@ public class AuthController {
|
||||
userMap.put("username", user.getUsername());
|
||||
userMap.put("role", user.getRolesAsString());
|
||||
userMap.put("enabled", user.isEnabled());
|
||||
userMap.put("portalAccess", resourceAccessService.canAccessPortal(user));
|
||||
userMap.put(
|
||||
"authenticationType",
|
||||
user.getAuthenticationType()); // Expose authentication type for SSO detection
|
||||
|
||||
-174
@@ -1,174 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
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.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
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;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import stirling.software.proprietary.access.model.OwnedResource;
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.access.model.ResourceType;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.security.model.Authority;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
import stirling.software.proprietary.security.repository.TeamRepository;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class OwnershipServiceTest {
|
||||
|
||||
private static final ResourceType TYPE = ResourceType.INTEGRATION_CONFIG;
|
||||
|
||||
@Mock private ResourceAccessService accessService;
|
||||
@Mock private TeamLeadLookup teamLeadLookup;
|
||||
@Mock private TeamRepository teamRepository;
|
||||
|
||||
@InjectMocks private OwnershipService ownership;
|
||||
|
||||
/** Minimal concrete OwnedResource for exercising the base behaviour. */
|
||||
static class TestResource extends OwnedResource {
|
||||
private final Long id;
|
||||
|
||||
TestResource(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- scope-based create authorization ----
|
||||
|
||||
@Test
|
||||
void userScopeSetsOwner() {
|
||||
User user = user(7);
|
||||
TestResource r = new TestResource(1L);
|
||||
|
||||
ownership.assignOwnership(r, OwnerScope.USER, null, user, () -> false);
|
||||
|
||||
assertThat(r.getScope()).isEqualTo(OwnerScope.USER);
|
||||
assertThat(r.getOwnerUser()).isSameAs(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
void userScopeBlockedByLockedServerOverride() {
|
||||
assertForbidden(
|
||||
() ->
|
||||
ownership.assignOwnership(
|
||||
new TestResource(1L), OwnerScope.USER, null, user(7), () -> true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminMayCreateServerScope() {
|
||||
TestResource r = new TestResource(1L);
|
||||
ownership.assignOwnership(r, OwnerScope.SERVER, null, admin(1), () -> false);
|
||||
assertThat(r.getOwnerUser()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonAdminCannotCreateServerScope() {
|
||||
assertForbidden(
|
||||
() ->
|
||||
ownership.assignOwnership(
|
||||
new TestResource(1L),
|
||||
OwnerScope.SERVER,
|
||||
null,
|
||||
user(7),
|
||||
() -> false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void teamLeaderMayCreateTeamScope() {
|
||||
Team team = new Team();
|
||||
team.setId(5L);
|
||||
User user = user(7);
|
||||
when(teamRepository.findById(5L)).thenReturn(Optional.of(team));
|
||||
when(teamLeadLookup.isLeaderOfTeam(user, 5L)).thenReturn(true);
|
||||
|
||||
TestResource r = new TestResource(1L);
|
||||
ownership.assignOwnership(r, OwnerScope.TEAM, 5L, user, () -> false);
|
||||
|
||||
assertThat(r.getOwnerTeam()).isSameAs(team);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonLeaderCannotCreateTeamScope() {
|
||||
Team team = new Team();
|
||||
team.setId(5L);
|
||||
when(teamRepository.findById(5L)).thenReturn(Optional.of(team));
|
||||
|
||||
assertForbidden(
|
||||
() ->
|
||||
ownership.assignOwnership(
|
||||
new TestResource(1L), OwnerScope.TEAM, 5L, user(7), () -> false));
|
||||
}
|
||||
|
||||
// ---- use / manage ----
|
||||
|
||||
@Test
|
||||
void enabledResourceUseDelegatesToTheAcl() {
|
||||
TestResource r = new TestResource(1L);
|
||||
User user = user(7);
|
||||
when(accessService.canUseResource(any(), any(), any(), any(), any())).thenReturn(true);
|
||||
|
||||
assertThat(ownership.canUse(TYPE, r, user)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledResourceUsableOnlyByOwnerOrAdmin() {
|
||||
TestResource r = new TestResource(1L);
|
||||
r.setEnabled(false);
|
||||
r.setOwnerUser(user(7));
|
||||
|
||||
assertThat(ownership.canUse(TYPE, r, user(7))).isTrue(); // owner
|
||||
assertThat(ownership.canUse(TYPE, r, user(8))).isFalse(); // someone else
|
||||
assertThat(ownership.canUse(TYPE, r, admin(2))).isTrue(); // admin
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledTeamResourceUsableByLeaderOfOwningTeam() {
|
||||
Team team = new Team();
|
||||
team.setId(5L);
|
||||
TestResource r = new TestResource(1L);
|
||||
r.setEnabled(false);
|
||||
r.setOwnerTeam(team);
|
||||
User leader = user(7);
|
||||
when(teamLeadLookup.isLeaderOfTeam(leader, 5L)).thenReturn(true);
|
||||
|
||||
assertThat(ownership.canUse(TYPE, r, leader)).isTrue(); // lead of the owning team
|
||||
assertThat(ownership.canUse(TYPE, r, user(8))).isFalse(); // not a lead
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
private void assertForbidden(org.assertj.core.api.ThrowableAssert.ThrowingCallable call) {
|
||||
assertThatThrownBy(call)
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode())
|
||||
.isEqualTo(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
private User user(long id) {
|
||||
User u = new User();
|
||||
u.setId(id);
|
||||
u.setUsername("user" + id);
|
||||
return u;
|
||||
}
|
||||
|
||||
private User admin(long id) {
|
||||
User u = user(id);
|
||||
new Authority("ROLE_ADMIN", u);
|
||||
return u;
|
||||
}
|
||||
}
|
||||
-217
@@ -1,217 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
|
||||
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 stirling.software.proprietary.access.model.AccessPermission;
|
||||
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
|
||||
import stirling.software.proprietary.access.model.PrincipalType;
|
||||
import stirling.software.proprietary.access.model.ResourceGrant;
|
||||
import stirling.software.proprietary.access.model.ResourceType;
|
||||
import stirling.software.proprietary.access.repository.ResourceGrantRepository;
|
||||
import stirling.software.proprietary.model.Team;
|
||||
import stirling.software.proprietary.security.model.Authority;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ResourceAccessServiceTest {
|
||||
|
||||
private static final ResourceType TYPE = ResourceType.INTEGRATION_CONFIG;
|
||||
private static final String RID = "42";
|
||||
|
||||
@Mock private ResourceGrantRepository grantRepository;
|
||||
@Mock private TeamLeadLookup teamLeadLookup;
|
||||
|
||||
@InjectMocks private ResourceAccessService service;
|
||||
|
||||
@BeforeEach
|
||||
void setPortalDefault() throws Exception {
|
||||
Field f = ResourceAccessService.class.getDeclaredField("portalDefaultPolicy");
|
||||
f.setAccessible(true);
|
||||
f.set(service, DefaultAccessPolicy.ADMINS_AND_TEAM_LEADS);
|
||||
}
|
||||
|
||||
// ---- owner / admin short-circuits ----
|
||||
|
||||
@Test
|
||||
void adminMayUseEvenWithExplicitOnlyAndNoGrants() {
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE, RID, null, DefaultAccessPolicy.EXPLICIT_ONLY, admin(1)))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownerMayUseEvenWithExplicitOnly() {
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE, RID, 5L, DefaultAccessPolicy.EXPLICIT_ONLY, user(5)))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullUserIsAlwaysDenied() {
|
||||
assertThat(service.canUseResource(TYPE, RID, 5L, DefaultAccessPolicy.ORG_ALL, null))
|
||||
.isFalse();
|
||||
assertThat(service.canManageResource(TYPE, RID, 5L, null)).isFalse();
|
||||
}
|
||||
|
||||
// ---- explicit grants ----
|
||||
|
||||
@Test
|
||||
void explicitUserGrantAllowsUse() {
|
||||
stubGrants(grant(PrincipalType.USER, 5L, AccessPermission.USE));
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE, RID, null, DefaultAccessPolicy.EXPLICIT_ONLY, user(5)))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void teamGrantAllowsUseForTeamMember() {
|
||||
stubGrants(grant(PrincipalType.TEAM, 7L, AccessPermission.USE));
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE,
|
||||
RID,
|
||||
null,
|
||||
DefaultAccessPolicy.EXPLICIT_ONLY,
|
||||
userInTeam(5, 7)))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void teamGrantDoesNotLeakToOtherTeams() {
|
||||
stubGrants(grant(PrincipalType.TEAM, 7L, AccessPermission.USE));
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE,
|
||||
RID,
|
||||
null,
|
||||
DefaultAccessPolicy.EXPLICIT_ONLY,
|
||||
userInTeam(5, 99)))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void manageGrantImpliesUse() {
|
||||
stubGrants(grant(PrincipalType.USER, 5L, AccessPermission.MANAGE));
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE, RID, null, DefaultAccessPolicy.EXPLICIT_ONLY, user(5)))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void useGrantDoesNotImplyManage() {
|
||||
stubGrants(grant(PrincipalType.USER, 5L, AccessPermission.USE));
|
||||
assertThat(service.canManageResource(TYPE, RID, null, user(5))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void manageGrantAllowsManage() {
|
||||
stubGrants(grant(PrincipalType.USER, 5L, AccessPermission.MANAGE));
|
||||
assertThat(service.canManageResource(TYPE, RID, null, user(5))).isTrue();
|
||||
}
|
||||
|
||||
// ---- default policies ----
|
||||
|
||||
@Test
|
||||
void orgAllDefaultAllowsAnyUser() {
|
||||
stubGrants();
|
||||
assertThat(service.canUseResource(TYPE, RID, null, DefaultAccessPolicy.ORG_ALL, user(5)))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitOnlyDefaultDeniesUngrantedUser() {
|
||||
stubGrants();
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE, RID, null, DefaultAccessPolicy.EXPLICIT_ONLY, user(5)))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void teamLeadDefaultAllowsLeaderButNotRegularUser() {
|
||||
stubGrants();
|
||||
User leader = user(5);
|
||||
when(teamLeadLookup.isAnyTeamLeader(leader)).thenReturn(true);
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE, RID, null, DefaultAccessPolicy.ADMINS_AND_TEAM_LEADS, leader))
|
||||
.isTrue();
|
||||
|
||||
stubGrants();
|
||||
assertThat(
|
||||
service.canUseResource(
|
||||
TYPE,
|
||||
RID,
|
||||
null,
|
||||
DefaultAccessPolicy.ADMINS_AND_TEAM_LEADS,
|
||||
user(6)))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
// ---- portal convenience (default policy ADMINS_AND_TEAM_LEADS) ----
|
||||
|
||||
@Test
|
||||
void portalAccessibleByAdmin() {
|
||||
assertThat(service.canAccessPortal(admin(1))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void portalDeniedToRegularUser() {
|
||||
when(grantRepository.findByResourceTypeAndResourceId(ResourceType.PORTAL, ""))
|
||||
.thenReturn(List.of());
|
||||
assertThat(service.canAccessPortal(user(5))).isFalse();
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
private void stubGrants(ResourceGrant... grants) {
|
||||
when(grantRepository.findByResourceTypeAndResourceId(TYPE, RID))
|
||||
.thenReturn(List.of(grants));
|
||||
}
|
||||
|
||||
private ResourceGrant grant(PrincipalType type, long principalId, AccessPermission permission) {
|
||||
ResourceGrant g = new ResourceGrant();
|
||||
g.setResourceType(TYPE);
|
||||
g.setResourceId(RID);
|
||||
g.setPrincipalType(type);
|
||||
g.setPrincipalId(principalId);
|
||||
g.setPermission(permission);
|
||||
return g;
|
||||
}
|
||||
|
||||
private User user(long id) {
|
||||
User u = new User();
|
||||
u.setId(id);
|
||||
u.setUsername("user" + id);
|
||||
return u;
|
||||
}
|
||||
|
||||
private User admin(long id) {
|
||||
User u = user(id);
|
||||
new Authority("ROLE_ADMIN", u);
|
||||
return u;
|
||||
}
|
||||
|
||||
private User userInTeam(long id, long teamId) {
|
||||
User u = user(id);
|
||||
Team team = new Team();
|
||||
team.setId(teamId);
|
||||
u.setTeam(team);
|
||||
return u;
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package stirling.software.proprietary.access.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SecretMaskerTest {
|
||||
|
||||
private final SecretMasker masker = new SecretMasker();
|
||||
|
||||
@Test
|
||||
void maskHidesFlatAndNestedSecretsButKeepsPlainFields() {
|
||||
Map<String, Object> nested = new LinkedHashMap<>();
|
||||
nested.put("host", "h.example");
|
||||
nested.put("secretKey", "sk-real");
|
||||
Map<String, Object> config = new LinkedHashMap<>();
|
||||
config.put("bucket", "acme");
|
||||
config.put("accessKey", "AKIA123");
|
||||
config.put("connection", nested); // non-sensitive parent, sensitive child
|
||||
|
||||
Map<String, Object> masked = masker.mask(config);
|
||||
|
||||
assertThat(masked.get("bucket")).isEqualTo("acme");
|
||||
assertThat(masked.get("accessKey")).isEqualTo(SecretMasker.MASK);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> conn = (Map<String, Object>) masked.get("connection");
|
||||
assertThat(conn.get("host")).isEqualTo("h.example");
|
||||
assertThat(conn.get("secretKey")).isEqualTo(SecretMasker.MASK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeKeepsStoredSecretWhenIncomingIsMasked() {
|
||||
Map<String, Object> stored = Map.of("bucket", "old", "secretKey", "REAL");
|
||||
Map<String, Object> incoming = Map.of("bucket", "new", "secretKey", SecretMasker.MASK);
|
||||
|
||||
Map<String, Object> merged = masker.merge(stored, incoming);
|
||||
|
||||
assertThat(merged.get("bucket")).isEqualTo("new"); // non-secret updated
|
||||
assertThat(merged.get("secretKey")).isEqualTo("REAL"); // secret retained
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergeAcceptsARealNewSecret() {
|
||||
Map<String, Object> merged =
|
||||
masker.merge(Map.of("secretKey", "OLD"), Map.of("secretKey", "NEW"));
|
||||
assertThat(merged.get("secretKey")).isEqualTo("NEW");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sanitizeDropsBlankSecretsOnCreate() {
|
||||
Map<String, Object> incoming = new LinkedHashMap<>();
|
||||
incoming.put("bucket", "b");
|
||||
incoming.put("secretKey", "");
|
||||
|
||||
Map<String, Object> clean = masker.sanitize(incoming);
|
||||
|
||||
assertThat(clean).containsEntry("bucket", "b").doesNotContainKey("secretKey");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deeplyNestedInputIsBoundedNotOverflowing() {
|
||||
// Build a structure far deeper than the recursion cap.
|
||||
Map<String, Object> root = new LinkedHashMap<>();
|
||||
Map<String, Object> cur = root;
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
Map<String, Object> next = new LinkedHashMap<>();
|
||||
cur.put("child", next);
|
||||
cur = next;
|
||||
}
|
||||
cur.put("secretKey", "deep");
|
||||
|
||||
// Must return (bounded recursion), not throw StackOverflowError.
|
||||
assertThat(masker.mask(root)).isNotNull();
|
||||
assertThat(masker.sanitize(root)).isNotNull();
|
||||
assertThat(masker.merge(root, root)).isNotNull();
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package stirling.software.proprietary.integration.crypto;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CredentialEncryptionTest {
|
||||
|
||||
@BeforeAll
|
||||
static void initKey() throws Exception {
|
||||
KeyGenerator generator = KeyGenerator.getInstance("AES");
|
||||
generator.init(256);
|
||||
SecretKey key = generator.generateKey();
|
||||
CredentialEncryption.initialiseForTesting(key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void roundTripRecoversPlaintext() {
|
||||
String plaintext = "s3-secret-key-ABC123/+=value";
|
||||
String encrypted = CredentialEncryption.encrypt(plaintext);
|
||||
|
||||
assertThat(encrypted).isNotNull().isNotEqualTo(plaintext);
|
||||
assertThat(CredentialEncryption.decrypt(encrypted)).isEqualTo(plaintext);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameInputProducesDifferentCiphertext() {
|
||||
String plaintext = "repeated-secret";
|
||||
|
||||
// Random IV per encryption => ciphertext must differ, but both decrypt back.
|
||||
String first = CredentialEncryption.encrypt(plaintext);
|
||||
String second = CredentialEncryption.encrypt(plaintext);
|
||||
|
||||
assertThat(first).isNotEqualTo(second);
|
||||
assertThat(CredentialEncryption.decrypt(first)).isEqualTo(plaintext);
|
||||
assertThat(CredentialEncryption.decrypt(second)).isEqualTo(plaintext);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullsPassThrough() {
|
||||
assertThat(CredentialEncryption.encrypt(null)).isNull();
|
||||
assertThat(CredentialEncryption.decrypt(null)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void tamperedCiphertextIsRejected() {
|
||||
// GCM is authenticated: flipping a byte of the stored blob must fail decryption, not
|
||||
// silently return corrupted plaintext.
|
||||
String encrypted = CredentialEncryption.encrypt("top-secret");
|
||||
byte[] raw = Base64.getDecoder().decode(encrypted);
|
||||
raw[raw.length - 1] ^= 0x01;
|
||||
String tampered = Base64.getEncoder().encodeToString(raw);
|
||||
|
||||
assertThatThrownBy(() -> CredentialEncryption.decrypt(tampered))
|
||||
.isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
}
|
||||
-182
@@ -1,182 +0,0 @@
|
||||
package stirling.software.proprietary.integration.service;
|
||||
|
||||
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.ArgumentMatchers.isNull;
|
||||
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.Set;
|
||||
|
||||
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;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import stirling.software.proprietary.access.model.DefaultAccessPolicy;
|
||||
import stirling.software.proprietary.access.model.OwnerScope;
|
||||
import stirling.software.proprietary.access.service.OwnershipService;
|
||||
import stirling.software.proprietary.access.service.SecretMasker;
|
||||
import stirling.software.proprietary.integration.dto.IntegrationConfigRequest;
|
||||
import stirling.software.proprietary.integration.dto.IntegrationConfigResponse;
|
||||
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 tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Integration-glue tests. Ownership authorization and secret masking are covered by {@code
|
||||
* OwnershipServiceTest} / {@code SecretMaskerTest}; here those collaborators are mocked and we
|
||||
* assert this service delegates to them correctly.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class IntegrationConfigServiceTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Mock private IntegrationConfigRepository repository;
|
||||
@Mock private OwnershipService ownership;
|
||||
@Mock private SecretMasker secretMasker;
|
||||
|
||||
@InjectMocks private IntegrationConfigService service;
|
||||
|
||||
@Test
|
||||
void createDelegatesOwnershipAndSanitizesConfig() {
|
||||
when(secretMasker.sanitize(any())).thenReturn(Map.of("bucket", "b"));
|
||||
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
User user = user(7);
|
||||
|
||||
IntegrationConfig created =
|
||||
service.create(request(IntegrationType.S3, OwnerScope.USER, null), user);
|
||||
|
||||
assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.S3);
|
||||
assertThat(created.getName()).isEqualTo("name");
|
||||
verify(ownership)
|
||||
.assignOwnership(eq(created), eq(OwnerScope.USER), isNull(), eq(user), any());
|
||||
verify(secretMasker).sanitize(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateMergesConfigViaSecretMasker() throws Exception {
|
||||
IntegrationConfig cfg = config(2L);
|
||||
cfg.setConfig("{\"bucket\":\"old\",\"secretKey\":\"REAL\"}");
|
||||
when(repository.findById(2L)).thenReturn(Optional.of(cfg));
|
||||
when(ownership.canManage(any(), eq(cfg), any())).thenReturn(true);
|
||||
when(secretMasker.merge(any(), any()))
|
||||
.thenReturn(Map.of("bucket", "new", "secretKey", "REAL"));
|
||||
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
IntegrationConfigRequest req =
|
||||
new IntegrationConfigRequest(
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
Map.of("bucket", "new", "secretKey", "********"));
|
||||
service.update(2L, req, user(7));
|
||||
|
||||
Map<String, Object> stored =
|
||||
MAPPER.readValue(cfg.getConfig(), new TypeReference<Map<String, Object>>() {});
|
||||
assertThat(stored.get("bucket")).isEqualTo("new");
|
||||
assertThat(stored.get("secretKey")).isEqualTo("REAL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateForbiddenWhenCannotManage() {
|
||||
IntegrationConfig cfg = config(3L);
|
||||
when(repository.findById(3L)).thenReturn(Optional.of(cfg));
|
||||
when(ownership.canManage(any(), eq(cfg), any())).thenReturn(false);
|
||||
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
service.update(
|
||||
3L,
|
||||
request(IntegrationType.S3, OwnerScope.USER, null),
|
||||
user(7)))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode())
|
||||
.isEqualTo(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void toResponseMasksConfig() {
|
||||
IntegrationConfig cfg = config(4L);
|
||||
cfg.setConfig("{\"secretKey\":\"x\"}");
|
||||
when(secretMasker.mask(any())).thenReturn(Map.of("secretKey", SecretMasker.MASK));
|
||||
when(ownership.canManage(any(), eq(cfg), any())).thenReturn(false);
|
||||
|
||||
IntegrationConfigResponse resp = service.toResponse(cfg, user(7));
|
||||
|
||||
assertThat(resp.config().get("secretKey")).isEqualTo(SecretMasker.MASK);
|
||||
assertThat(resp.canManage()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listIncludesAConfigSharedViaAnExplicitGrant() {
|
||||
User user = user(7);
|
||||
when(repository.findByOwnerUser(user)).thenReturn(List.of());
|
||||
when(repository.findByScope(OwnerScope.SERVER)).thenReturn(List.of());
|
||||
when(ownership.grantedResourceIds(any(), eq(user))).thenReturn(Set.of("99"));
|
||||
IntegrationConfig shared = config(99L);
|
||||
when(repository.findById(99L)).thenReturn(Optional.of(shared));
|
||||
when(ownership.canUse(any(), eq(shared), eq(user))).thenReturn(true);
|
||||
|
||||
List<IntegrationConfig> visible = service.listVisible(user);
|
||||
|
||||
assertThat(visible).extracting(IntegrationConfig::getId).contains(99L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonAdminCannotChangeLockedFlag() {
|
||||
IntegrationConfig cfg = config(5L); // locked = false
|
||||
when(repository.findById(5L)).thenReturn(Optional.of(cfg));
|
||||
when(ownership.canManage(any(), eq(cfg), any())).thenReturn(true);
|
||||
when(ownership.isAdmin(any())).thenReturn(false);
|
||||
|
||||
IntegrationConfigRequest req =
|
||||
new IntegrationConfigRequest(null, null, null, null, null, true, null, null);
|
||||
|
||||
assertThatThrownBy(() -> service.update(5L, req, user(7)))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.extracting(e -> ((ResponseStatusException) e).getStatusCode())
|
||||
.isEqualTo(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
private IntegrationConfig config(long id) {
|
||||
IntegrationConfig cfg = new IntegrationConfig();
|
||||
cfg.setId(id);
|
||||
cfg.setIntegrationType(IntegrationType.S3);
|
||||
cfg.setName("cfg" + id);
|
||||
cfg.setEnabled(true);
|
||||
cfg.setDefaultAccess(DefaultAccessPolicy.EXPLICIT_ONLY);
|
||||
return cfg;
|
||||
}
|
||||
|
||||
private IntegrationConfigRequest request(IntegrationType type, OwnerScope scope, Long teamId) {
|
||||
return new IntegrationConfigRequest(
|
||||
type, "name", scope, teamId, null, null, null, Map.of("bucket", "b"));
|
||||
}
|
||||
|
||||
private User user(long id) {
|
||||
User u = new User();
|
||||
u.setId(id);
|
||||
u.setUsername("user" + id);
|
||||
return u;
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -28,7 +28,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.enumeration.Role;
|
||||
import stirling.software.proprietary.access.service.ResourceAccessService;
|
||||
import stirling.software.proprietary.security.model.AuthenticationType;
|
||||
import stirling.software.proprietary.security.model.Authority;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
@@ -59,7 +58,6 @@ class AuthControllerLoginTest {
|
||||
@Mock private MfaService mfaService;
|
||||
@Mock private TotpService totpService;
|
||||
@Mock private RefreshRateLimitService refreshRateLimitService;
|
||||
@Mock private ResourceAccessService resourceAccessService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -82,8 +80,7 @@ class AuthControllerLoginTest {
|
||||
refreshRateLimitService,
|
||||
securityProperties,
|
||||
applicationProperties,
|
||||
new stirling.software.proprietary.service.AiUserDataService(null),
|
||||
resourceAccessService);
|
||||
new stirling.software.proprietary.service.AiUserDataService(null));
|
||||
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
|
||||
+1
-4
@@ -28,7 +28,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.enumeration.Role;
|
||||
import stirling.software.proprietary.access.service.ResourceAccessService;
|
||||
import stirling.software.proprietary.security.model.AuthenticationType;
|
||||
import stirling.software.proprietary.security.model.Authority;
|
||||
import stirling.software.proprietary.security.model.User;
|
||||
@@ -60,7 +59,6 @@ class AuthControllerMoreTest {
|
||||
@Mock private MfaService mfaService;
|
||||
@Mock private TotpService totpService;
|
||||
@Mock private RefreshRateLimitService refreshRateLimitService;
|
||||
@Mock private ResourceAccessService resourceAccessService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -83,8 +81,7 @@ class AuthControllerMoreTest {
|
||||
refreshRateLimitService,
|
||||
securityProperties,
|
||||
applicationProperties,
|
||||
new stirling.software.proprietary.service.AiUserDataService(null),
|
||||
resourceAccessService);
|
||||
new stirling.software.proprietary.service.AiUserDataService(null));
|
||||
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
-- Resource access grants: which user/team may use a gated resource (portal, integration config).
|
||||
|
||||
CREATE TABLE IF NOT EXISTS resource_grants (
|
||||
resource_grant_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
resource_type VARCHAR(64) NOT NULL,
|
||||
resource_id VARCHAR(255) NOT NULL DEFAULT '',
|
||||
principal_type VARCHAR(32) NOT NULL,
|
||||
principal_id BIGINT NOT NULL,
|
||||
permission VARCHAR(32) NOT NULL,
|
||||
granted_by_user_id BIGINT,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_resource_grant
|
||||
ON resource_grants (resource_type, resource_id, principal_type, principal_id, permission);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_resource_grants_lookup
|
||||
ON resource_grants (resource_type, resource_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_resource_grants_principal
|
||||
ON resource_grants (principal_type, principal_id);
|
||||
@@ -1,25 +0,0 @@
|
||||
-- S3/MCP/API integration configs; config_encrypted holds an AES-GCM encrypted JSON blob.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS integration_configs (
|
||||
integration_config_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
integration_type VARCHAR(32) NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
scope VARCHAR(32) NOT NULL,
|
||||
owner_user_id BIGINT,
|
||||
owner_team_id BIGINT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
locked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
default_access VARCHAR(32) NOT NULL DEFAULT 'EXPLICIT_ONLY',
|
||||
config_encrypted TEXT,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_integration_configs_owner
|
||||
ON integration_configs (owner_user_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_integration_configs_type
|
||||
ON integration_configs (integration_type);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_integration_configs_scope
|
||||
ON integration_configs (scope);
|
||||
@@ -1,5 +1,8 @@
|
||||
"""Agent modules for Stirling AI reasoning flows."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
from ._registry import AgentDescriptor, RegisterableAgent
|
||||
from .execution import ExecutionPlanningAgent
|
||||
from .orchestrator import OrchestratorAgent
|
||||
from .pdf_create import PdfCreateAgent
|
||||
@@ -8,7 +11,17 @@ from .pdf_questions import PdfQuestionAgent
|
||||
from .pdf_review import PdfReviewAgent
|
||||
from .user_spec import UserSpecAgent
|
||||
|
||||
|
||||
def build_descriptors(agents: Iterable[RegisterableAgent]) -> list[AgentDescriptor]:
|
||||
"""The canonical descriptor list driving both orchestrator routing and the MCP
|
||||
manifest. Pass the live agent singletons. Adding an agent means implementing
|
||||
``describe`` and including its instance in the caller's list.
|
||||
"""
|
||||
return [agent.describe() for agent in agents]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AgentDescriptor",
|
||||
"ExecutionPlanningAgent",
|
||||
"OrchestratorAgent",
|
||||
"PdfCreateAgent",
|
||||
@@ -17,5 +30,7 @@ __all__ = [
|
||||
"PdfEditPlanSelection",
|
||||
"PdfQuestionAgent",
|
||||
"PdfReviewAgent",
|
||||
"RegisterableAgent",
|
||||
"UserSpecAgent",
|
||||
"build_descriptors",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Single source of truth for how each agent is exposed.
|
||||
|
||||
An agent declares one :class:`AgentDescriptor` via :meth:`RegisterableAgent.describe`.
|
||||
Two projections are derived from the collected descriptors, so neither has to be
|
||||
hand-maintained:
|
||||
|
||||
* the **orchestrator** builds its delegate ``ToolOutput`` union and ``resume``
|
||||
dispatch from descriptors whose ``orchestrator`` route is set;
|
||||
* the **MCP capabilities manifest** is built from descriptors' ``mcp`` rows.
|
||||
|
||||
Adding an agent therefore means implementing ``describe`` and adding the instance
|
||||
to ``build_descriptors`` — the orchestrator and the manifest both update for free.
|
||||
|
||||
Note: this ``AgentDescriptor`` registry (how an agent is *published*) is unrelated
|
||||
to the runtime "capability" toolsets like ``ContradictionCapability`` /
|
||||
``RagCapability`` (tools *injected into* an agent run).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_ai.output import ToolOutput
|
||||
from pydantic_ai.tools import RunContext
|
||||
|
||||
from stirling.contracts import OrchestratorRequest, OrchestratorResponse, SupportedCapability
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
OrchestrateFn = Callable[[OrchestratorRequest], Awaitable[OrchestratorResponse]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrchestratorDeps:
|
||||
runtime: AppRuntime
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrchestratorRoute:
|
||||
"""How an agent is exposed to the top-level orchestrator LLM and resume path.
|
||||
|
||||
``capability`` keys the resume dispatch: the orchestrator re-enters this
|
||||
delegate when a ``resume_with`` of the same value arrives.
|
||||
"""
|
||||
|
||||
capability: SupportedCapability
|
||||
tool_name: str
|
||||
tool_description: str
|
||||
orchestrate: OrchestrateFn
|
||||
|
||||
async def _invoke(self, ctx: RunContext[OrchestratorDeps]) -> OrchestratorResponse:
|
||||
return await self.orchestrate(ctx.deps.request)
|
||||
|
||||
def tool_output(self) -> ToolOutput[OrchestratorResponse]:
|
||||
return ToolOutput(self._invoke, name=self.tool_name, description=self.tool_description)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class McpCapability:
|
||||
"""One row in the MCP capabilities manifest the Java MCP server publishes."""
|
||||
|
||||
id: str
|
||||
description: str
|
||||
input_model: type[BaseModel]
|
||||
mode: Literal["sync", "async"]
|
||||
required_scope: str
|
||||
route: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentDescriptor:
|
||||
"""How one agent is published. ``orchestrator`` set => routable by the
|
||||
top-level orchestrator; ``mcp`` non-empty => exposed in the MCP manifest.
|
||||
The two are independent: an agent may be one, the other, or both."""
|
||||
|
||||
orchestrator: OrchestratorRoute | None = None
|
||||
mcp: tuple[McpCapability, ...] = ()
|
||||
|
||||
|
||||
class RegisterableAgent(ABC):
|
||||
"""Base for any agent that publishes itself to the orchestrator and/or MCP.
|
||||
|
||||
Enforces a uniform ``describe`` entry point that startup wiring collects via
|
||||
``build_descriptors``."""
|
||||
|
||||
@abstractmethod
|
||||
def describe(self) -> AgentDescriptor: ...
|
||||
@@ -1,13 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, RegisterableAgent
|
||||
from stirling.contracts import AgentExecutionRequest, CannotContinueExecutionAction, NextExecutionAction
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
|
||||
class ExecutionPlanningAgent:
|
||||
class ExecutionPlanningAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
# MCP-only: an internal sub-agent the orchestrator never delegates to.
|
||||
return AgentDescriptor(
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="agent-next-action",
|
||||
description=(
|
||||
"Decide the next execution step for an in-progress agent workflow. Returns a"
|
||||
" ToolCall, Completed, or CannotContinue action."
|
||||
),
|
||||
input_model=AgentExecutionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/agents/next-action",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def next_action(self, request: AgentExecutionRequest) -> NextExecutionAction:
|
||||
return CannotContinueExecutionAction(
|
||||
reason=f"Execution planning is not implemented yet for step {request.current_step_index}."
|
||||
|
||||
@@ -29,6 +29,7 @@ from pydantic import BaseModel, Field
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.exceptions import AgentRunError
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, RegisterableAgent
|
||||
from stirling.contracts.ledger import (
|
||||
Discrepancy,
|
||||
DiscrepancyKind,
|
||||
@@ -113,7 +114,7 @@ class StatementsResult(BaseModel):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class MathAuditorAgent:
|
||||
class MathAuditorAgent(RegisterableAgent):
|
||||
"""
|
||||
Encapsulates the Ledger Auditor pipeline.
|
||||
|
||||
@@ -121,6 +122,37 @@ class MathAuditorAgent:
|
||||
pre-built Model objects and ModelSettings.
|
||||
"""
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
# MCP-only: the orchestrator reaches the math auditor indirectly (an agent
|
||||
# emits a plan with the MATH_AUDITOR_AGENT tool, which Java runs via the
|
||||
# examine/deliberate routes), so there is no orchestrator delegate here.
|
||||
return AgentDescriptor(
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="math-audit-examine",
|
||||
description=(
|
||||
"Examine a folio manifest of financial / numeric documents and surface the"
|
||||
" evidence that needs to be checked for arithmetic consistency."
|
||||
),
|
||||
input_model=FolioManifest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/examine",
|
||||
),
|
||||
McpCapability(
|
||||
id="math-audit-deliberate",
|
||||
description=(
|
||||
"Render a deliberated verdict on a single piece of evidence the examine step"
|
||||
" surfaced (does the arithmetic check out, with what caveats)."
|
||||
),
|
||||
input_model=Evidence,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/deliberate",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
fast_model = runtime.fast_model
|
||||
model_settings = runtime.fast_model_settings
|
||||
|
||||
@@ -1,91 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import assert_never
|
||||
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import ToolOutput
|
||||
from pydantic_ai.tools import RunContext
|
||||
|
||||
from stirling.agents.pdf_create import PdfCreateAgent
|
||||
from stirling.agents.pdf_edit import PdfEditAgent
|
||||
from stirling.agents.pdf_questions import PdfQuestionAgent
|
||||
from stirling.agents.pdf_review import PdfReviewAgent
|
||||
from stirling.agents.user_spec import UserSpecAgent
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorDeps, OrchestratorRoute
|
||||
from stirling.contracts import (
|
||||
AgentDraftWorkflowResponse,
|
||||
ConvertMarkdownResponse,
|
||||
ExtractedTextArtifact,
|
||||
OrchestratorRequest,
|
||||
OrchestratorResponse,
|
||||
PdfEditResponse,
|
||||
PdfQuestionOrchestrateResponse,
|
||||
PdfReviewOrchestrateResponse,
|
||||
SupportedCapability,
|
||||
UnsupportedCapabilityResponse,
|
||||
format_conversation_history,
|
||||
format_file_names,
|
||||
)
|
||||
from stirling.contracts.pdf_create import PdfCreateOrchestrateResponse
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrchestratorDeps:
|
||||
runtime: AppRuntime
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
class OrchestratorAgent:
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
def __init__(self, runtime: AppRuntime, descriptors: list[AgentDescriptor]) -> None:
|
||||
self.runtime = runtime
|
||||
routes = [d.orchestrator for d in descriptors if d.orchestrator is not None]
|
||||
self._delegates_by_capability: dict[SupportedCapability, OrchestratorRoute] = {
|
||||
route.capability: route for route in routes
|
||||
}
|
||||
self.agent = Agent(
|
||||
model=runtime.fast_model,
|
||||
output_type=[
|
||||
ToolOutput(
|
||||
self.delegate_pdf_edit,
|
||||
name="delegate_pdf_edit",
|
||||
description="Delegate requests for PDF modifications and return the PDF edit result.",
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_pdf_question,
|
||||
name="delegate_pdf_question",
|
||||
description="Delegate questions about PDF contents and return the PDF question result.",
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_user_spec,
|
||||
name="delegate_user_spec",
|
||||
description="Delegate requests to create or revise a user agent spec and return the draft result.",
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_pdf_review,
|
||||
name="delegate_pdf_review",
|
||||
description=(
|
||||
"Delegate requests to review a PDF and leave review comments, notes, or"
|
||||
" sticky-note annotations on the document itself. Use this when the user"
|
||||
" wants the PDF returned with comments attached (e.g. 'review this',"
|
||||
" 'add review comments', 'flag unclear sentences', 'annotate with"
|
||||
" feedback')."
|
||||
),
|
||||
),
|
||||
*(route.tool_output() for route in routes),
|
||||
# PDF ingest is a canned one-shot (no agent, never resumed), so like
|
||||
# unsupported_capability it lives inline rather than in the registry.
|
||||
ToolOutput(
|
||||
self.delegate_pdf_ingest,
|
||||
name="delegate_pdf_ingest",
|
||||
description=(
|
||||
"Delegate requests to convert a PDF to Markdown or extract its content as readable text."
|
||||
),
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_pdf_create,
|
||||
name="delegate_pdf_create",
|
||||
description=(
|
||||
"Delegate requests to create a new PDF document from scratch based on a"
|
||||
" description. Use this when the user wants to generate a new document"
|
||||
" (e.g. 'create an invoice', 'write a report', 'make a contract',"
|
||||
" 'draft a letter'). No input file is required."
|
||||
"Delegate any request to convert a PDF to Markdown or extract its content as readable text."
|
||||
),
|
||||
),
|
||||
ToolOutput(
|
||||
@@ -98,16 +52,7 @@ class OrchestratorAgent:
|
||||
system_prompt=(
|
||||
"You are the top-level orchestrator. "
|
||||
"Choose exactly one output function that best handles the request. "
|
||||
"Use delegate_pdf_edit for any requested modification of one or more PDFs. "
|
||||
"Use delegate_pdf_question for questions about the contents of the attached PDFs. "
|
||||
"Use delegate_user_spec for requests to create or define an agent spec. "
|
||||
"Use delegate_pdf_review when the user wants the PDF returned with review"
|
||||
" comments attached — anything like 'review this', 'annotate with comments',"
|
||||
" 'leave feedback on the PDF'. "
|
||||
"Use delegate_pdf_create when the user wants to generate a new document from"
|
||||
" scratch with no input file — invoices, reports, letters, contracts, etc. "
|
||||
"Use delegate_pdf_ingest for any request to convert a PDF to Markdown "
|
||||
"or extract its content as readable text. "
|
||||
"Consult each delegate tool's description and pick the single best fit. "
|
||||
"Use unsupported_capability when the user asks about the assistant itself "
|
||||
"or when none of the other outputs fit; supply a helpful message."
|
||||
),
|
||||
@@ -132,70 +77,23 @@ class OrchestratorAgent:
|
||||
return result.output
|
||||
|
||||
async def _resume(self, request: OrchestratorRequest, capability: SupportedCapability) -> OrchestratorResponse:
|
||||
"""Fast-path to get back to the correct endpoint without having to call AI.
|
||||
"""Fast-path back to the right delegate without consulting the LLM.
|
||||
|
||||
Also the entry point for the *multi-turn* flow where a delegate emits a plan with
|
||||
``resume_with`` set — Java runs the plan, captures any tool reports as artifacts, and
|
||||
re-enters via this method so the delegate can digest the reports.
|
||||
re-enters here so the delegate can digest the reports.
|
||||
"""
|
||||
match capability:
|
||||
case SupportedCapability.PDF_QUESTION:
|
||||
return await self._run_pdf_question(request)
|
||||
case SupportedCapability.PDF_REVIEW:
|
||||
return await self._run_pdf_review(request)
|
||||
case SupportedCapability.PDF_EDIT:
|
||||
return await self._run_pdf_edit(request)
|
||||
case SupportedCapability.AGENT_DRAFT:
|
||||
return await self._run_agent_draft(request)
|
||||
case SupportedCapability.PDF_CREATE:
|
||||
return await self._run_pdf_create(request)
|
||||
case (
|
||||
SupportedCapability.ORCHESTRATE
|
||||
| SupportedCapability.AGENT_REVISE
|
||||
| SupportedCapability.AGENT_NEXT_ACTION
|
||||
| SupportedCapability.MATH_AUDITOR_AGENT
|
||||
):
|
||||
raise ValueError(f"Cannot resume orchestrator with capability: {capability}")
|
||||
case _ as unreachable:
|
||||
assert_never(unreachable)
|
||||
|
||||
async def delegate_pdf_edit(self, ctx: RunContext[OrchestratorDeps]) -> PdfEditResponse:
|
||||
return await self._run_pdf_edit(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_edit(self, request: OrchestratorRequest) -> PdfEditResponse:
|
||||
return await PdfEditAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def delegate_pdf_question(self, ctx: RunContext[OrchestratorDeps]) -> PdfQuestionOrchestrateResponse:
|
||||
return await self._run_pdf_question(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_question(self, request: OrchestratorRequest) -> PdfQuestionOrchestrateResponse:
|
||||
return await PdfQuestionAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def delegate_user_spec(self, ctx: RunContext[OrchestratorDeps]) -> AgentDraftWorkflowResponse:
|
||||
return await self._run_agent_draft(ctx.deps.request)
|
||||
|
||||
async def _run_agent_draft(self, request: OrchestratorRequest) -> AgentDraftWorkflowResponse:
|
||||
return await UserSpecAgent(self.runtime).orchestrate(request)
|
||||
route = self._delegates_by_capability.get(capability)
|
||||
if route is None:
|
||||
raise ValueError(f"Cannot resume orchestrator with capability: {capability}")
|
||||
return await route.orchestrate(request)
|
||||
|
||||
async def delegate_pdf_ingest(self, ctx: RunContext[OrchestratorDeps]) -> ConvertMarkdownResponse:
|
||||
request = ctx.deps.request
|
||||
return ConvertMarkdownResponse(
|
||||
reason="PDF to Markdown requested — Java converts deterministically.",
|
||||
files_to_ingest=request.files,
|
||||
files_to_ingest=ctx.deps.request.files,
|
||||
)
|
||||
|
||||
async def delegate_pdf_review(self, ctx: RunContext[OrchestratorDeps]) -> PdfReviewOrchestrateResponse:
|
||||
return await self._run_pdf_review(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_review(self, request: OrchestratorRequest) -> PdfReviewOrchestrateResponse:
|
||||
return await PdfReviewAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def delegate_pdf_create(self, ctx: RunContext[OrchestratorDeps]) -> PdfCreateOrchestrateResponse:
|
||||
return await self._run_pdf_create(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_create(self, request: OrchestratorRequest) -> PdfCreateOrchestrateResponse:
|
||||
return await PdfCreateAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def unsupported_capability(
|
||||
self,
|
||||
ctx: RunContext[OrchestratorDeps],
|
||||
|
||||
@@ -20,6 +20,7 @@ import logging
|
||||
from pydantic import Field
|
||||
from pydantic_ai import Agent
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, RegisterableAgent
|
||||
from stirling.agents.pdf_comment.prompts import COMMENT_AGENT_SYSTEM_PROMPT
|
||||
from stirling.contracts.pdf_comments import (
|
||||
MAX_COMMENT_TEXT_LENGTH,
|
||||
@@ -66,7 +67,7 @@ class LlmCommentOutput(ApiModel):
|
||||
rationale: str = Field(max_length=1_000)
|
||||
|
||||
|
||||
class PdfCommentAgent:
|
||||
class PdfCommentAgent(RegisterableAgent):
|
||||
"""Encapsulates the single-shot PDF comment generation pipeline.
|
||||
|
||||
Instantiated once at app startup with an :class:`AppRuntime`, which
|
||||
@@ -82,6 +83,22 @@ class PdfCommentAgent:
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
# MCP-only: invoked as a tool inside the PDF review plan, never a
|
||||
# top-level orchestrator delegate.
|
||||
return AgentDescriptor(
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="pdf-comment-generate",
|
||||
description="Generate inline review comments for a PDF document.",
|
||||
input_model=PdfCommentRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-comment/generate",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def generate(self, request: PdfCommentRequest) -> PdfCommentResponse:
|
||||
"""Run the agent against a ``PdfCommentRequest`` and return comments.
|
||||
|
||||
|
||||
@@ -28,10 +28,12 @@ from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.contracts import (
|
||||
EditCannotDoResponse,
|
||||
EditPlanResponse,
|
||||
OrchestratorRequest,
|
||||
SupportedCapability,
|
||||
ToolOperationStep,
|
||||
format_conversation_history,
|
||||
)
|
||||
@@ -317,7 +319,7 @@ def _safe_filename(title: str) -> str:
|
||||
# ── Agent ─────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class PdfCreateAgent:
|
||||
class PdfCreateAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self._jinja_env = _build_jinja_env()
|
||||
@@ -343,6 +345,21 @@ class PdfCreateAgent:
|
||||
model_settings={**runtime.smart_model_settings, "temperature": 0.3},
|
||||
)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_CREATE,
|
||||
tool_name="delegate_pdf_create",
|
||||
tool_description=(
|
||||
"Delegate requests to create a new PDF document from scratch based on a"
|
||||
" description. Use this when the user wants to generate a new document"
|
||||
" (e.g. 'create an invoice', 'write a report', 'make a contract',"
|
||||
" 'draft a letter'). No input file is required."
|
||||
),
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> PdfCreateOrchestrateResponse:
|
||||
history = format_conversation_history(request.conversation_history)
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._page_text import format_page_text, get_extracted_text_artifact, has_page_text
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.contracts import (
|
||||
EditCannotDoResponse,
|
||||
EditClarificationRequest,
|
||||
@@ -171,11 +172,35 @@ class PdfEditParameterSelector:
|
||||
)
|
||||
|
||||
|
||||
class PdfEditAgent:
|
||||
class PdfEditAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self.parameter_selector = PdfEditParameterSelector(runtime)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_EDIT,
|
||||
tool_name="delegate_pdf_edit",
|
||||
tool_description="Delegate any requested modification of one or more PDFs; returns the edit result.",
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="pdf-edit-plan",
|
||||
description=(
|
||||
"Produce an edit plan (a structured sequence of PDF operations) from a"
|
||||
" natural-language edit request. The plan is executed by Java through the job"
|
||||
" pipeline; this capability does not modify files itself."
|
||||
),
|
||||
input_model=PdfEditRequest,
|
||||
mode="async",
|
||||
required_scope="mcp.tools.write",
|
||||
route="/api/v1/pdf-edit",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> PdfEditResponse:
|
||||
"""Entry point for the orchestrator delegate — adapts the orchestrator's
|
||||
request shape into a :class:`PdfEditRequest` and runs the standard
|
||||
|
||||
@@ -5,6 +5,7 @@ import logging
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.agents.contradiction import ContradictionCapability, ContradictionDetector
|
||||
from stirling.agents.math_presentation import MathIntentClassifier, extract_math_verdict
|
||||
from stirling.agents.shared import ChunkedReasoner, WholeDocReaderCapability
|
||||
@@ -85,7 +86,7 @@ _MATH_SYNTH_SYSTEM_PROMPT = (
|
||||
)
|
||||
|
||||
|
||||
class PdfQuestionAgent:
|
||||
class PdfQuestionAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self._math_synth_agent: Agent[None, str] = Agent(
|
||||
@@ -103,6 +104,26 @@ class PdfQuestionAgent:
|
||||
# (mirrors the chunked-reasoner pattern).
|
||||
self._contradiction_detector = ContradictionDetector(runtime)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_QUESTION,
|
||||
tool_name="delegate_pdf_question",
|
||||
tool_description="Delegate questions about the contents of the attached PDFs; returns the answer.",
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="pdf-question-answer",
|
||||
description="Answer a natural-language question about a PDF document.",
|
||||
input_model=PdfQuestionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-question",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def handle(self, request: PdfQuestionRequest) -> PdfQuestionResponse:
|
||||
logger.info(
|
||||
"[pdf-question] handle: files=%s question=%r",
|
||||
|
||||
@@ -31,6 +31,7 @@ from typing import Literal
|
||||
from pydantic import Field
|
||||
from pydantic_ai import Agent
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.agents.contradiction import ContradictionDetector, ContradictionIntentClassifier
|
||||
from stirling.agents.contradiction.detector import _escape_for_tag
|
||||
from stirling.agents.contradiction.prompts import REVIEW_LOCALISER_PROMPT
|
||||
@@ -104,7 +105,7 @@ class _LocalisedContradictionReport(ApiModel):
|
||||
comments: list[_PairedLocalisedContradiction] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PdfReviewAgent:
|
||||
class PdfReviewAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self._localiser_agent: Agent[None, _LocalisedVerdict] = Agent(
|
||||
@@ -128,6 +129,21 @@ class PdfReviewAgent:
|
||||
# request's stages.
|
||||
self._contradiction_detector = ContradictionDetector(runtime)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_REVIEW,
|
||||
tool_name="delegate_pdf_review",
|
||||
tool_description=(
|
||||
"Delegate requests to review a PDF and leave review comments, notes, or"
|
||||
" sticky-note annotations on the document itself. Use this when the user"
|
||||
" wants the PDF returned with comments attached (e.g. 'review this',"
|
||||
" 'add review comments', 'flag unclear sentences', 'annotate with feedback')."
|
||||
),
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> PdfReviewOrchestrateResponse:
|
||||
"""Entry point for the orchestrator delegate.
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.agents.pdf_edit import PdfEditAgent
|
||||
from stirling.contracts import (
|
||||
AgentDraft,
|
||||
@@ -18,6 +19,7 @@ from stirling.contracts import (
|
||||
OrchestratorRequest,
|
||||
PdfEditRequest,
|
||||
PdfEditTerminalResponse,
|
||||
SupportedCapability,
|
||||
format_conversation_history,
|
||||
)
|
||||
from stirling.models import ApiModel
|
||||
@@ -30,7 +32,7 @@ class UserSpecMetadata(ApiModel):
|
||||
objective: str
|
||||
|
||||
|
||||
class UserSpecAgent:
|
||||
class UserSpecAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self.pdf_edit_agent = PdfEditAgent(runtime)
|
||||
@@ -45,6 +47,39 @@ class UserSpecAgent:
|
||||
model_settings=runtime.smart_model_settings,
|
||||
)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.AGENT_DRAFT,
|
||||
tool_name="delegate_user_spec",
|
||||
tool_description="Delegate requests to create or define an agent spec; returns the draft result.",
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="agent-draft",
|
||||
description=(
|
||||
"Draft a structured agent specification from a free-text description"
|
||||
" of the task the user wants automated."
|
||||
),
|
||||
input_model=AgentDraftRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/draft",
|
||||
),
|
||||
McpCapability(
|
||||
id="agent-revise",
|
||||
description=(
|
||||
"Revise an existing draft agent specification based on user feedback or constraint changes."
|
||||
),
|
||||
input_model=AgentRevisionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/revise",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> AgentDraftWorkflowResponse:
|
||||
"""Entry point for the orchestrator delegate — adapts the orchestrator's
|
||||
request shape into an :class:`AgentDraftRequest` and runs the standard
|
||||
|
||||
@@ -1,160 +1,46 @@
|
||||
"""
|
||||
Curated registry of agent capabilities the MCP server (Java side) is allowed to publish.
|
||||
"""Serialize the MCP capabilities manifest the Java MCP server pulls at boot.
|
||||
|
||||
Internal sub-agents (currently only ``ExecutionPlanningAgent`` - it lives behind the orchestrator
|
||||
and has no end-user-facing API surface) are intentionally absent. The handoff spec calls for
|
||||
"user-facing" capabilities only; revisit this list when adding a new agent and ask whether MCP
|
||||
clients should be able to invoke it directly.
|
||||
The manifest is *derived* from the agent registry: every agent declares its
|
||||
exposed capabilities in ``describe()`` (see ``stirling.agents._registry``), and
|
||||
this module flattens the ``mcp`` rows of the startup descriptor list into the
|
||||
wire shape Java consumes. There is no separately maintained capability list to
|
||||
keep in sync — adding an MCP capability means adding an ``McpCapability`` to the
|
||||
owning agent's descriptor.
|
||||
|
||||
The Java side pulls ``/api/v1/agents/capabilities`` once at boot and again every few minutes; the
|
||||
manifest is the authoritative source for the ``stirling_ai`` MCP tool's operation enum.
|
||||
Curation note: exposure is opt-in. An agent is published to MCP only if its
|
||||
descriptor carries one or more ``McpCapability`` rows; registering an agent with
|
||||
the orchestrator does not auto-expose it over the (OAuth-scoped) MCP surface.
|
||||
|
||||
The Java side pulls ``/api/v1/agents/capabilities`` once at boot and again every
|
||||
few minutes; the manifest is the authoritative source for the ``stirling_ai`` MCP
|
||||
tool's operation enum.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from stirling.contracts import (
|
||||
AgentDraftRequest,
|
||||
AgentExecutionRequest,
|
||||
AgentRevisionRequest,
|
||||
Evidence,
|
||||
FolioManifest,
|
||||
PdfCommentRequest,
|
||||
PdfEditRequest,
|
||||
PdfQuestionRequest,
|
||||
)
|
||||
from stirling.agents import AgentDescriptor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentCapability:
|
||||
"""One row in the curated manifest.
|
||||
def manifest_payload(descriptors: Iterable[AgentDescriptor]) -> dict[str, Any]:
|
||||
"""Flatten the ``mcp`` rows of the descriptor list to the wire shape.
|
||||
|
||||
Attributes:
|
||||
id: stable capability identifier (used as the operation enum value in
|
||||
``stirling_ai``). Avoid renaming - clients persist these.
|
||||
description: one-line human-friendly summary shown inside MCP tool descriptions.
|
||||
input_model: Pydantic class whose JSON Schema becomes the capability's
|
||||
``input_schema``. Auto-derived; do not hand-write schemas.
|
||||
mode: ``"sync"`` if the capability returns content inline, ``"async"`` if it returns a
|
||||
plan that Java executes via the job pipeline.
|
||||
required_scope: coarse OAuth scope. ``mcp.tools.read`` for pure-read capabilities
|
||||
(Q&A, audits) and ``mcp.tools.write`` for anything that yields a plan / file.
|
||||
route: HTTP path Java POSTs to when invoking this capability. When a capability does
|
||||
not have a stable per-agent route yet, use the generic invoke fallback at
|
||||
``/api/v1/agents/invoke/{id}``.
|
||||
"""
|
||||
|
||||
id: str
|
||||
description: str
|
||||
input_model: type[BaseModel]
|
||||
mode: str
|
||||
required_scope: str
|
||||
route: str
|
||||
|
||||
|
||||
EXPOSED_CAPABILITIES: list[AgentCapability] = [
|
||||
AgentCapability(
|
||||
id="pdf-question-answer",
|
||||
description="Answer a natural-language question about a PDF document.",
|
||||
input_model=PdfQuestionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-question",
|
||||
),
|
||||
AgentCapability(
|
||||
id="pdf-edit-plan",
|
||||
description=(
|
||||
"Produce an edit plan (a structured sequence of PDF operations) from a"
|
||||
" natural-language edit request. The plan is executed by Java through the job"
|
||||
" pipeline; this capability does not modify files itself."
|
||||
),
|
||||
input_model=PdfEditRequest,
|
||||
mode="async",
|
||||
required_scope="mcp.tools.write",
|
||||
route="/api/v1/pdf-edit",
|
||||
),
|
||||
AgentCapability(
|
||||
id="agent-draft",
|
||||
description=(
|
||||
"Draft a structured agent specification from a free-text description of the task the user wants automated."
|
||||
),
|
||||
input_model=AgentDraftRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/draft",
|
||||
),
|
||||
AgentCapability(
|
||||
id="agent-revise",
|
||||
description=("Revise an existing draft agent specification based on user feedback or constraint changes."),
|
||||
input_model=AgentRevisionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/revise",
|
||||
),
|
||||
AgentCapability(
|
||||
id="math-audit-examine",
|
||||
description=(
|
||||
"Examine a folio manifest of financial / numeric documents and surface the"
|
||||
" evidence that needs to be checked for arithmetic consistency."
|
||||
),
|
||||
input_model=FolioManifest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/examine",
|
||||
),
|
||||
AgentCapability(
|
||||
id="math-audit-deliberate",
|
||||
description=(
|
||||
"Render a deliberated verdict on a single piece of evidence the examine step"
|
||||
" surfaced (does the arithmetic check out, with what caveats)."
|
||||
),
|
||||
input_model=Evidence,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/deliberate",
|
||||
),
|
||||
AgentCapability(
|
||||
id="pdf-comment-generate",
|
||||
description="Generate inline review comments for a PDF document.",
|
||||
input_model=PdfCommentRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-comment/generate",
|
||||
),
|
||||
AgentCapability(
|
||||
id="agent-next-action",
|
||||
description=(
|
||||
"Decide the next execution step for an in-progress agent workflow. Returns a"
|
||||
" ToolCall, Completed, or CannotContinue action."
|
||||
),
|
||||
input_model=AgentExecutionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/agents/next-action",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def manifest_payload() -> dict[str, Any]:
|
||||
"""Serialize the curated registry to the wire shape consumed by Java.
|
||||
|
||||
Schema is derived from ``input_model.model_json_schema()`` so we never hand-write JSON
|
||||
Schema - the Pydantic model is the single source of truth.
|
||||
Schema is derived from ``input_model.model_json_schema()`` so we never
|
||||
hand-write JSON Schema - the Pydantic model is the single source of truth.
|
||||
"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for cap in EXPOSED_CAPABILITIES:
|
||||
items.append(
|
||||
{
|
||||
"id": cap.id,
|
||||
"description": cap.description,
|
||||
"input_schema": cap.input_model.model_json_schema(),
|
||||
"mode": cap.mode,
|
||||
"required_scope": cap.required_scope,
|
||||
"route": cap.route,
|
||||
}
|
||||
)
|
||||
for descriptor in descriptors:
|
||||
for cap in descriptor.mcp:
|
||||
items.append(
|
||||
{
|
||||
"id": cap.id,
|
||||
"description": cap.description,
|
||||
"input_schema": cap.input_model.model_json_schema(),
|
||||
"mode": cap.mode,
|
||||
"required_scope": cap.required_scope,
|
||||
"route": cap.route,
|
||||
}
|
||||
)
|
||||
return {"version": 1, "capabilities": items}
|
||||
|
||||
@@ -12,9 +12,12 @@ from pydantic_ai.models.instrumented import InstrumentationSettings
|
||||
from stirling.agents import (
|
||||
ExecutionPlanningAgent,
|
||||
OrchestratorAgent,
|
||||
PdfCreateAgent,
|
||||
PdfEditAgent,
|
||||
PdfQuestionAgent,
|
||||
PdfReviewAgent,
|
||||
UserSpecAgent,
|
||||
build_descriptors,
|
||||
)
|
||||
from stirling.agents.ledger import MathAuditorAgent
|
||||
from stirling.agents.pdf_comment import PdfCommentAgent
|
||||
@@ -88,13 +91,28 @@ async def lifespan(fast_api: FastAPI):
|
||||
runtime = build_runtime(settings)
|
||||
fast_api.state.settings = settings
|
||||
fast_api.state.runtime = runtime
|
||||
fast_api.state.orchestrator_agent = OrchestratorAgent(runtime)
|
||||
fast_api.state.pdf_edit_agent = PdfEditAgent(runtime)
|
||||
fast_api.state.pdf_question_agent = PdfQuestionAgent(runtime)
|
||||
fast_api.state.pdf_review_agent = PdfReviewAgent(runtime)
|
||||
fast_api.state.pdf_create_agent = PdfCreateAgent(runtime)
|
||||
fast_api.state.user_spec_agent = UserSpecAgent(runtime)
|
||||
fast_api.state.execution_planning_agent = ExecutionPlanningAgent(runtime)
|
||||
fast_api.state.math_auditor_agent = MathAuditorAgent(runtime)
|
||||
fast_api.state.pdf_comment_agent = PdfCommentAgent(runtime)
|
||||
# One descriptor list drives both orchestrator routing and the MCP manifest.
|
||||
fast_api.state.agent_descriptors = build_descriptors(
|
||||
[
|
||||
fast_api.state.pdf_edit_agent,
|
||||
fast_api.state.pdf_question_agent,
|
||||
fast_api.state.user_spec_agent,
|
||||
fast_api.state.pdf_review_agent,
|
||||
fast_api.state.pdf_create_agent,
|
||||
fast_api.state.pdf_comment_agent,
|
||||
fast_api.state.math_auditor_agent,
|
||||
fast_api.state.execution_planning_agent,
|
||||
]
|
||||
)
|
||||
fast_api.state.orchestrator_agent = OrchestratorAgent(runtime, fast_api.state.agent_descriptors)
|
||||
tracer_provider = setup_posthog_tracking(settings)
|
||||
if tracer_provider:
|
||||
Agent.instrument_all(InstrumentationSettings(tracer_provider=tracer_provider))
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from stirling.api.agent_capabilities import manifest_payload
|
||||
|
||||
@@ -12,11 +12,11 @@ router = APIRouter(prefix="/api/v1/agents", tags=["agents"])
|
||||
|
||||
|
||||
@router.get("/capabilities")
|
||||
def get_capabilities() -> dict[str, Any]:
|
||||
"""Return the curated agent capabilities manifest.
|
||||
def get_capabilities(request: Request) -> dict[str, Any]:
|
||||
"""Return the agent capabilities manifest, derived from the startup registry.
|
||||
|
||||
Gated by ``EngineSharedSecretMiddleware`` when the ``STIRLING_ENGINE_SHARED_SECRET`` env var
|
||||
is configured. In dev/local mode (no secret set), the endpoint is open - the engine binds to
|
||||
localhost only by default, so this is acceptable while iterating.
|
||||
"""
|
||||
return manifest_payload()
|
||||
return manifest_payload(request.app.state.agent_descriptors)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""
|
||||
Orchestrator ``delegate_pdf_review`` contract test.
|
||||
PDF-review delegate contract test.
|
||||
|
||||
The real orchestrator delegates PDF-review requests via a pydantic-ai tool
|
||||
output. Exercising the full ``agent.run(...)`` call would hit the LLM and
|
||||
requires building a real ``RunContext`` — so instead this test invokes
|
||||
``delegate_pdf_review`` directly with a minimal ``deps`` stand-in. That's
|
||||
enough to verify the wire contract the orchestrator produces:
|
||||
The orchestrator routes PDF-review requests to ``PdfReviewAgent.orchestrate``
|
||||
(the orchestrator merely selects the delegate; the review logic lives on the
|
||||
agent). Exercising the agent directly avoids the LLM routing call and verifies
|
||||
the wire contract the delegate produces for a plain prose-review request:
|
||||
|
||||
* it returns an ``EditPlanResponse``;
|
||||
* with exactly one step;
|
||||
@@ -16,13 +15,11 @@ enough to verify the wire contract the orchestrator produces:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from stirling.agents import OrchestratorAgent
|
||||
from stirling.agents import PdfReviewAgent
|
||||
from stirling.contracts import AiFile, OrchestratorRequest
|
||||
from stirling.contracts.pdf_edit import EditPlanResponse
|
||||
from stirling.models import FileId
|
||||
@@ -30,27 +27,28 @@ from stirling.models.agent_tool_models import AgentToolId, PdfCommentAgentParams
|
||||
from stirling.services.runtime import AppRuntime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _FakeDeps:
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_review_wires_prompt_to_tool_step(runtime: AppRuntime) -> None:
|
||||
orchestrator = OrchestratorAgent(runtime)
|
||||
async def test_pdf_review_wires_prompt_to_tool_step(runtime: AppRuntime) -> None:
|
||||
review_agent = PdfReviewAgent(runtime)
|
||||
request = OrchestratorRequest(
|
||||
user_message="please add review comments flagging ambiguous dates",
|
||||
files=[AiFile(id=FileId("contract-id"), name="contract.pdf")],
|
||||
)
|
||||
ctx = SimpleNamespace(deps=_FakeDeps(request=request))
|
||||
|
||||
# PdfReviewAgent now classifies math intent locally via a tiny LLM. Stub it
|
||||
# to false so this test stays focused on the prose-review wire contract.
|
||||
with patch(
|
||||
"stirling.agents.pdf_review.MathIntentClassifier.classify",
|
||||
new=AsyncMock(return_value=False),
|
||||
# PdfReviewAgent classifies math and contradiction intent locally via tiny
|
||||
# LLMs. Stub both to false so this test stays focused on the prose-review
|
||||
# wire contract.
|
||||
with (
|
||||
patch(
|
||||
"stirling.agents.pdf_review.MathIntentClassifier.classify",
|
||||
new=AsyncMock(return_value=False),
|
||||
),
|
||||
patch(
|
||||
"stirling.agents.pdf_review.ContradictionIntentClassifier.classify",
|
||||
new=AsyncMock(return_value=False),
|
||||
),
|
||||
):
|
||||
response = await orchestrator.delegate_pdf_review(ctx) # type: ignore[arg-type]
|
||||
response = await review_agent.orchestrate(request)
|
||||
|
||||
assert isinstance(response, EditPlanResponse)
|
||||
assert len(response.steps) == 1
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Behavioural lock: a scripted top-level tool call reaches the right delegate.
|
||||
|
||||
No real LLM — a :class:`FunctionModel` scripts the exact tool call the orchestrator
|
||||
would have received, and we assert which delegate handled it. Built on the real
|
||||
descriptor list (via ``build_descriptors``) with each agent's ``orchestrate``
|
||||
swapped for a recording spy, so the test stays honest to whatever agents are
|
||||
actually registered.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
from pydantic_ai.messages import ModelMessage, ModelResponse, ToolCallPart
|
||||
from pydantic_ai.models.function import AgentInfo, FunctionModel
|
||||
|
||||
from stirling.agents import OrchestratorAgent, build_descriptors
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.contracts import (
|
||||
ConvertMarkdownResponse,
|
||||
EditCannotDoResponse,
|
||||
EditPlanResponse,
|
||||
OrchestratorRequest,
|
||||
OrchestratorResponse,
|
||||
PdfQuestionNotFoundResponse,
|
||||
SupportedCapability,
|
||||
)
|
||||
from stirling.services.runtime import AppRuntime
|
||||
|
||||
_REACHED: list[SupportedCapability] = []
|
||||
|
||||
|
||||
class _SpyAgent(RegisterableAgent):
|
||||
"""Stand-in agent that reproduces a real delegate's tool surface but records
|
||||
the reach and returns a fixed sentinel instead of doing work."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
capability: SupportedCapability,
|
||||
tool_name: str,
|
||||
response: OrchestratorResponse,
|
||||
) -> None:
|
||||
self._capability = capability
|
||||
self._tool_name = tool_name
|
||||
self._response = response
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=self._capability,
|
||||
tool_name=self._tool_name,
|
||||
tool_description=f"spy for {self._tool_name}",
|
||||
orchestrate=self._orchestrate,
|
||||
),
|
||||
)
|
||||
|
||||
async def _orchestrate(self, _request: OrchestratorRequest) -> OrchestratorResponse:
|
||||
_REACHED.append(self._capability)
|
||||
return self._response
|
||||
|
||||
|
||||
def _spies() -> list[RegisterableAgent]:
|
||||
return [
|
||||
_SpyAgent(SupportedCapability.PDF_EDIT, "delegate_pdf_edit", EditCannotDoResponse(reason="spy")),
|
||||
_SpyAgent(
|
||||
SupportedCapability.PDF_QUESTION,
|
||||
"delegate_pdf_question",
|
||||
PdfQuestionNotFoundResponse(reason="spy"),
|
||||
),
|
||||
_SpyAgent(SupportedCapability.PDF_REVIEW, "delegate_pdf_review", EditPlanResponse(summary="", steps=[])),
|
||||
_SpyAgent(SupportedCapability.PDF_CREATE, "delegate_pdf_create", EditPlanResponse(summary="", steps=[])),
|
||||
]
|
||||
|
||||
|
||||
def _script(tool_name: str) -> Callable[[list[ModelMessage], AgentInfo], ModelResponse]:
|
||||
def call(_messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
|
||||
return ModelResponse(parts=[ToolCallPart(tool_name=tool_name, args={})])
|
||||
|
||||
return call
|
||||
|
||||
|
||||
async def _route(runtime: AppRuntime, tool_name: str) -> OrchestratorResponse:
|
||||
_REACHED.clear()
|
||||
scripted = replace(runtime, fast_model=FunctionModel(_script(tool_name)))
|
||||
orchestrator = OrchestratorAgent(scripted, build_descriptors(_spies()))
|
||||
return await orchestrator.handle(OrchestratorRequest(user_message="x"))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_edit_reaches_edit_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_edit")
|
||||
assert _REACHED == [SupportedCapability.PDF_EDIT]
|
||||
assert isinstance(response, EditCannotDoResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_question_reaches_question_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_question")
|
||||
assert _REACHED == [SupportedCapability.PDF_QUESTION]
|
||||
assert isinstance(response, PdfQuestionNotFoundResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_review_reaches_review_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_review")
|
||||
assert _REACHED == [SupportedCapability.PDF_REVIEW]
|
||||
assert isinstance(response, EditPlanResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_create_reaches_create_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_create")
|
||||
assert _REACHED == [SupportedCapability.PDF_CREATE]
|
||||
assert isinstance(response, EditPlanResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_ingest_returns_convert_markdown(runtime: AppRuntime) -> None:
|
||||
# pdf_ingest is a canned inline orchestrator tool (no agent, never resumed) —
|
||||
# no reach recorded, just a deterministic convert response.
|
||||
response = await _route(runtime, "delegate_pdf_ingest")
|
||||
assert _REACHED == []
|
||||
assert isinstance(response, ConvertMarkdownResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resume_dispatches_to_matching_delegate(runtime: AppRuntime) -> None:
|
||||
_REACHED.clear()
|
||||
orchestrator = OrchestratorAgent(runtime, build_descriptors(_spies()))
|
||||
await orchestrator.handle(OrchestratorRequest(user_message="x", resume_with=SupportedCapability.PDF_REVIEW))
|
||||
assert _REACHED == [SupportedCapability.PDF_REVIEW]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resume_with_unroutable_capability_raises(runtime: AppRuntime) -> None:
|
||||
# MATH_AUDITOR_AGENT is MCP-only — not an orchestrator delegate, so it has no
|
||||
# resumable route and resuming into it must raise.
|
||||
orchestrator = OrchestratorAgent(runtime, build_descriptors(_spies()))
|
||||
with pytest.raises(ValueError, match="Cannot resume"):
|
||||
await orchestrator.handle(
|
||||
OrchestratorRequest(user_message="x", resume_with=SupportedCapability.MATH_AUDITOR_AGENT)
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Lock the MCP capabilities manifest wire shape.
|
||||
|
||||
Exercises the real ``GET /api/v1/agents/capabilities`` endpoint (so it covers the
|
||||
actual startup wiring of ``app.state.agent_descriptors``) and pins every
|
||||
capability's id, metadata, and Pydantic-derived input schema. The manifest is
|
||||
built by flattening each agent's ``describe()`` rows; this suite is the guard
|
||||
that the derived manifest never drifts from the published contract.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import build_app_settings
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import BaseModel
|
||||
|
||||
from stirling.api import app
|
||||
from stirling.config import load_settings
|
||||
from stirling.contracts import (
|
||||
AgentDraftRequest,
|
||||
AgentExecutionRequest,
|
||||
AgentRevisionRequest,
|
||||
Evidence,
|
||||
FolioManifest,
|
||||
PdfCommentRequest,
|
||||
PdfEditRequest,
|
||||
PdfQuestionRequest,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest() -> Iterator[dict[str, Any]]:
|
||||
# Force test settings for the lifespan (other suites pop this override, so we
|
||||
# can't rely on a module-level set), then enter the client as a context manager
|
||||
# so the lifespan runs and populates ``app.state.agent_descriptors`` — the
|
||||
# manifest is built from that real startup registration, not a duplicated list.
|
||||
app.dependency_overrides[load_settings] = build_app_settings
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
response = client.get("/api/v1/agents/capabilities")
|
||||
finally:
|
||||
app.dependency_overrides.pop(load_settings, None)
|
||||
assert response.status_code == 200
|
||||
yield response.json()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Expected:
|
||||
description: str
|
||||
mode: str
|
||||
required_scope: str
|
||||
route: str
|
||||
input_model: type[BaseModel]
|
||||
|
||||
|
||||
# Expected per-capability metadata, keyed by id. Order-independent on purpose —
|
||||
# Java consumes the manifest as a keyed operation registry, not a sequence.
|
||||
_EXPECTED: dict[str, _Expected] = {
|
||||
"pdf-question-answer": _Expected(
|
||||
description="Answer a natural-language question about a PDF document.",
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-question",
|
||||
input_model=PdfQuestionRequest,
|
||||
),
|
||||
"pdf-edit-plan": _Expected(
|
||||
description=(
|
||||
"Produce an edit plan (a structured sequence of PDF operations) from a"
|
||||
" natural-language edit request. The plan is executed by Java through the job"
|
||||
" pipeline; this capability does not modify files itself."
|
||||
),
|
||||
mode="async",
|
||||
required_scope="mcp.tools.write",
|
||||
route="/api/v1/pdf-edit",
|
||||
input_model=PdfEditRequest,
|
||||
),
|
||||
"agent-draft": _Expected(
|
||||
description=(
|
||||
"Draft a structured agent specification from a free-text description of the task the user wants automated."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/draft",
|
||||
input_model=AgentDraftRequest,
|
||||
),
|
||||
"agent-revise": _Expected(
|
||||
description="Revise an existing draft agent specification based on user feedback or constraint changes.",
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/revise",
|
||||
input_model=AgentRevisionRequest,
|
||||
),
|
||||
"math-audit-examine": _Expected(
|
||||
description=(
|
||||
"Examine a folio manifest of financial / numeric documents and surface the"
|
||||
" evidence that needs to be checked for arithmetic consistency."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/examine",
|
||||
input_model=FolioManifest,
|
||||
),
|
||||
"math-audit-deliberate": _Expected(
|
||||
description=(
|
||||
"Render a deliberated verdict on a single piece of evidence the examine step"
|
||||
" surfaced (does the arithmetic check out, with what caveats)."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/deliberate",
|
||||
input_model=Evidence,
|
||||
),
|
||||
"pdf-comment-generate": _Expected(
|
||||
description="Generate inline review comments for a PDF document.",
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-comment/generate",
|
||||
input_model=PdfCommentRequest,
|
||||
),
|
||||
"agent-next-action": _Expected(
|
||||
description=(
|
||||
"Decide the next execution step for an in-progress agent workflow. Returns a"
|
||||
" ToolCall, Completed, or CannotContinue action."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/agents/next-action",
|
||||
input_model=AgentExecutionRequest,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def test_manifest_version(manifest: dict[str, Any]) -> None:
|
||||
assert manifest["version"] == 1
|
||||
|
||||
|
||||
def test_manifest_exposes_exactly_the_expected_capabilities(manifest: dict[str, Any]) -> None:
|
||||
ids = {c["id"] for c in manifest["capabilities"]}
|
||||
assert ids == set(_EXPECTED)
|
||||
|
||||
|
||||
def test_manifest_capability_metadata_and_schema(manifest: dict[str, Any]) -> None:
|
||||
by_id = {c["id"]: c for c in manifest["capabilities"]}
|
||||
for cap_id, expected in _EXPECTED.items():
|
||||
entry = by_id[cap_id]
|
||||
assert entry["description"] == expected.description, cap_id
|
||||
assert entry["mode"] == expected.mode, cap_id
|
||||
assert entry["required_scope"] == expected.required_scope, cap_id
|
||||
assert entry["route"] == expected.route, cap_id
|
||||
assert entry["input_schema"] == expected.input_model.model_json_schema(), cap_id
|
||||
@@ -112,14 +112,12 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({
|
||||
// falling back to the backend version
|
||||
const currentVersion = appVersion ?? config?.appVersion ?? null;
|
||||
|
||||
// Check for updates on mount — skipped when the update UI is hidden (SaaS
|
||||
// build, managed-disabled desktop) so no external update call ever fires.
|
||||
// Check for updates on mount
|
||||
useEffect(() => {
|
||||
if (hideUpdateSection) return;
|
||||
if (currentVersion) {
|
||||
checkForUpdate();
|
||||
}
|
||||
}, [currentVersion, config?.machineType, hideUpdateSection]);
|
||||
}, [currentVersion, config?.machineType]);
|
||||
|
||||
const checkForUpdate = async () => {
|
||||
if (!currentVersion) return;
|
||||
|
||||
+1
-6
@@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
|
||||
import CoreGeneralSection from "@core/components/shared/config/configSections/GeneralSection";
|
||||
import { DefaultAppSettings } from "@app/components/shared/config/configSections/DefaultAppSettings";
|
||||
import { useDesktopInstall } from "@app/hooks/useDesktopInstall";
|
||||
import { useSaaSMode } from "@app/hooks/useSaaSMode";
|
||||
import {
|
||||
desktopUpdateService,
|
||||
type UpdateMode,
|
||||
@@ -23,9 +22,6 @@ import {
|
||||
const GeneralSection: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const install = useDesktopInstall();
|
||||
// In SaaS connection mode the cloud owns app versioning — hide the update
|
||||
// section (which also stops the core auto-check from firing).
|
||||
const isSaaSMode = useSaaSMode();
|
||||
const [updateModeInfo, setUpdateModeInfo] = useState<UpdateModeInfo>({
|
||||
mode: "prompt",
|
||||
locked: false,
|
||||
@@ -97,8 +93,7 @@ const GeneralSection: React.FC = () => {
|
||||
)}
|
||||
<CoreGeneralSection
|
||||
hideUpdateSection={
|
||||
isSaaSMode ||
|
||||
(updateModeInfo.mode === "disabled" && updateModeInfo.locked)
|
||||
updateModeInfo.mode === "disabled" && updateModeInfo.locked
|
||||
}
|
||||
desktopInstall={{
|
||||
state: install.state,
|
||||
|
||||
@@ -9,7 +9,6 @@ const getVersionMock = vi.fn();
|
||||
const getUpdateModeMock = vi.fn();
|
||||
const canInstallUpdatesMock = vi.fn();
|
||||
const getUpdateSummaryMock = vi.fn();
|
||||
const getCurrentModeMock = vi.fn();
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
invoke: (cmd: string, args?: unknown) => invokeMock(cmd, args),
|
||||
@@ -37,12 +36,6 @@ vi.mock("@app/services/desktopUpdateService", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@app/services/connectionModeService", () => ({
|
||||
connectionModeService: {
|
||||
getCurrentMode: () => getCurrentModeMock(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { useDesktopUpdatePopup } from "@app/hooks/useDesktopUpdatePopup";
|
||||
|
||||
/** Flush pending microtasks so awaited promises settle. */
|
||||
@@ -81,11 +74,8 @@ describe("useDesktopUpdatePopup — auto mode", () => {
|
||||
getUpdateModeMock.mockReset();
|
||||
canInstallUpdatesMock.mockReset();
|
||||
getUpdateSummaryMock.mockReset();
|
||||
getCurrentModeMock.mockReset();
|
||||
|
||||
// Defaults: local (non-SaaS) connection, auto mode, update available,
|
||||
// install permitted.
|
||||
getCurrentModeMock.mockResolvedValue("local");
|
||||
// Defaults: auto mode, update available, install permitted.
|
||||
getUpdateModeMock.mockResolvedValue("auto");
|
||||
getVersionMock.mockResolvedValue("1.0.0");
|
||||
getUpdateSummaryMock.mockResolvedValue({ latest_version: "2.0.0" });
|
||||
@@ -199,18 +189,4 @@ describe("useDesktopUpdatePopup — auto mode", () => {
|
||||
expect(invocations).toContain("download_and_install_update");
|
||||
expect(invocations).toContain("restart_app");
|
||||
});
|
||||
|
||||
it("skips the update check entirely in SaaS connection mode", async () => {
|
||||
// In SaaS mode the cloud owns versioning — the self-hosted update check
|
||||
// must never run: no mode lookup, no external summary fetch, no install.
|
||||
getCurrentModeMock.mockResolvedValue("saas");
|
||||
|
||||
await runStartup();
|
||||
|
||||
expect(getUpdateModeMock).not.toHaveBeenCalled();
|
||||
expect(getUpdateSummaryMock).not.toHaveBeenCalled();
|
||||
const invocations = invokeMock.mock.calls.map((c) => c[0]);
|
||||
expect(invocations).not.toContain("download_and_install_update");
|
||||
expect(invocations).not.toContain("restart_app");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
desktopUpdateService,
|
||||
type CanInstallResult,
|
||||
} from "@app/services/desktopUpdateService";
|
||||
import { connectionModeService } from "@app/services/connectionModeService";
|
||||
|
||||
const SNOOZE_KEY = "stirling-pdf-updater:snoozedUntil";
|
||||
const STARTUP_DELAY_MS = 15_000;
|
||||
@@ -73,10 +72,6 @@ export function useDesktopUpdatePopup() {
|
||||
hasChecked.current = true;
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
// In SaaS connection mode the cloud owns app versioning — the self-hosted
|
||||
// update check + popup must never run (no external call, no modal).
|
||||
if ((await connectionModeService.getCurrentMode()) === "saas") return;
|
||||
|
||||
let mode: Awaited<ReturnType<typeof desktopUpdateService.getUpdateMode>> =
|
||||
"prompt";
|
||||
try {
|
||||
|
||||
@@ -212,12 +212,8 @@ export function usePolicyAutoRun(): void {
|
||||
s.configured &&
|
||||
s.status === "active" &&
|
||||
s.backendId &&
|
||||
// Only enforce in the editor when the policy includes "editor" as a source.
|
||||
// runOn is an editor-specific parameter: "upload" fires here, "export" fires
|
||||
// at export time via policyExport. Non-editor sources have their own triggers.
|
||||
(!s.sources ||
|
||||
s.sources.length === 0 ||
|
||||
s.sources.includes("editor")) &&
|
||||
// Only auto-run on upload when the policy is set to run on upload
|
||||
// (export-triggered policies enforce at export time instead).
|
||||
(s.runOn ?? "upload") === "upload",
|
||||
);
|
||||
for (const [categoryId, s] of active) {
|
||||
@@ -279,7 +275,6 @@ export function usePolicyAutoRun(): void {
|
||||
// input file it ran on (needs that input's stub, still in the workspace).
|
||||
const outputMode = policies[run.categoryId]?.outputMode ?? "new_version";
|
||||
const outputName = policies[run.categoryId]?.outputName ?? "";
|
||||
const outputNamePosition = policies[run.categoryId]?.outputNamePosition;
|
||||
const parentStub = fileStubs.find((s) => (s.id as string) === run.fileId);
|
||||
void importOutputs(run, {
|
||||
addFiles,
|
||||
@@ -287,7 +282,6 @@ export function usePolicyAutoRun(): void {
|
||||
bumpRevision,
|
||||
outputMode,
|
||||
outputName,
|
||||
outputNamePosition,
|
||||
parentStub,
|
||||
}).finally(() => importing.current.delete(run.runId));
|
||||
}
|
||||
@@ -320,11 +314,9 @@ interface ImportContext {
|
||||
bumpRevision: () => void;
|
||||
/** "new_file" adds the output as a separate file; "new_version" versions the input. */
|
||||
outputMode: "new_file" | "new_version";
|
||||
/** Rename rule. Empty → keep the input's filename. */
|
||||
/** Rename rule. Empty → keep the input's filename; set → use the policy's
|
||||
* renamed output (applied server-side per the name-position setting). */
|
||||
outputName: string;
|
||||
/** Where the rename is applied: before ("prefix") or after ("suffix") the
|
||||
* base filename. Defaults to "suffix" when absent. */
|
||||
outputNamePosition?: "prefix" | "suffix" | "auto-number";
|
||||
/** The input file's stub — required to version it; absent if it's been removed. */
|
||||
parentStub: StirlingFileStub | undefined;
|
||||
}
|
||||
@@ -335,20 +327,6 @@ interface ImportContext {
|
||||
* don't, adopt it so the poll/import effects pick it up. Server-excluded ad-hoc runs and runs we
|
||||
* can't map to a configured category are skipped.
|
||||
*/
|
||||
function applyOutputName(
|
||||
inputFileName: string,
|
||||
outputName: string,
|
||||
position: "prefix" | "suffix" | "auto-number",
|
||||
): string {
|
||||
const dot = inputFileName.lastIndexOf(".");
|
||||
const base = dot > 0 ? inputFileName.slice(0, dot) : inputFileName;
|
||||
const ext = dot > 0 ? inputFileName.slice(dot) : "";
|
||||
if (position === "suffix") return `${base}_${outputName}${ext}`;
|
||||
if (position === "prefix") return `${outputName}_${base}${ext}`;
|
||||
// auto-number requires dedup state not available here — fall back to suffix.
|
||||
return `${base}_${outputName}${ext}`;
|
||||
}
|
||||
|
||||
async function reconcileServerRuns(
|
||||
policies: PoliciesByCategory,
|
||||
): Promise<void> {
|
||||
@@ -428,11 +406,7 @@ async function importOutputs(
|
||||
// rule the backend's auto-suffixed name (e.g. "_watermarked_sanitized") would
|
||||
// otherwise rename every output.
|
||||
const targetName = ctx.outputName
|
||||
? applyOutputName(
|
||||
run.fileName,
|
||||
ctx.outputName,
|
||||
ctx.outputNamePosition ?? "suffix",
|
||||
)
|
||||
? undefined // use the run's per-output (renamed) name below
|
||||
: run.fileName;
|
||||
const settled = await Promise.allSettled(
|
||||
pending.map(async (out) => {
|
||||
|
||||
@@ -134,7 +134,6 @@ export function usePolicies() {
|
||||
reviewerEmail: result.reviewerEmail,
|
||||
outputMode: result.folder.outputMode,
|
||||
outputName: result.folder.outputName,
|
||||
outputNamePosition: result.folder.outputNamePosition,
|
||||
runOn: result.folder.runOn,
|
||||
});
|
||||
},
|
||||
@@ -171,7 +170,6 @@ export function usePolicies() {
|
||||
reviewerEmail: result.reviewerEmail,
|
||||
outputMode: result.folder.outputMode,
|
||||
outputName: result.folder.outputName,
|
||||
outputNamePosition: result.folder.outputNamePosition,
|
||||
runOn: result.folder.runOn,
|
||||
});
|
||||
},
|
||||
@@ -236,7 +234,6 @@ export function usePolicies() {
|
||||
reviewerEmail: result.reviewerEmail,
|
||||
outputMode: result.folder.outputMode,
|
||||
outputName: result.folder.outputName,
|
||||
outputNamePosition: result.folder.outputNamePosition,
|
||||
runOn: result.folder.runOn,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -114,7 +114,6 @@ describe("Login", () => {
|
||||
displayName: null,
|
||||
isAnonymous: false,
|
||||
isAdmin: false,
|
||||
portalAccess: false,
|
||||
role: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
@@ -170,7 +169,6 @@ describe("Login", () => {
|
||||
displayName: mockSession.user.username,
|
||||
isAnonymous: false,
|
||||
isAdmin: false,
|
||||
portalAccess: false,
|
||||
role: mockSession.user.role,
|
||||
loading: false,
|
||||
error: null,
|
||||
@@ -198,7 +196,6 @@ describe("Login", () => {
|
||||
displayName: null,
|
||||
isAnonymous: false,
|
||||
isAdmin: false,
|
||||
portalAccess: false,
|
||||
role: null,
|
||||
loading: true,
|
||||
error: null,
|
||||
|
||||
@@ -53,7 +53,6 @@ export function decodedToState(
|
||||
fieldValues: decoded.fieldValues,
|
||||
outputMode: decoded.folder.outputMode,
|
||||
outputName: decoded.folder.outputName,
|
||||
outputNamePosition: decoded.folder.outputNamePosition,
|
||||
runOn: decoded.folder.runOn,
|
||||
folderId: localFolderId,
|
||||
backendId: decoded.id,
|
||||
|
||||
@@ -70,7 +70,6 @@ function activeExportPolicies(): ExportPolicy[] {
|
||||
s.configured &&
|
||||
s.status === "active" &&
|
||||
s.backendId &&
|
||||
(s.sources.length === 0 || s.sources.includes("editor")) &&
|
||||
s.runOn === "export",
|
||||
)
|
||||
.map(([id, s]) => ({
|
||||
|
||||
@@ -131,9 +131,6 @@ export interface PolicyState {
|
||||
* input's filename; when set, it's applied as a prefix/suffix per the policy's
|
||||
* name-position setting. */
|
||||
outputName?: string;
|
||||
/** Whether the rename rule is applied before ("prefix") or after ("suffix")
|
||||
* the base filename, or as an auto-incrementing number. */
|
||||
outputNamePosition?: "prefix" | "suffix" | "auto-number";
|
||||
/** When the policy runs: on "upload" or before "export". Defaults to "upload". */
|
||||
runOn?: "upload" | "export";
|
||||
/**
|
||||
|
||||
@@ -379,9 +379,6 @@ label = "Read mode"
|
||||
consume = "Consume: process each file once"
|
||||
snapshot = "Snapshot: re-read the folder every run"
|
||||
|
||||
[sources.types.editor]
|
||||
label = "Editor"
|
||||
|
||||
[sources.types.unknown]
|
||||
label = "Source"
|
||||
|
||||
@@ -699,11 +696,6 @@ description = "{{file}} is signed and ready to transfer. It activates one instan
|
||||
title = "Policies"
|
||||
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."
|
||||
|
||||
[policies.offline]
|
||||
title = "Backend unavailable"
|
||||
description = "Your policies are saved and will appear once the connection is restored."
|
||||
retry = "Retry"
|
||||
|
||||
[policies.status]
|
||||
active = "Active"
|
||||
paused = "Paused"
|
||||
@@ -732,17 +724,15 @@ description = "Across active policies"
|
||||
[policies.card]
|
||||
comingSoon = "Coming soon"
|
||||
notSetUp = "Not set up"
|
||||
setUp = "Set up →"
|
||||
|
||||
[policies.detail]
|
||||
title = "{{category}} policy"
|
||||
meta = "Runs on {{event}} · output {{output}}"
|
||||
outputAsNewFile = "as a new file"
|
||||
outputAsNewVersion = "as a new version"
|
||||
enforces = "Enforces"
|
||||
sources = "Sources"
|
||||
onEveryUpload = "On every upload"
|
||||
onEveryExport = "On every export"
|
||||
showMore = "Show more"
|
||||
showLess = "Show less"
|
||||
retry = "Retry"
|
||||
enforceNote = "{{scope}} · originals stay untouched, the enforced version is saved alongside."
|
||||
recentActivity = "Recent activity"
|
||||
|
||||
[policies.detail.actions]
|
||||
@@ -756,6 +746,10 @@ editSettings = "Edit settings"
|
||||
title = "No activity yet"
|
||||
description = "Documents will appear here once this policy runs."
|
||||
|
||||
[policies.detail.scoped]
|
||||
title = "Scoped"
|
||||
description = "Limited to: {{types}}"
|
||||
|
||||
[policies.wizard.title]
|
||||
edit = "Edit {{category}} policy"
|
||||
setUp = "Set up {{category}} policy"
|
||||
@@ -784,9 +778,6 @@ heading = "Settings"
|
||||
|
||||
[policies.wizard.sources]
|
||||
heading = "Sources"
|
||||
loading = "Loading sources…"
|
||||
emptyTitle = "No sources available"
|
||||
emptyDescription = "Connect a source on the Sources page first, then attach it to a policy here."
|
||||
|
||||
[policies.wizard.docTypes]
|
||||
heading = "Document types"
|
||||
@@ -818,10 +809,9 @@ suffix = "Suffix"
|
||||
autoNumber = "Auto-number"
|
||||
placeholder = "Text to add (optional)"
|
||||
|
||||
[policies.wizard.output.retries]
|
||||
heading = "Retries"
|
||||
maxLabel = "Max retries"
|
||||
delayLabel = "Retry delay (min)"
|
||||
[policies.wizard.output.reviewerEmail]
|
||||
label = "Reviewer email"
|
||||
helper = "Low-confidence enforcements are routed here for review."
|
||||
|
||||
[users.summary]
|
||||
members = "Members"
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
* entitlement calls. It never enters the portal — the browser is the human
|
||||
* admin and uses the Supabase JWT for SaaS reads. Don't add it here.
|
||||
*/
|
||||
import { clearStoredToken, getStoredToken } from "@shared/auth";
|
||||
import { getStoredToken } from "@shared/auth";
|
||||
import { getSupabaseClient } from "@shared/auth/supabase/supabaseClient";
|
||||
import { ensureSaasSupabase } from "@portal/auth/saasSupabase";
|
||||
|
||||
@@ -156,12 +156,6 @@ async function localJson<T>(
|
||||
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
|
||||
signal: options.signal,
|
||||
});
|
||||
if (res.status === 401) {
|
||||
// Stale or invalid JWT — clear it so the auth provider re-initialises and
|
||||
// shows the login screen rather than leaving the user stuck with a banner.
|
||||
clearStoredToken();
|
||||
window.dispatchEvent(new CustomEvent("jwt-available"));
|
||||
}
|
||||
return unwrap<T>(res);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,173 +1,72 @@
|
||||
/**
|
||||
* Policies service layer.
|
||||
*
|
||||
* The portal calls the real Stirling policy API (`/api/v1/policies`). MSW
|
||||
* intercepts these calls in dev/Storybook; dropping MSW is enough to hit the
|
||||
* live backend — no call-site changes needed.
|
||||
*
|
||||
* `fetchPolicies()` assembles the decorated catalogue client-side from the
|
||||
* backend's flat `WirePolicy[]` + `PolicyRunView[]`, mirroring the same
|
||||
* approach the editor uses for its own catalogue view.
|
||||
*/
|
||||
|
||||
import { apiClient } from "@portal/api/http";
|
||||
import { fromWirePolicy, toWirePolicy } from "@shared/policies/codec";
|
||||
import { runsToActivity, runsToStats } from "@shared/policies/runs";
|
||||
import type { PolicyDecodedState, WirePolicy } from "@shared/policies/types";
|
||||
import {
|
||||
POLICY_CATEGORIES,
|
||||
POLICY_CONFIG,
|
||||
type CatalogueEntry,
|
||||
type DecoratedPolicy,
|
||||
type PoliciesResponse,
|
||||
type PoliciesSummary,
|
||||
type PolicySetupResult,
|
||||
type PolicyState,
|
||||
type PolicyStatus,
|
||||
} from "@portal/mocks/policies";
|
||||
import type { PolicyRunView } from "@shared/policies/types";
|
||||
import type { PoliciesResponse, Policy } from "@portal/mocks/policies";
|
||||
|
||||
/**
|
||||
* Policies service layer — the backend contract.
|
||||
*
|
||||
* Unlike every other portal surface (which use the mock `/v1/...` base), this
|
||||
* one calls the REAL Stirling policy API base `/api/v1/policies` so it is
|
||||
* genuinely plug-and-play: drop MSW and these exact calls hit the live backend
|
||||
* (PolicyController). The list response is the portal's catalogue shape; the
|
||||
* single-policy / create / delete / run calls match the backend records.
|
||||
*/
|
||||
|
||||
export type {
|
||||
CatalogueEntry,
|
||||
DecoratedPolicy,
|
||||
InputSpec,
|
||||
OutputSpec,
|
||||
PipelineStep,
|
||||
PoliciesResponse,
|
||||
PoliciesSummary,
|
||||
Policy,
|
||||
PolicyActivityItem,
|
||||
PolicyCategory,
|
||||
PolicyConfigDef,
|
||||
PolicyDecodedState,
|
||||
PolicyField,
|
||||
PolicyFieldType,
|
||||
PolicyRowStatus,
|
||||
PolicyRunView,
|
||||
PolicySetupResult,
|
||||
PolicySource,
|
||||
PolicyState,
|
||||
PolicyStats,
|
||||
PolicyActivityItem,
|
||||
PolicyStatus,
|
||||
WirePolicy,
|
||||
WireOutputOptions,
|
||||
WireOutputSpec,
|
||||
TriggerConfig,
|
||||
} from "@portal/mocks/policies";
|
||||
export {
|
||||
ENDPOINT_LABELS,
|
||||
POLICY_CATEGORIES,
|
||||
POLICY_CONFIG,
|
||||
POLICY_DOC_TYPES,
|
||||
POLICY_SOURCES,
|
||||
TOOL_ENDPOINTS,
|
||||
humanizeEndpoint,
|
||||
} from "@portal/mocks/policies";
|
||||
|
||||
// Re-export the wire step type under the legacy name components depend on.
|
||||
export type { WirePipelineStep as PipelineStep } from "@shared/policies/types";
|
||||
|
||||
// ── Client-side catalogue assembly ───────────────────────────────────────────
|
||||
|
||||
function decoratePolicy(
|
||||
decoded: PolicyDecodedState,
|
||||
runs: PolicyRunView[],
|
||||
isDefault: boolean,
|
||||
): DecoratedPolicy | null {
|
||||
const category = POLICY_CATEGORIES.find((c) => c.id === decoded.categoryId);
|
||||
const config = POLICY_CONFIG[decoded.categoryId];
|
||||
if (!category || !config) return null;
|
||||
|
||||
const policyRuns = runs.filter((r) => r.policyId === decoded.id);
|
||||
const status: PolicyStatus = decoded.enabled ? "active" : "paused";
|
||||
const state: PolicyState = {
|
||||
configured: true,
|
||||
status,
|
||||
sources: decoded.sources,
|
||||
scopeTypes: decoded.scopeTypes,
|
||||
reviewerEmail: decoded.reviewerEmail,
|
||||
fieldValues: decoded.fieldValues,
|
||||
outputMode: decoded.outputMode,
|
||||
outputName: decoded.outputName,
|
||||
outputNamePosition: decoded.outputNamePosition,
|
||||
runOn: decoded.runOn,
|
||||
maxRetries: decoded.maxRetries,
|
||||
retryDelayMinutes: decoded.retryDelayMinutes,
|
||||
backendId: decoded.id,
|
||||
isDefault,
|
||||
};
|
||||
|
||||
return {
|
||||
category,
|
||||
config,
|
||||
state,
|
||||
steps: decoded.steps,
|
||||
stats: runsToStats(policyRuns),
|
||||
activity: runsToActivity(policyRuns),
|
||||
};
|
||||
}
|
||||
|
||||
/** GET /api/v1/policies + GET /api/v1/policies/runs → assembled catalogue. */
|
||||
/** GET /api/v1/policies — the catalogue + every configured policy. */
|
||||
export async function fetchPolicies(): Promise<PoliciesResponse> {
|
||||
const [wirePolicies, runs] = await Promise.all([
|
||||
apiClient.local.json<WirePolicy[]>("/api/v1/policies"),
|
||||
apiClient.local
|
||||
.json<PolicyRunView[]>("/api/v1/policies/runs")
|
||||
.catch(() => [] as PolicyRunView[]),
|
||||
]);
|
||||
|
||||
const decodedByCategory = new Map<
|
||||
string,
|
||||
{ decoded: PolicyDecodedState; isDefault: boolean }
|
||||
>();
|
||||
for (const wire of wirePolicies) {
|
||||
const decoded = fromWirePolicy(wire);
|
||||
if (decoded.categoryId) {
|
||||
decodedByCategory.set(decoded.categoryId, { decoded, isDefault: false });
|
||||
}
|
||||
}
|
||||
|
||||
const catalogue: CatalogueEntry[] = POLICY_CATEGORIES.map((category) => {
|
||||
const entry = decodedByCategory.get(category.id);
|
||||
const policy = entry
|
||||
? decoratePolicy(entry.decoded, runs, entry.isDefault)
|
||||
: null;
|
||||
return { category, config: POLICY_CONFIG[category.id], policy };
|
||||
});
|
||||
|
||||
const active = wirePolicies.filter((p) => p.enabled).length;
|
||||
const paused = wirePolicies.filter((p) => !p.enabled).length;
|
||||
const enabledPolicyIds = new Set(
|
||||
wirePolicies.filter((p) => p.enabled).map((p) => p.id),
|
||||
);
|
||||
const docsEnforced = runs.filter(
|
||||
(r) =>
|
||||
r.status === "COMPLETED" &&
|
||||
r.policyId != null &&
|
||||
enabledPolicyIds.has(r.policyId),
|
||||
).length;
|
||||
const summary: PoliciesSummary = {
|
||||
active,
|
||||
paused,
|
||||
categories: POLICY_CATEGORIES.length,
|
||||
docsEnforced,
|
||||
};
|
||||
|
||||
return { summary, catalogue };
|
||||
return apiClient.local.json<PoliciesResponse>("/api/v1/policies");
|
||||
}
|
||||
|
||||
/** GET /api/v1/policies/{id} — one stored policy's raw record. */
|
||||
export async function fetchPolicy(id: string): Promise<WirePolicy> {
|
||||
return apiClient.local.json<WirePolicy>(
|
||||
export async function fetchPolicy(id: string): Promise<Policy> {
|
||||
return apiClient.local.json<Policy>(
|
||||
`/api/v1/policies/${encodeURIComponent(id)}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/policies — create (blank id) or update (matched id). The
|
||||
* backend stamps owner + teamId server-side and returns the stored record.
|
||||
* POST /api/v1/policies — create (blank id) or update (matched id). The backend
|
||||
* assigns owner + team server-side and returns the stored policy with its id.
|
||||
*/
|
||||
export async function savePolicy(wire: WirePolicy): Promise<WirePolicy> {
|
||||
return apiClient.local.json<WirePolicy>("/api/v1/policies", {
|
||||
export async function savePolicy(policy: Policy): Promise<Policy> {
|
||||
return apiClient.local.json<Policy>("/api/v1/policies", {
|
||||
method: "POST",
|
||||
body: wire,
|
||||
body: policy,
|
||||
});
|
||||
}
|
||||
|
||||
/** DELETE /api/v1/policies/{id} */
|
||||
/** DELETE /api/v1/policies/{id} — remove a stored policy. */
|
||||
export async function deletePolicy(id: string): Promise<void> {
|
||||
await apiClient.local.json<void>(
|
||||
`/api/v1/policies/${encodeURIComponent(id)}`,
|
||||
@@ -177,80 +76,22 @@ export async function deletePolicy(id: string): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Wire-build helpers (so Policies.tsx doesn't need codec knowledge) ────────
|
||||
|
||||
const DEFAULT_RETRIES = 3;
|
||||
const DEFAULT_RETRY_DELAY = 5;
|
||||
|
||||
// Catalogue policy bodies carry categoryId at the top level so the pipelines
|
||||
// mock handler can discriminate them from raw pipeline saves on the shared
|
||||
// POST /api/v1/policies endpoint. The real backend ignores unknown fields.
|
||||
type CatalogueWireBody = WirePolicy & { categoryId: string };
|
||||
|
||||
/** Build a wire policy from a setup wizard result. */
|
||||
export function buildWireFromSetup(
|
||||
entry: CatalogueEntry,
|
||||
result: PolicySetupResult,
|
||||
enabled = true,
|
||||
): CatalogueWireBody {
|
||||
return {
|
||||
categoryId: entry.category.id,
|
||||
...toWirePolicy({
|
||||
id: entry.policy?.state.backendId ?? "",
|
||||
name: `${entry.category.label} Policy`,
|
||||
enabled,
|
||||
categoryId: entry.category.id,
|
||||
sources: result.sources,
|
||||
scopeTypes: result.scopeTypes,
|
||||
reviewerEmail: result.reviewerEmail,
|
||||
fieldValues: result.fieldValues,
|
||||
runOn: result.runOn,
|
||||
outputMode: result.outputMode,
|
||||
outputName: result.outputName,
|
||||
outputNamePosition: result.outputNamePosition,
|
||||
maxRetries: result.maxRetries,
|
||||
retryDelayMinutes: result.retryDelayMinutes,
|
||||
steps: result.steps,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a wire policy from an existing decorated policy (e.g. for pause/resume). */
|
||||
export function buildWireFromState(
|
||||
entry: CatalogueEntry,
|
||||
policy: DecoratedPolicy,
|
||||
enabled: boolean,
|
||||
): CatalogueWireBody {
|
||||
const s = policy.state;
|
||||
return {
|
||||
categoryId: entry.category.id,
|
||||
...toWirePolicy({
|
||||
id: s.backendId ?? "",
|
||||
name: `${entry.category.label} Policy`,
|
||||
enabled,
|
||||
categoryId: entry.category.id,
|
||||
sources: s.sources,
|
||||
scopeTypes: s.scopeTypes,
|
||||
reviewerEmail: s.reviewerEmail,
|
||||
fieldValues: s.fieldValues,
|
||||
runOn: s.runOn ?? "upload",
|
||||
outputMode: s.outputMode ?? "new_version",
|
||||
outputName: s.outputName ?? "",
|
||||
outputNamePosition: s.outputNamePosition ?? "suffix",
|
||||
maxRetries: s.maxRetries ?? DEFAULT_RETRIES,
|
||||
retryDelayMinutes: s.retryDelayMinutes ?? DEFAULT_RETRY_DELAY,
|
||||
steps: policy.steps,
|
||||
}),
|
||||
};
|
||||
/** The async run acknowledgement: a run id to poll for status. */
|
||||
export interface PolicyRunResponse {
|
||||
status: boolean;
|
||||
/** The run id (poll GET /api/v1/policies/run/{id} for status). */
|
||||
fileId: string | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/policies/{id}/run — trigger a stored policy immediately. The
|
||||
* real endpoint is multipart; the portal sends no files, relying on whatever
|
||||
* the backend has queued for this policy.
|
||||
* POST /api/v1/policies/{id}/run — run a stored policy now. The real endpoint
|
||||
* is multipart (the documents to process); the portal has no files to attach,
|
||||
* so this triggers the policy on whatever the backend has queued and returns a
|
||||
* run id. Runs regardless of the policy's enabled flag.
|
||||
*/
|
||||
export async function runPolicy(id: string): Promise<{ runId: string }> {
|
||||
return apiClient.local.json<{ runId: string }>(
|
||||
export async function runPolicy(id: string): Promise<PolicyRunResponse> {
|
||||
return apiClient.local.json<PolicyRunResponse>(
|
||||
`/api/v1/policies/${encodeURIComponent(id)}/run`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { RequirePortalAccess } from "@shared/auth";
|
||||
import { RequireAdmin } from "@shared/auth";
|
||||
import { Spinner } from "@shared/components";
|
||||
import { LoginScreen } from "@portal/components/LoginScreen";
|
||||
import { EDITOR_URL } from "@portal/auth/editorUrl";
|
||||
|
||||
// Stable module-level ref; RequirePortalAccess calls it from an effect.
|
||||
/**
|
||||
* Module-level so the reference is stable across renders (RequireAdmin runs it
|
||||
* from an effect). The portal is admin-only today; authenticated non-admins are
|
||||
* bounced to the editor rather than shown an access-denied page.
|
||||
*/
|
||||
function redirectToEditor(): void {
|
||||
window.location.href = EDITOR_URL;
|
||||
}
|
||||
@@ -27,11 +31,17 @@ function FullScreenMessage({ children }: { children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Gates the portal: login when signed out, redirect to the editor without portal access. */
|
||||
/**
|
||||
* Gates the whole portal behind an authenticated admin session:
|
||||
* - loading -> spinner
|
||||
* - signed out -> login screen
|
||||
* - signed in, not admin -> redirect to the editor
|
||||
* - signed in admin -> the portal
|
||||
*/
|
||||
export function AuthGate({ children }: { children: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<RequirePortalAccess
|
||||
<RequireAdmin
|
||||
fallback={<LoginScreen />}
|
||||
onForbidden={redirectToEditor}
|
||||
loading={
|
||||
@@ -46,6 +56,6 @@ export function AuthGate({ children }: { children: ReactNode }) {
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</RequirePortalAccess>
|
||||
</RequireAdmin>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Card, Chip, StatusBadge } from "@shared/components";
|
||||
import { Card, Chip, StatusBadge, StatTile } from "@shared/components";
|
||||
import type { CatalogueEntry } from "@portal/api/policies";
|
||||
import { policyIcon } from "@portal/components/policies/policyIcons";
|
||||
import "@portal/views/Policies.css";
|
||||
@@ -9,13 +9,17 @@ interface PolicyCategoryCardProps {
|
||||
onOpen: (entry: CatalogueEntry) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* One card per policy category. Configured categories show the live status +
|
||||
* stats and open the detail panel; unconfigured ones show the summary + a
|
||||
* "Set up" affordance; coming-soon categories render locked and inert.
|
||||
*/
|
||||
export function PolicyCategoryCard({ entry, onOpen }: PolicyCategoryCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { category, config, policy } = entry;
|
||||
const comingSoon = category.comingSoon === true;
|
||||
const openable = !comingSoon;
|
||||
const status = policy?.state.status;
|
||||
const enforces = config.rules.join(" · ");
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -38,39 +42,22 @@ export function PolicyCategoryCard({ entry, onOpen }: PolicyCategoryCardProps) {
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span className="portal-policies__cat-icon" aria-hidden>
|
||||
{policyIcon(category.icon)}
|
||||
</span>
|
||||
|
||||
<div className="portal-policies__card-identity">
|
||||
<h2 className="portal-policies__card-title">{category.label}</h2>
|
||||
{enforces && (
|
||||
<span className="portal-policies__card-enforces">{enforces}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{comingSoon ? (
|
||||
<Chip tone="neutral" size="sm">
|
||||
{t("policies.card.comingSoon")}
|
||||
</Chip>
|
||||
) : policy ? (
|
||||
<div className="portal-policies__card-meta">
|
||||
<span className="portal-policies__card-statpair">
|
||||
<span className="portal-policies__card-statval">
|
||||
{policy.stats.enforced.toLocaleString()}
|
||||
</span>
|
||||
<span className="portal-policies__card-statlbl">
|
||||
{t("policies.stats.docsEnforced")}
|
||||
</span>
|
||||
</span>
|
||||
<span className="portal-policies__card-statpair">
|
||||
<span className="portal-policies__card-statval">
|
||||
{policy.stats.dataProcessed}
|
||||
</span>
|
||||
<span className="portal-policies__card-statlbl">
|
||||
{t("policies.stats.dataProcessed")}
|
||||
</span>
|
||||
</span>
|
||||
<header className="portal-policies__card-head">
|
||||
<span
|
||||
className={`portal-policies__cat-icon portal-policies__cat-icon--${category.tone}`}
|
||||
aria-hidden
|
||||
>
|
||||
{policyIcon(category.icon)}
|
||||
</span>
|
||||
<div className="portal-policies__card-titles">
|
||||
<h2 className="portal-policies__card-title">{category.label}</h2>
|
||||
<span className="portal-policies__card-blurb">{category.desc}</span>
|
||||
</div>
|
||||
{comingSoon ? (
|
||||
<Chip tone="neutral" size="sm">
|
||||
{t("policies.card.comingSoon")}
|
||||
</Chip>
|
||||
) : policy ? (
|
||||
<StatusBadge
|
||||
tone={status === "paused" ? "warning" : "success"}
|
||||
size="sm"
|
||||
@@ -80,11 +67,45 @@ export function PolicyCategoryCard({ entry, onOpen }: PolicyCategoryCardProps) {
|
||||
? t("policies.status.paused")
|
||||
: t("policies.status.active")}
|
||||
</StatusBadge>
|
||||
</div>
|
||||
) : (
|
||||
<Chip tone="blue" size="sm">
|
||||
{t("policies.card.notSetUp")}
|
||||
</Chip>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<p className="portal-policies__card-summary">{config.summary}</p>
|
||||
|
||||
{policy ? (
|
||||
<footer className="portal-policies__card-stats">
|
||||
<StatTile
|
||||
label={t("policies.stats.docsEnforced")}
|
||||
value={policy.stats.enforced.toLocaleString()}
|
||||
/>
|
||||
<StatTile
|
||||
label={t("policies.stats.dataProcessed")}
|
||||
value={policy.stats.dataProcessed}
|
||||
/>
|
||||
<StatTile
|
||||
label={t("policies.stats.activeFor")}
|
||||
value={policy.stats.activeFor}
|
||||
/>
|
||||
</footer>
|
||||
) : (
|
||||
<Chip tone="blue" size="sm">
|
||||
{t("policies.card.notSetUp")}
|
||||
</Chip>
|
||||
<footer className="portal-policies__card-foot">
|
||||
<div className="portal-policies__card-rules">
|
||||
{config.rules.slice(0, 3).map((rule) => (
|
||||
<Chip key={rule} tone="neutral" size="sm">
|
||||
{rule}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
{!comingSoon && (
|
||||
<span className="portal-policies__card-cta">
|
||||
{t("policies.card.setUp")}
|
||||
</span>
|
||||
)}
|
||||
</footer>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -12,7 +12,6 @@ const meta: Meta<typeof PolicyDetailPanel> = {
|
||||
onRun: () => {},
|
||||
onTogglePause: () => {},
|
||||
onDelete: () => {},
|
||||
onRetry: () => {},
|
||||
},
|
||||
};
|
||||
export default meta;
|
||||
@@ -44,40 +43,3 @@ export const CustomNoActivity: Story = {
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** Flagged activity items — shows retry button and error expansion. */
|
||||
export const WithFlaggedItems: Story = {
|
||||
args: {
|
||||
policy: {
|
||||
...decorateForStory("security"),
|
||||
state: { ...decorateForStory("security").state, isDefault: false },
|
||||
activity: [
|
||||
{
|
||||
doc: "Q4-Report.pdf",
|
||||
action: "Low-confidence match — routed for review",
|
||||
time: "2h ago",
|
||||
status: "flagged",
|
||||
},
|
||||
{
|
||||
doc: "Contract-2026.pdf",
|
||||
action:
|
||||
"Enforcement failed: timeout after 30s — step 2/3 (redact) did not complete within the allowed window. Check the document for unusual formatting or large embedded images.",
|
||||
time: "4h ago",
|
||||
status: "flagged",
|
||||
},
|
||||
{
|
||||
doc: "Invoice-March.pdf",
|
||||
action: "Enforced successfully",
|
||||
time: "6h ago",
|
||||
status: "enforced",
|
||||
},
|
||||
{
|
||||
doc: "HR-Policy-v3.pdf",
|
||||
action: "Processing…",
|
||||
time: "just now",
|
||||
status: "processing",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,102 +1,42 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Banner,
|
||||
Button,
|
||||
Card,
|
||||
Chip,
|
||||
EmptyState,
|
||||
Modal,
|
||||
StatTile,
|
||||
StatusBadge,
|
||||
} from "@shared/components";
|
||||
import {
|
||||
humanizeEndpoint,
|
||||
type DecoratedPolicy,
|
||||
type PolicyActivityItem,
|
||||
} from "@portal/api/policies";
|
||||
import { humanizeEndpoint, type DecoratedPolicy } from "@portal/api/policies";
|
||||
import { policyIcon } from "@portal/components/policies/policyIcons";
|
||||
import "@portal/views/Policies.css";
|
||||
|
||||
interface PolicyDetailPanelProps {
|
||||
/** The configured policy being viewed, or null when closed. */
|
||||
policy: DecoratedPolicy | null;
|
||||
/** Whether a lifecycle action (run/pause/delete) is in flight. */
|
||||
busy?: boolean;
|
||||
onClose: () => void;
|
||||
onEdit: () => void;
|
||||
onRun?: () => void;
|
||||
onRun: () => void;
|
||||
onTogglePause: () => void;
|
||||
onDelete: () => void;
|
||||
onRetry?: (item: PolicyActivityItem) => void;
|
||||
}
|
||||
|
||||
function CheckIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="13"
|
||||
height="13"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function WarnIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="13"
|
||||
height="13"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function SpinIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="13"
|
||||
height="13"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className="portal-policies__activity-spin"
|
||||
aria-hidden
|
||||
>
|
||||
<path d="M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ActivityError({ message }: { message: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const needsToggle = message.length > 80 || message.includes("\n");
|
||||
if (!needsToggle) return <>{message}</>;
|
||||
return (
|
||||
<span className="portal-policies__activity-error">
|
||||
<span
|
||||
className={
|
||||
"portal-policies__activity-error-text" +
|
||||
(expanded ? "" : " portal-policies__activity-error-text--clamped")
|
||||
}
|
||||
>
|
||||
{message}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="portal-policies__link portal-policies__activity-error-toggle"
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
>
|
||||
{expanded
|
||||
? t("policies.detail.showLess")
|
||||
: t("policies.detail.showMore")}
|
||||
</button>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const ACTIVITY_TONE = {
|
||||
enforced: "success",
|
||||
flagged: "warning",
|
||||
processing: "info",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Narrative view for a configured policy: the enforced tool chain, recent
|
||||
* activity, summary stats, and the lifecycle actions (run now, pause/resume,
|
||||
* delete). Built-in (default) policies hide Delete — they're configurable but
|
||||
* not deletable, matching the backend.
|
||||
*/
|
||||
export function PolicyDetailPanel({
|
||||
policy,
|
||||
busy = false,
|
||||
@@ -105,36 +45,31 @@ export function PolicyDetailPanel({
|
||||
onRun,
|
||||
onTogglePause,
|
||||
onDelete,
|
||||
onRetry,
|
||||
}: PolicyDetailPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
if (!policy) return null;
|
||||
const { category, config, state, steps, stats, activity } = policy;
|
||||
const isPaused = state.status === "paused";
|
||||
const canDelete = state.isDefault !== true;
|
||||
|
||||
const enforceItems = steps.length > 0 ? steps.map((s) => s.operation) : null;
|
||||
const hasEditorSource = state.sources.includes("editor");
|
||||
const trigger =
|
||||
state.runOn === "export"
|
||||
? t("policies.detail.onEveryExport")
|
||||
: t("policies.detail.onEveryUpload");
|
||||
const outputLabel =
|
||||
state.outputMode === "new_file"
|
||||
? t("policies.detail.outputAsNewFile")
|
||||
: t("policies.detail.outputAsNewVersion");
|
||||
|
||||
function sourceLabel(id: string) {
|
||||
if (id === "editor") return t("sources.types.editor.label");
|
||||
return id;
|
||||
}
|
||||
const enforceItems = steps.length > 0 ? steps.map((s) => s.operation) : [];
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onClose={onClose}
|
||||
width="lg"
|
||||
title={category.label}
|
||||
title={
|
||||
<span className="portal-policies__wizard-title">
|
||||
<span
|
||||
className={`portal-policies__cat-icon portal-policies__cat-icon--${category.tone}`}
|
||||
aria-hidden
|
||||
>
|
||||
{policyIcon(category.icon)}
|
||||
</span>
|
||||
{t("policies.detail.title", { category: category.label })}
|
||||
</span>
|
||||
}
|
||||
subtitle={config.summary}
|
||||
footer={
|
||||
<div className="portal-policies__detail-foot">
|
||||
{canDelete && (
|
||||
@@ -149,17 +84,15 @@ export function PolicyDetailPanel({
|
||||
{t("policies.detail.actions.delete")}
|
||||
</Button>
|
||||
)}
|
||||
{onRun && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onRun}
|
||||
disabled={busy}
|
||||
style={canDelete ? undefined : { marginRight: "auto" }}
|
||||
>
|
||||
{t("policies.detail.actions.runNow")}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onRun}
|
||||
disabled={busy}
|
||||
style={canDelete ? undefined : { marginRight: "auto" }}
|
||||
>
|
||||
{t("policies.detail.actions.runNow")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -176,66 +109,57 @@ export function PolicyDetailPanel({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{/* Status + trigger strip */}
|
||||
<div className="portal-policies__detail-status">
|
||||
<StatusBadge tone={isPaused ? "warning" : "success"} pulse={!isPaused}>
|
||||
{isPaused ? t("policies.status.paused") : t("policies.status.active")}
|
||||
</StatusBadge>
|
||||
{hasEditorSource && (
|
||||
<>
|
||||
<span className="portal-policies__detail-sep" aria-hidden>
|
||||
·
|
||||
</span>
|
||||
<span className="portal-policies__detail-meta">{trigger}</span>
|
||||
<span className="portal-policies__detail-sep" aria-hidden>
|
||||
·
|
||||
</span>
|
||||
<span className="portal-policies__detail-meta">{outputLabel}</span>
|
||||
</>
|
||||
)}
|
||||
<span className="portal-policies__detail-meta">
|
||||
{t("policies.detail.meta", {
|
||||
event: state.runOn ?? "upload",
|
||||
output:
|
||||
state.outputMode === "new_file"
|
||||
? t("policies.detail.outputAsNewFile")
|
||||
: t("policies.detail.outputAsNewVersion"),
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Enforces — plain text, no pills */}
|
||||
<div className="portal-policies__detail-inline">
|
||||
<span className="portal-policies__detail-inline-label">
|
||||
{t("policies.detail.enforces")}
|
||||
</span>
|
||||
<span className="portal-policies__detail-inline-value">
|
||||
{enforceItems
|
||||
? enforceItems.map((op, i) => (
|
||||
<span key={op}>
|
||||
{i > 0 && (
|
||||
<span
|
||||
className="portal-policies__enforce-arrow"
|
||||
aria-hidden
|
||||
>
|
||||
{" "}
|
||||
→{" "}
|
||||
</span>
|
||||
)}
|
||||
<h3 className="portal-policies__wizard-heading">
|
||||
{t("policies.detail.enforces")}
|
||||
</h3>
|
||||
<Card padding="default">
|
||||
{enforceItems.length > 0 ? (
|
||||
<div className="portal-policies__enforce-flow">
|
||||
{enforceItems.map((op, i) => (
|
||||
<span key={op} className="portal-policies__enforce-item">
|
||||
{i > 0 && (
|
||||
<span className="portal-policies__enforce-arrow" aria-hidden>
|
||||
→
|
||||
</span>
|
||||
)}
|
||||
<Chip tone="blue" size="sm">
|
||||
{humanizeEndpoint(op)}
|
||||
</span>
|
||||
))
|
||||
: config.rules.join(" · ")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Sources */}
|
||||
{state.sources.length > 0 && (
|
||||
<div className="portal-policies__detail-inline">
|
||||
<span className="portal-policies__detail-inline-label">
|
||||
{t("policies.detail.sources")}
|
||||
</span>
|
||||
<span className="portal-policies__detail-inline-value">
|
||||
{state.sources.map(sourceLabel).join(" · ")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</Chip>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="portal-policies__enforce-flow">
|
||||
{config.rules.map((rule) => (
|
||||
<Chip key={rule} tone="neutral" size="sm">
|
||||
{rule}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="portal-policies__enforce-note">
|
||||
{t("policies.detail.enforceNote", { scope: config.scopeLabel })}
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
<h3 className="portal-policies__wizard-heading">
|
||||
{t("policies.detail.recentActivity")}
|
||||
</h3>
|
||||
|
||||
{activity.length > 0 ? (
|
||||
<Card padding="none">
|
||||
{activity.map((item, i) => (
|
||||
@@ -244,46 +168,20 @@ export function PolicyDetailPanel({
|
||||
className="portal-policies__activity-row"
|
||||
>
|
||||
<span
|
||||
className={`portal-policies__activity-icon portal-policies__activity-icon--${
|
||||
item.status === "flagged"
|
||||
? "warning"
|
||||
: item.status === "processing"
|
||||
? "info"
|
||||
: "success"
|
||||
}`}
|
||||
>
|
||||
{item.status === "flagged" ? (
|
||||
<WarnIcon />
|
||||
) : item.status === "processing" ? (
|
||||
<SpinIcon />
|
||||
) : (
|
||||
<CheckIcon />
|
||||
)}
|
||||
</span>
|
||||
className={`portal-policies__activity-dot portal-policies__activity-dot--${ACTIVITY_TONE[item.status]}`}
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="portal-policies__activity-text">
|
||||
<span className="portal-policies__activity-doc">
|
||||
{item.doc}
|
||||
</span>
|
||||
<span className="portal-policies__activity-action">
|
||||
{item.status === "flagged" ? (
|
||||
<ActivityError message={item.action} />
|
||||
) : (
|
||||
item.action
|
||||
)}
|
||||
{item.action}
|
||||
</span>
|
||||
</span>
|
||||
<span className="portal-policies__activity-time">
|
||||
{item.time}
|
||||
</span>
|
||||
{item.status === "flagged" && onRetry && (
|
||||
<button
|
||||
type="button"
|
||||
className="portal-policies__link portal-policies__activity-retry"
|
||||
onClick={() => onRetry(item)}
|
||||
>
|
||||
{t("policies.detail.retry")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
@@ -311,6 +209,16 @@ export function PolicyDetailPanel({
|
||||
value={stats.activeFor}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{state.scopeTypes.length > 0 && (
|
||||
<Banner
|
||||
tone="neutral"
|
||||
title={t("policies.detail.scoped.title")}
|
||||
description={t("policies.detail.scoped.description", {
|
||||
types: state.scopeTypes.join(", "),
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,16 +14,14 @@ import {
|
||||
} from "@shared/components";
|
||||
import {
|
||||
POLICY_DOC_TYPES,
|
||||
POLICY_SOURCES,
|
||||
humanizeEndpoint,
|
||||
type CatalogueEntry,
|
||||
type PipelineStep,
|
||||
type PolicySetupResult,
|
||||
} from "@portal/api/policies";
|
||||
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 "@portal/views/Policies.css";
|
||||
|
||||
interface PolicySetupWizardProps {
|
||||
@@ -61,27 +59,15 @@ function resolveFieldValues(
|
||||
* round-trips); otherwise the category preset's default chain. Each preset step
|
||||
* starts enabled — the user toggles tools off in the workflow.
|
||||
*/
|
||||
// Temporary: tracks which tools start disabled until the tool registry lands in
|
||||
// the portal and can drive this via registry metadata or a defaultEnabled flag.
|
||||
const DISABLED_BY_DEFAULT = new Set(["/api/v1/security/add-watermark"]);
|
||||
|
||||
function seedTools(entry: CatalogueEntry): ToolState[] {
|
||||
const savedSteps = entry.policy?.steps ?? [];
|
||||
const savedByOp = new Map(savedSteps.map((s) => [s.operation, s]));
|
||||
// Always use defaultOperations as the canonical list so tools added after a
|
||||
// policy was first saved still appear when editing.
|
||||
return entry.config.defaultOperations.map((s) => {
|
||||
const saved = savedByOp.get(s.operation);
|
||||
return {
|
||||
operation: s.operation,
|
||||
enabled: saved
|
||||
? true
|
||||
: savedSteps.length > 0
|
||||
? false
|
||||
: !DISABLED_BY_DEFAULT.has(s.operation),
|
||||
parameters: saved?.parameters ?? s.parameters,
|
||||
};
|
||||
});
|
||||
const source = entry.policy?.steps?.length
|
||||
? entry.policy.steps
|
||||
: entry.config.defaultOperations;
|
||||
return source.map((s) => ({
|
||||
operation: s.operation,
|
||||
enabled: true,
|
||||
parameters: s.parameters,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,50 +112,27 @@ function PolicySetupWizardBody({
|
||||
resolveFieldValues(entry),
|
||||
);
|
||||
const [sources, setSources] = useState<string[]>(
|
||||
policy?.state.sources ?? ["editor"],
|
||||
policy?.state.sources.length ? policy.state.sources : ["editor"],
|
||||
);
|
||||
|
||||
const sourcesAsync = useAsync(() => fetchSources(), []);
|
||||
const availableSources = useMemo(() => {
|
||||
const backendSources = (sourcesAsync.data?.sources ?? []).filter(
|
||||
(s) => s.status !== "disabled",
|
||||
);
|
||||
const editorSource = {
|
||||
id: "editor",
|
||||
name: t("sources.types.editor.label"),
|
||||
type: "editor",
|
||||
status: "active" as const,
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [],
|
||||
docsTotal: null,
|
||||
};
|
||||
return [editorSource, ...backendSources];
|
||||
}, [sourcesAsync.data, t]);
|
||||
const [scopeNarrow, setScopeNarrow] = useState(
|
||||
(policy?.state.scopeTypes.length ?? 0) > 0,
|
||||
);
|
||||
const [scopeTypes, setScopeTypes] = useState<string[]>(
|
||||
policy?.state.scopeTypes ?? [],
|
||||
);
|
||||
// TODO: replace with user-picker backed by GET /api/v1/user/users (UserSummary[]).
|
||||
// Store username (which is the email in Spring Security) as reviewerEmail.
|
||||
// See UserSelector.tsx in the editor for the grouping/display pattern.
|
||||
const [reviewerEmail] = useState(policy?.state.reviewerEmail ?? "");
|
||||
const [reviewerEmail, setReviewerEmail] = useState(
|
||||
policy?.state.reviewerEmail ?? "you@acme.com",
|
||||
);
|
||||
const [outputMode, setOutputMode] = useState<"new_file" | "new_version">(
|
||||
policy?.state.outputMode ?? "new_version",
|
||||
);
|
||||
const [outputName, setOutputName] = useState(policy?.state.outputName ?? "");
|
||||
const [outputNamePosition, setOutputNamePosition] = useState<
|
||||
"prefix" | "suffix" | "auto-number"
|
||||
>(policy?.state.outputNamePosition ?? "suffix");
|
||||
>("suffix");
|
||||
const [runOn, setRunOn] = useState<"upload" | "export">(
|
||||
policy?.state.runOn ?? "upload",
|
||||
);
|
||||
const [maxRetries, setMaxRetries] = useState(policy?.state.maxRetries ?? 3);
|
||||
const [retryDelayMinutes, setRetryDelayMinutes] = useState(
|
||||
policy?.state.retryDelayMinutes ?? 5,
|
||||
);
|
||||
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -217,8 +180,6 @@ function PolicySetupWizardBody({
|
||||
outputName: outputName.trim(),
|
||||
outputNamePosition,
|
||||
runOn,
|
||||
maxRetries,
|
||||
retryDelayMinutes,
|
||||
steps,
|
||||
});
|
||||
} catch {
|
||||
@@ -236,7 +197,10 @@ function PolicySetupWizardBody({
|
||||
width="lg"
|
||||
title={
|
||||
<span className="portal-policies__wizard-title">
|
||||
<span className="portal-policies__cat-icon" aria-hidden>
|
||||
<span
|
||||
className={`portal-policies__cat-icon portal-policies__cat-icon--${category.tone}`}
|
||||
aria-hidden
|
||||
>
|
||||
{policyIcon(category.icon)}
|
||||
</span>
|
||||
{isEdit
|
||||
@@ -308,7 +272,9 @@ function PolicySetupWizardBody({
|
||||
<span className="portal-policies__tool-name">
|
||||
{humanizeEndpoint(tl.operation)}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<code className="portal-policies__tool-endpoint">
|
||||
{tl.operation}
|
||||
</code>
|
||||
<ToggleSwitch
|
||||
size="sm"
|
||||
checked={tl.enabled}
|
||||
@@ -349,43 +315,31 @@ function PolicySetupWizardBody({
|
||||
{t("policies.wizard.sources.heading")}
|
||||
</h3>
|
||||
<div className="portal-policies__sources">
|
||||
{sourcesAsync.loading && !sourcesAsync.data ? (
|
||||
<p className="portal-policies__sources-loading">
|
||||
{t("policies.wizard.sources.loading")}
|
||||
</p>
|
||||
) : availableSources.length === 1 ? (
|
||||
<Banner
|
||||
tone="neutral"
|
||||
title={t("policies.wizard.sources.emptyTitle")}
|
||||
description={t("policies.wizard.sources.emptyDescription")}
|
||||
/>
|
||||
) : (
|
||||
availableSources.map((src) => (
|
||||
<button
|
||||
key={src.id}
|
||||
type="button"
|
||||
className={
|
||||
"portal-policies__source" +
|
||||
(sources.includes(src.id)
|
||||
? " portal-policies__source--on"
|
||||
: "")
|
||||
}
|
||||
onClick={() => toggleSource(src.id)}
|
||||
>
|
||||
<span className="portal-policies__source-icon" aria-hidden>
|
||||
{sourceTypeMeta(src.type).icon}
|
||||
{POLICY_SOURCES.map((src) => (
|
||||
<button
|
||||
key={src.id}
|
||||
type="button"
|
||||
className={
|
||||
"portal-policies__source" +
|
||||
(sources.includes(src.id)
|
||||
? " portal-policies__source--on"
|
||||
: "")
|
||||
}
|
||||
onClick={() => toggleSource(src.id)}
|
||||
>
|
||||
<span className="portal-policies__source-icon" aria-hidden>
|
||||
{policyIcon(src.icon)}
|
||||
</span>
|
||||
<span className="portal-policies__source-text">
|
||||
<span className="portal-policies__source-label">
|
||||
{src.label}
|
||||
</span>
|
||||
<span className="portal-policies__source-text">
|
||||
<span className="portal-policies__source-label">
|
||||
{src.name}
|
||||
</span>
|
||||
<span className="portal-policies__source-desc">
|
||||
{src.type}
|
||||
</span>
|
||||
<span className="portal-policies__source-desc">
|
||||
{src.desc}
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<h3 className="portal-policies__wizard-heading">
|
||||
@@ -438,130 +392,107 @@ function PolicySetupWizardBody({
|
||||
{t("policies.wizard.output.heading")}
|
||||
</h3>
|
||||
<div className="portal-policies__fields">
|
||||
{sources.includes("editor") && (
|
||||
<>
|
||||
<FormField
|
||||
label={t("policies.wizard.output.runOn.label")}
|
||||
helperText={t("policies.wizard.output.runOn.helper")}
|
||||
>
|
||||
<Select
|
||||
inputSize="sm"
|
||||
value={runOn}
|
||||
onChange={(e) =>
|
||||
setRunOn(e.target.value as "upload" | "export")
|
||||
}
|
||||
options={[
|
||||
{
|
||||
value: "upload",
|
||||
label: t("policies.wizard.output.runOn.upload"),
|
||||
},
|
||||
{
|
||||
value: "export",
|
||||
label: t("policies.wizard.output.runOn.export"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label={t("policies.wizard.output.outputAs.label")}>
|
||||
<Select
|
||||
inputSize="sm"
|
||||
value={outputMode}
|
||||
onChange={(e) => {
|
||||
const mode = e.target.value as "new_file" | "new_version";
|
||||
setOutputMode(mode);
|
||||
// Auto-number only applies to separate new files.
|
||||
if (
|
||||
mode === "new_version" &&
|
||||
outputNamePosition === "auto-number"
|
||||
) {
|
||||
setOutputNamePosition("suffix");
|
||||
}
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
value: "new_version",
|
||||
label: t("policies.wizard.output.outputAs.newVersion"),
|
||||
},
|
||||
{
|
||||
value: "new_file",
|
||||
label: t("policies.wizard.output.outputAs.newFile"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
label={t("policies.wizard.output.filenameRule.label")}
|
||||
>
|
||||
<div className="portal-policies__name-row">
|
||||
<Select
|
||||
inputSize="sm"
|
||||
value={outputNamePosition}
|
||||
onChange={(e) =>
|
||||
setOutputNamePosition(
|
||||
e.target.value as "prefix" | "suffix" | "auto-number",
|
||||
)
|
||||
}
|
||||
options={[
|
||||
{
|
||||
value: "prefix",
|
||||
label: t(
|
||||
"policies.wizard.output.filenameRule.prefix",
|
||||
),
|
||||
},
|
||||
{
|
||||
value: "suffix",
|
||||
label: t(
|
||||
"policies.wizard.output.filenameRule.suffix",
|
||||
),
|
||||
},
|
||||
...(outputMode === "new_file"
|
||||
? [
|
||||
{
|
||||
value: "auto-number",
|
||||
label: t(
|
||||
"policies.wizard.output.filenameRule.autoNumber",
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]}
|
||||
/>
|
||||
{outputNamePosition !== "auto-number" && (
|
||||
<Input
|
||||
inputSize="sm"
|
||||
value={outputName}
|
||||
placeholder={t(
|
||||
"policies.wizard.output.filenameRule.placeholder",
|
||||
)}
|
||||
onChange={(e) => setOutputName(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</FormField>
|
||||
</>
|
||||
)}
|
||||
{/* TODO: reviewer user-picker goes here */}
|
||||
<h4 className="portal-policies__wizard-subheading">
|
||||
{t("policies.wizard.output.retries.heading")}
|
||||
</h4>
|
||||
<FormField label={t("policies.wizard.output.retries.maxLabel")}>
|
||||
<Input
|
||||
<FormField
|
||||
label={t("policies.wizard.output.runOn.label")}
|
||||
helperText={t("policies.wizard.output.runOn.helper")}
|
||||
>
|
||||
<Select
|
||||
inputSize="sm"
|
||||
type="number"
|
||||
value={String(maxRetries)}
|
||||
value={runOn}
|
||||
onChange={(e) =>
|
||||
setMaxRetries(Math.max(0, Number(e.target.value) || 0))
|
||||
setRunOn(e.target.value as "upload" | "export")
|
||||
}
|
||||
options={[
|
||||
{
|
||||
value: "upload",
|
||||
label: t("policies.wizard.output.runOn.upload"),
|
||||
},
|
||||
{
|
||||
value: "export",
|
||||
label: t("policies.wizard.output.runOn.export"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label={t("policies.wizard.output.retries.delayLabel")}>
|
||||
<FormField label={t("policies.wizard.output.outputAs.label")}>
|
||||
<Select
|
||||
inputSize="sm"
|
||||
value={outputMode}
|
||||
onChange={(e) => {
|
||||
const mode = e.target.value as "new_file" | "new_version";
|
||||
setOutputMode(mode);
|
||||
// Auto-number only applies to separate new files.
|
||||
if (
|
||||
mode === "new_version" &&
|
||||
outputNamePosition === "auto-number"
|
||||
) {
|
||||
setOutputNamePosition("suffix");
|
||||
}
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
value: "new_version",
|
||||
label: t("policies.wizard.output.outputAs.newVersion"),
|
||||
},
|
||||
{
|
||||
value: "new_file",
|
||||
label: t("policies.wizard.output.outputAs.newFile"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label={t("policies.wizard.output.filenameRule.label")}>
|
||||
<div className="portal-policies__name-row">
|
||||
<Select
|
||||
inputSize="sm"
|
||||
value={outputNamePosition}
|
||||
onChange={(e) =>
|
||||
setOutputNamePosition(
|
||||
e.target.value as "prefix" | "suffix" | "auto-number",
|
||||
)
|
||||
}
|
||||
options={[
|
||||
{
|
||||
value: "prefix",
|
||||
label: t("policies.wizard.output.filenameRule.prefix"),
|
||||
},
|
||||
{
|
||||
value: "suffix",
|
||||
label: t("policies.wizard.output.filenameRule.suffix"),
|
||||
},
|
||||
...(outputMode === "new_file"
|
||||
? [
|
||||
{
|
||||
value: "auto-number",
|
||||
label: t(
|
||||
"policies.wizard.output.filenameRule.autoNumber",
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]}
|
||||
/>
|
||||
{outputNamePosition !== "auto-number" && (
|
||||
<Input
|
||||
inputSize="sm"
|
||||
value={outputName}
|
||||
placeholder={t(
|
||||
"policies.wizard.output.filenameRule.placeholder",
|
||||
)}
|
||||
onChange={(e) => setOutputName(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</FormField>
|
||||
<FormField
|
||||
label={t("policies.wizard.output.reviewerEmail.label")}
|
||||
helperText={t("policies.wizard.output.reviewerEmail.helper")}
|
||||
>
|
||||
<Input
|
||||
inputSize="sm"
|
||||
type="number"
|
||||
value={String(retryDelayMinutes)}
|
||||
onChange={(e) =>
|
||||
setRetryDelayMinutes(Math.max(0, Number(e.target.value) || 0))
|
||||
}
|
||||
type="email"
|
||||
value={reviewerEmail}
|
||||
onChange={(e) => setReviewerEmail(e.target.value)}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
|
||||
@@ -3,53 +3,38 @@
|
||||
* policy built straight from the catalogue + seed data, so stories render the
|
||||
* same shapes the MSW handlers serve without standing up the whole API.
|
||||
*/
|
||||
import { fromWirePolicy } from "@shared/policies/codec";
|
||||
import { runsToActivity, runsToStats } from "@shared/policies/runs";
|
||||
import {
|
||||
POLICY_CATEGORIES,
|
||||
POLICY_CONFIG,
|
||||
seedPolicies,
|
||||
seedPolicyRuns,
|
||||
seedRuntime,
|
||||
type DecoratedPolicy,
|
||||
type PolicyState,
|
||||
} from "@portal/mocks/policies";
|
||||
|
||||
export { POLICY_CATEGORIES, POLICY_CONFIG };
|
||||
|
||||
/** A decorated, active policy for a category, mirroring fetchPolicies() assembly. */
|
||||
/** A decorated, active policy for a category, mirroring the handler's decorate(). */
|
||||
export function decorateForStory(categoryId: string): DecoratedPolicy {
|
||||
const category = POLICY_CATEGORIES.find((c) => c.id === categoryId)!;
|
||||
const config = POLICY_CONFIG[categoryId];
|
||||
|
||||
// Use the seeded security policy for any category (story only needs the shape).
|
||||
const wire = seedPolicies()[0];
|
||||
const decoded = fromWirePolicy(wire);
|
||||
const allRuns = seedPolicyRuns();
|
||||
const policyRuns = allRuns.filter((r) => r.policyId === wire.id);
|
||||
|
||||
const state: PolicyState = {
|
||||
configured: true,
|
||||
status: decoded.enabled ? "active" : "paused",
|
||||
sources: decoded.sources,
|
||||
scopeTypes: decoded.scopeTypes,
|
||||
reviewerEmail: decoded.reviewerEmail,
|
||||
fieldValues: decoded.fieldValues,
|
||||
outputMode: decoded.outputMode,
|
||||
outputName: decoded.outputName,
|
||||
outputNamePosition: decoded.outputNamePosition,
|
||||
runOn: decoded.runOn,
|
||||
maxRetries: decoded.maxRetries,
|
||||
retryDelayMinutes: decoded.retryDelayMinutes,
|
||||
backendId: wire.id,
|
||||
isDefault: true,
|
||||
};
|
||||
|
||||
const rt = seedRuntime().pol_security_default;
|
||||
return {
|
||||
category,
|
||||
config,
|
||||
state,
|
||||
steps: decoded.steps,
|
||||
stats: runsToStats(policyRuns),
|
||||
activity: runsToActivity(policyRuns),
|
||||
state: {
|
||||
configured: true,
|
||||
status: "active",
|
||||
sources: ["editor"],
|
||||
scopeTypes: [],
|
||||
reviewerEmail: rt.reviewerEmail,
|
||||
fieldValues: {},
|
||||
outputMode: "new_version",
|
||||
outputName: "",
|
||||
runOn: "upload",
|
||||
backendId: "pol_story",
|
||||
isDefault: true,
|
||||
},
|
||||
steps: config.defaultOperations,
|
||||
stats: rt.stats,
|
||||
activity: rt.activity,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ export interface SourceTypeMeta {
|
||||
|
||||
const SOURCE_TYPE_META: Record<string, SourceTypeMeta> = {
|
||||
folder: { labelKey: "sources.types.folder.label", icon: "⛁", tone: "blue" },
|
||||
editor: { labelKey: "sources.types.editor.label", icon: "✏", tone: "green" },
|
||||
};
|
||||
|
||||
const UNKNOWN_TYPE_META: SourceTypeMeta = {
|
||||
|
||||
@@ -1,35 +1,39 @@
|
||||
import { http, HttpResponse, delay } from "msw";
|
||||
import {
|
||||
POLICY_CATEGORIES,
|
||||
POLICY_CONFIG,
|
||||
seedPolicies,
|
||||
seedPolicyRuns,
|
||||
type WirePolicy,
|
||||
seedRuntime,
|
||||
emptyRuntime,
|
||||
type CatalogueEntry,
|
||||
type DecoratedPolicy,
|
||||
type PoliciesResponse,
|
||||
type PoliciesSummary,
|
||||
type Policy,
|
||||
type PolicyRowStatus,
|
||||
type PolicyRuntime,
|
||||
type PolicyState,
|
||||
} from "@portal/mocks/policies";
|
||||
import type { PolicyRunView } from "@shared/policies/types";
|
||||
|
||||
/**
|
||||
* The portal exercises the REAL policy API base — `/api/v1/policies`, NOT the
|
||||
* portal's usual `/v1/...` — so this surface is plug-and-play against the live
|
||||
* backend (drop MSW and the same calls hit Stirling).
|
||||
*
|
||||
* These handlers speak the backend's actual wire contract:
|
||||
* - GET /api/v1/policies → WirePolicy[]
|
||||
* - GET /api/v1/policies/runs → PolicyRunView[]
|
||||
* - POST /api/v1/policies → WirePolicy (create / update)
|
||||
* - DELETE /api/v1/policies/:id → 204
|
||||
*
|
||||
* The decorated catalogue (summary, category grouping, stats) is assembled
|
||||
* client-side in api/policies.ts#fetchPolicies(), mirroring the real backend.
|
||||
* backend (drop MSW and the same calls hit Stirling). These handlers mutate an
|
||||
* in-memory store, so create/delete/run behave like a real backend within a
|
||||
* session (see the notifications handler for the same stateful pattern).
|
||||
*/
|
||||
|
||||
let store: WirePolicy[] = seedPolicies();
|
||||
let runs: PolicyRunView[] = seedPolicyRuns();
|
||||
/** Configured policies, keyed by backend id (the source of truth). */
|
||||
let store: Policy[] = seedPolicies();
|
||||
/** Runtime extras the wire record doesn't carry (scope, stats, activity). */
|
||||
let runtime: Record<string, PolicyRuntime> = seedRuntime();
|
||||
|
||||
export function resetPoliciesStore(
|
||||
seed?: WirePolicy[],
|
||||
seedRuns?: PolicyRunView[],
|
||||
seed?: Policy[],
|
||||
seedRt?: Record<string, PolicyRuntime>,
|
||||
): void {
|
||||
store = seed ? [...seed] : seedPolicies();
|
||||
runs = seedRuns ? [...seedRuns] : seedPolicyRuns();
|
||||
runtime = seedRt ? { ...seedRt } : seedRuntime();
|
||||
}
|
||||
|
||||
let idCounter = 0;
|
||||
@@ -38,21 +42,78 @@ function nextId(categoryId: string): string {
|
||||
return `pol_${categoryId}_${Date.now().toString(36)}_${idCounter}`;
|
||||
}
|
||||
|
||||
function categoryId(wire: WirePolicy): string {
|
||||
return (wire.output?.options?.categoryId as string | undefined) ?? "";
|
||||
/** Derive the display status from the wire `enabled` flag. */
|
||||
function rowStatus(policy: Policy): PolicyRowStatus {
|
||||
return policy.enabled ? "active" : "paused";
|
||||
}
|
||||
|
||||
/** Build the decorated runtime view the catalogue/detail consumes. */
|
||||
function decorate(policy: Policy): DecoratedPolicy | null {
|
||||
const category = POLICY_CATEGORIES.find((c) => c.id === policy.categoryId);
|
||||
const config = POLICY_CONFIG[policy.categoryId];
|
||||
if (!category || !config) return null;
|
||||
const rt = runtime[policy.id] ?? emptyRuntime();
|
||||
const status = rowStatus(policy);
|
||||
const state: PolicyState = {
|
||||
configured: true,
|
||||
status: status === "paused" ? "paused" : "active",
|
||||
sources: policy.sources.map((s) => s.source),
|
||||
scopeTypes: rt.scopeTypes,
|
||||
reviewerEmail: rt.reviewerEmail,
|
||||
fieldValues: rt.fieldValues,
|
||||
outputMode: policy.output.mode,
|
||||
outputName: policy.output.name,
|
||||
runOn: policy.trigger?.event ?? "upload",
|
||||
backendId: policy.id,
|
||||
isDefault: rt.isDefault,
|
||||
};
|
||||
return {
|
||||
category,
|
||||
config,
|
||||
state,
|
||||
steps: policy.steps,
|
||||
stats: rt.stats,
|
||||
activity: rt.activity,
|
||||
};
|
||||
}
|
||||
|
||||
/** The full catalogue response: every category, each with its policy (or null). */
|
||||
function buildResponse(): PoliciesResponse {
|
||||
const byCategory = new Map<string, Policy>();
|
||||
for (const p of store) byCategory.set(p.categoryId, p);
|
||||
|
||||
const catalogue: CatalogueEntry[] = POLICY_CATEGORIES.map((category) => {
|
||||
const policy = byCategory.get(category.id);
|
||||
return {
|
||||
category,
|
||||
config: POLICY_CONFIG[category.id],
|
||||
policy: policy ? decorate(policy) : null,
|
||||
};
|
||||
});
|
||||
|
||||
const active = store.filter((p) => p.enabled).length;
|
||||
const paused = store.filter((p) => !p.enabled).length;
|
||||
const docsEnforced = store
|
||||
.filter((p) => p.enabled)
|
||||
.reduce((sum, p) => sum + (runtime[p.id]?.stats.enforced ?? 0), 0);
|
||||
const summary: PoliciesSummary = {
|
||||
active,
|
||||
paused,
|
||||
categories: POLICY_CATEGORIES.length,
|
||||
docsEnforced,
|
||||
};
|
||||
|
||||
return { summary, catalogue };
|
||||
}
|
||||
|
||||
export const policiesHandlers = [
|
||||
// List — the catalogue (categories + configs + configured policies).
|
||||
http.get("/api/v1/policies", async () => {
|
||||
await delay(120);
|
||||
return HttpResponse.json(store);
|
||||
}),
|
||||
|
||||
http.get("/api/v1/policies/runs", async () => {
|
||||
await delay(120);
|
||||
return HttpResponse.json(runs);
|
||||
return HttpResponse.json(buildResponse());
|
||||
}),
|
||||
|
||||
// Get one stored policy by id (the raw wire record).
|
||||
http.get("/api/v1/policies/:id", async ({ params }) => {
|
||||
await delay(120);
|
||||
const policy = store.find((p) => p.id === params.id);
|
||||
@@ -60,17 +121,17 @@ export const policiesHandlers = [
|
||||
return HttpResponse.json(policy);
|
||||
}),
|
||||
|
||||
// Create or update — one policy per category: a create for a category that
|
||||
// already has one replaces it, matching the editor's contract.
|
||||
// Create or update — a blank id is assigned (create) or matched (update).
|
||||
// One policy per category: a create for a category that already has one
|
||||
// replaces it, matching the editor's "one policy per category, ever".
|
||||
http.post("/api/v1/policies", async ({ request }) => {
|
||||
await delay(120);
|
||||
const incoming = (await request.json()) as WirePolicy;
|
||||
const catId = categoryId(incoming);
|
||||
const incoming = (await request.json()) as Policy;
|
||||
const existing = incoming.id
|
||||
? store.find((p) => p.id === incoming.id)
|
||||
: store.find((p) => categoryId(p) === catId);
|
||||
const id = existing?.id ?? nextId(catId);
|
||||
const saved: WirePolicy = {
|
||||
: store.find((p) => p.categoryId === incoming.categoryId);
|
||||
const id = existing?.id ?? nextId(incoming.categoryId);
|
||||
const saved: Policy = {
|
||||
...incoming,
|
||||
id,
|
||||
owner: existing?.owner ?? "you@acme.com",
|
||||
@@ -78,16 +139,45 @@ export const policiesHandlers = [
|
||||
store = existing
|
||||
? store.map((p) => (p.id === id ? saved : p))
|
||||
: [...store, saved];
|
||||
// Seed runtime for a brand-new policy so the detail panel has somewhere to
|
||||
// read from; an update keeps whatever runtime it already had.
|
||||
if (!runtime[id]) runtime[id] = emptyRuntime();
|
||||
return HttpResponse.json(saved);
|
||||
}),
|
||||
|
||||
// Delete a stored policy by id.
|
||||
http.delete("/api/v1/policies/:id", async ({ params }) => {
|
||||
await delay(120);
|
||||
const id = String(params.id);
|
||||
if (!store.some((p) => p.id === id))
|
||||
return new HttpResponse(null, { status: 404 });
|
||||
const existed = store.some((p) => p.id === id);
|
||||
if (!existed) return new HttpResponse(null, { status: 404 });
|
||||
store = store.filter((p) => p.id !== id);
|
||||
runs = runs.filter((r) => r.policyId !== id);
|
||||
delete runtime[id];
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
|
||||
// Run a stored policy now. The real endpoint is multipart (files) and returns
|
||||
// a run id; the portal has no files, so the mock just acknowledges with a run
|
||||
// id and nudges the activity feed so the run is visible.
|
||||
http.post("/api/v1/policies/:id/run", async ({ params }) => {
|
||||
await delay(120);
|
||||
const id = String(params.id);
|
||||
const policy = store.find((p) => p.id === id);
|
||||
if (!policy) return new HttpResponse(null, { status: 404 });
|
||||
const rt = runtime[id] ?? emptyRuntime();
|
||||
runtime[id] = {
|
||||
...rt,
|
||||
activity: [
|
||||
{
|
||||
doc: "manual-run.pdf",
|
||||
action: "Enforcing…",
|
||||
time: "just now",
|
||||
status: "processing",
|
||||
},
|
||||
...rt.activity,
|
||||
],
|
||||
};
|
||||
const runId = `run_${Date.now().toString(36)}`;
|
||||
return HttpResponse.json({ status: true, fileId: runId, message: null });
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -1,84 +1,200 @@
|
||||
/**
|
||||
* Policies fixtures and the canonical TS model the portal shares with them.
|
||||
*
|
||||
* Wire types (`WirePolicy`, `WirePipelineStep`) come from the shared codec
|
||||
* layer and match the backend record exactly. Catalogue and UI types
|
||||
* (`PolicyCategory`, `PolicyConfigDef`, `PolicyState`, …) are portal-only:
|
||||
* the backend has no "category" concept — `categoryId` rides in
|
||||
* `output.options`. The catalogue assembles client-side in `api/policies.ts`
|
||||
* from the decoded wire records + these static definitions.
|
||||
* The model mirrors the editor + backend policy contract so the portal's
|
||||
* "set up a policy" flow is plug-and-play against the real `/api/v1/policies`
|
||||
* API. A policy is a stored automation: an ordered chain of tool steps (each
|
||||
* step's `operation` is a Stirling endpoint path) plus an output destination,
|
||||
* fired automatically by a trigger (editor upload/export) over a set of
|
||||
* sources. The catalogue groups policies by category, each category carrying a
|
||||
* `PolicyConfigDef` (summary, rules, fields, default tool chain) the setup flow
|
||||
* builds from.
|
||||
*
|
||||
* api/policies.ts re-exports everything; components never reach in here.
|
||||
* The wire types (`Policy`, `PipelineStep`) match the backend records exactly;
|
||||
* the catalogue + decorated state shapes (`PolicyConfigDef`, `PolicyField`,
|
||||
* `PolicyState`, …) are lifted from the editor's `types/policies.ts`, with
|
||||
* ReactNode icons replaced by string icon keys (the portal renders its own).
|
||||
*
|
||||
* api/policies.ts re-exports these types; the MSW handlers serve the fixture
|
||||
* data over intercepted apiClient.local.json() calls. Components never reach in here.
|
||||
*/
|
||||
|
||||
import type { WirePipelineStep, WirePolicy } from "@shared/policies/types";
|
||||
import type { PolicyRunView } from "@shared/policies/types";
|
||||
|
||||
export type {
|
||||
PolicyActivityItem,
|
||||
PolicyDecodedState,
|
||||
PolicyRunStatus,
|
||||
PolicyRunView,
|
||||
PolicyStats,
|
||||
WireOutputOptions,
|
||||
WireOutputSpec,
|
||||
WirePipelineStep,
|
||||
WirePolicy,
|
||||
} from "@shared/policies/types";
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Catalogue model — portal-specific (lifted from editor types/policies.ts) */
|
||||
/* Backend wire model — matches Policy.java / PipelineStep.java exactly */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export type PolicyStatus = "active" | "paused";
|
||||
/**
|
||||
* A single tool invocation in a policy's pipeline. `operation` is a Stirling
|
||||
* endpoint path (e.g. `/api/v1/security/auto-redact`); `parameters` are the
|
||||
* scalar form fields that endpoint accepts. `fileParameters` binds a tool's
|
||||
* named file field to an asset key in a run's supporting-file store.
|
||||
*/
|
||||
export interface PipelineStep {
|
||||
operation: string;
|
||||
parameters: Record<string, unknown>;
|
||||
fileParameters?: Record<string, string>;
|
||||
}
|
||||
|
||||
/** When a policy fires automatically. A null trigger means manual-only. */
|
||||
export interface TriggerConfig {
|
||||
/** The editor event the policy runs on. */
|
||||
event: "upload" | "export";
|
||||
}
|
||||
|
||||
/** Where a policy's documents come from (a connected source). */
|
||||
export interface InputSpec {
|
||||
/** Source id from {@link POLICY_SOURCES}. */
|
||||
source: string;
|
||||
}
|
||||
|
||||
/** How a run's result is delivered. */
|
||||
export interface OutputSpec {
|
||||
/** A separate new file, or a new version of the input the policy ran on. */
|
||||
mode: "new_file" | "new_version";
|
||||
/** Rename rule for the output; empty keeps the input filename. */
|
||||
name: string;
|
||||
namePosition: "prefix" | "suffix" | "auto-number";
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored policy record — the exact JSON body the backend returns from
|
||||
* `GET /api/v1/policies` and accepts on `POST /api/v1/policies`. The portal
|
||||
* decorates this with catalogue + runtime data for display (see {@link decorate}).
|
||||
*/
|
||||
export interface Policy {
|
||||
/** Blank on create; the backend assigns one and returns it. */
|
||||
id: string;
|
||||
name: string;
|
||||
/** Server-assigned owner; the client never forges it. */
|
||||
owner?: string;
|
||||
/** Whether the trigger fires automatically. Pausing flips this. */
|
||||
enabled: boolean;
|
||||
trigger: TriggerConfig | null;
|
||||
sources: InputSpec[];
|
||||
steps: PipelineStep[];
|
||||
output: OutputSpec;
|
||||
/** The category this policy belongs to. Drives catalogue grouping. */
|
||||
categoryId: string;
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Catalogue model — lifted from editor types/policies.ts */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export type PolicyStatus = "default" | "active" | "paused";
|
||||
|
||||
/** Derived display status for a card/detail. */
|
||||
export type PolicyRowStatus = "active" | "paused" | "setup";
|
||||
|
||||
/** A configurable field within a policy's settings. */
|
||||
export type PolicyFieldType = "toggle" | "select" | "chips" | "text";
|
||||
|
||||
export interface PolicyField {
|
||||
label: string;
|
||||
key: string;
|
||||
type: PolicyFieldType;
|
||||
/** Default value: boolean (toggle), string (select/text), string[] (chips). */
|
||||
value: boolean | string | string[];
|
||||
/** Options for select/chips. */
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Static definition of a policy category. The editor's `icon: ReactNode` is
|
||||
* replaced by a string `icon` key the portal resolves to its own glyph.
|
||||
*/
|
||||
export interface PolicyCategory {
|
||||
id: string;
|
||||
label: string;
|
||||
/** Icon key the portal renders (not a component — the portal owns glyphs). */
|
||||
icon: string;
|
||||
/** Visual tone for the category's icon chip. */
|
||||
tone: "neutral" | "blue" | "purple" | "green" | "amber" | "red";
|
||||
/** Long description shown in the setup flow. */
|
||||
desc: string;
|
||||
/** Drives the "Set up Classification" affordance (doc-type narrowing). */
|
||||
providesClassification?: boolean;
|
||||
/** Locked "Coming soon" — can't be opened or configured. */
|
||||
comingSoon?: boolean;
|
||||
}
|
||||
|
||||
/** The narrative + field configuration backing a category. */
|
||||
export interface PolicyConfigDef {
|
||||
/** One-line summary of what the policy enforces. */
|
||||
summary: string;
|
||||
/** Pipeline-like rule chips shown in the "Enforces" section. */
|
||||
rules: string[];
|
||||
/** Human label for the scope this policy applies to. */
|
||||
scopeLabel: string;
|
||||
/** Editable policy-level settings fields. */
|
||||
fields: PolicyField[];
|
||||
defaultOperations: WirePipelineStep[];
|
||||
/**
|
||||
* The preset pipeline a new policy is seeded with — the real, editable tool
|
||||
* steps (each `operation` is a Stirling endpoint path, matching the backend's
|
||||
* PipelineStep). The setup flow starts from these.
|
||||
*/
|
||||
defaultOperations: PipelineStep[];
|
||||
}
|
||||
|
||||
/** A source a policy can run over (setup "Sources" step). */
|
||||
export interface PolicySource {
|
||||
id: string;
|
||||
label: string;
|
||||
desc: string;
|
||||
/** Icon key the portal renders. */
|
||||
icon: string;
|
||||
}
|
||||
|
||||
/** Three-up summary stats shown at the foot of a configured policy's detail. */
|
||||
export interface PolicyStats {
|
||||
/** Documents enforced. */
|
||||
enforced: number;
|
||||
/** Human-formatted data-processed figure, e.g. "2.3 GB". */
|
||||
dataProcessed: string;
|
||||
/** Human-formatted active-for figure, e.g. "12d", or "—" when idle. */
|
||||
activeFor: string;
|
||||
}
|
||||
|
||||
/** An entry in a policy's recent-activity feed. */
|
||||
export interface PolicyActivityItem {
|
||||
/** Document the policy acted on. */
|
||||
doc: string;
|
||||
/** What the policy did, e.g. "Redacted 4 PII matches • 2 pages". */
|
||||
action: string;
|
||||
/** Relative timestamp, e.g. "2h ago". */
|
||||
time: string;
|
||||
/** "enforced" (clean), "flagged" (needs review), "processing" (running). */
|
||||
status: "enforced" | "flagged" | "processing";
|
||||
}
|
||||
|
||||
/**
|
||||
* The collected settings the setup flow gathers and the detail panel reads —
|
||||
* the editor's `PolicyState`, minus the local-cache bookkeeping (folderId etc).
|
||||
*/
|
||||
export interface PolicyState {
|
||||
configured: boolean;
|
||||
status: PolicyStatus;
|
||||
/** Selected sources (ids from {@link POLICY_SOURCES}). */
|
||||
sources: string[];
|
||||
/** When non-empty, narrows the policy to these document types. */
|
||||
scopeTypes: string[];
|
||||
/** Email low-confidence enforcements are routed to. */
|
||||
reviewerEmail: string;
|
||||
/** Saved field values, keyed by field key (overrides the definition default). */
|
||||
fieldValues: Record<string, boolean | string | string[]>;
|
||||
/** How a run's output is delivered. Defaults to "new_version". */
|
||||
outputMode?: "new_file" | "new_version";
|
||||
/** Rename rule for the output. Empty keeps the input filename. */
|
||||
outputName?: string;
|
||||
outputNamePosition?: "prefix" | "suffix" | "auto-number";
|
||||
/** When the policy runs. Defaults to "upload". */
|
||||
runOn?: "upload" | "export";
|
||||
maxRetries?: number;
|
||||
retryDelayMinutes?: number;
|
||||
/** Backend record id once persisted; used to update/delete/run it. */
|
||||
backendId?: string;
|
||||
/** A shipped catalogue policy (configurable but not deletable). */
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
/** What the setup flow hands back on submit — collected settings + built steps. */
|
||||
export interface PolicySetupResult {
|
||||
fieldValues: Record<string, boolean | string | string[]>;
|
||||
sources: string[];
|
||||
@@ -88,40 +204,57 @@ export interface PolicySetupResult {
|
||||
outputName: string;
|
||||
outputNamePosition: "prefix" | "suffix" | "auto-number";
|
||||
runOn: "upload" | "export";
|
||||
maxRetries: number;
|
||||
retryDelayMinutes: number;
|
||||
steps: WirePipelineStep[];
|
||||
/** The configured tool chain as backend pipeline steps. */
|
||||
steps: PipelineStep[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A configured policy as the catalogue view consumes it: the wire record plus
|
||||
* the catalogue's category/config and derived runtime data. The handlers build
|
||||
* this from the in-memory store + fixtures.
|
||||
*/
|
||||
export interface DecoratedPolicy {
|
||||
category: PolicyCategory;
|
||||
config: PolicyConfigDef;
|
||||
state: PolicyState;
|
||||
steps: WirePipelineStep[];
|
||||
stats: import("@shared/policies/types").PolicyStats;
|
||||
activity: import("@shared/policies/types").PolicyActivityItem[];
|
||||
/** The policy's configured steps (drives the detail "Enforces" flow). */
|
||||
steps: PipelineStep[];
|
||||
stats: PolicyStats;
|
||||
activity: PolicyActivityItem[];
|
||||
}
|
||||
|
||||
/** Catalogue strip totals shown above the cards. */
|
||||
export interface PoliciesSummary {
|
||||
/** Policies currently active (enabled). */
|
||||
active: number;
|
||||
/** Policies configured but paused. */
|
||||
paused: number;
|
||||
/** Categories available to configure. */
|
||||
categories: number;
|
||||
/** Documents enforced across all active policies. */
|
||||
docsEnforced: number;
|
||||
}
|
||||
|
||||
/** The `GET /api/v1/policies` response, in the portal's catalogue shape. */
|
||||
export interface PoliciesResponse {
|
||||
summary: PoliciesSummary;
|
||||
/** Every catalogue category, each with its definition + (optional) state. */
|
||||
catalogue: CatalogueEntry[];
|
||||
}
|
||||
|
||||
/** One catalogue row: a category, its definition, and its current state. */
|
||||
export interface CatalogueEntry {
|
||||
category: PolicyCategory;
|
||||
config: PolicyConfigDef;
|
||||
/** The configured policy's runtime view, or null when not yet set up. */
|
||||
policy: DecoratedPolicy | null;
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Tool → endpoint registry */
|
||||
/* Maps a frontend tool id to its Stirling endpoint path. The setup flow's */
|
||||
/* pipeline steps carry endpoint paths (the backend's PipelineStep contract), */
|
||||
/* so this is the seam that keeps the preset chains plug-and-play. */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export const TOOL_ENDPOINTS: Record<string, string> = {
|
||||
@@ -133,6 +266,7 @@ export const TOOL_ENDPOINTS: Record<string, string> = {
|
||||
compress: "/api/v1/misc/compress-pdf",
|
||||
};
|
||||
|
||||
/** A friendly label for an endpoint path (for the detail "Enforces" chips). */
|
||||
export const ENDPOINT_LABELS: Record<string, string> = {
|
||||
"/api/v1/security/auto-redact": "Redact PII",
|
||||
"/api/v1/security/sanitize-pdf": "Remove JavaScript",
|
||||
@@ -142,6 +276,7 @@ export const ENDPOINT_LABELS: Record<string, string> = {
|
||||
"/api/v1/misc/compress-pdf": "Compress",
|
||||
};
|
||||
|
||||
/** "/api/v1/security/auto-redact" → "Auto Redact" — fallback humanisation. */
|
||||
export function humanizeEndpoint(path: string): string {
|
||||
if (ENDPOINT_LABELS[path]) return ENDPOINT_LABELS[path];
|
||||
const last = path.split("/").filter(Boolean).pop() ?? path;
|
||||
@@ -152,12 +287,15 @@ export function humanizeEndpoint(path: string): string {
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Catalogue definitions */
|
||||
/* Catalogue definitions — categories, configs, sources, doc types */
|
||||
/* Modelled on the editor's policyDefinitions. PII redact regexes are the */
|
||||
/* precise patterns the /auto-redact endpoint matches (wordsToRedact). */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
/** PII regexes seeded into a Security policy's redact step (SSN + cards). */
|
||||
const DEFAULT_PII_PATTERNS: string[] = [
|
||||
"\\b(?!000|666|9\\d{2})\\d{3}([- ])(?!00)\\d{2}\\1(?!0000)\\d{4}\\b",
|
||||
"\\b(?:4\\d{12}(?:\\d{3})?|5[1-5]\\d{14}|3[47]\\d{13}|6(?:011|5\\d{2})\\d{12})\\b",
|
||||
"\\b(?!000|666|9\\d{2})\\d{3}([- ])(?!00)\\d{2}\\1(?!0000)\\d{4}\\b", // SSN
|
||||
"\\b(?:4\\d{12}(?:\\d{3})?|5[1-5]\\d{14}|3[47]\\d{13}|6(?:011|5\\d{2})\\d{12})\\b", // cards
|
||||
];
|
||||
|
||||
export const POLICY_CATEGORIES: PolicyCategory[] = [
|
||||
@@ -233,8 +371,10 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
security: {
|
||||
summary:
|
||||
"Detects and redacts PII, strips active content (JavaScript), and watermarks documents.",
|
||||
rules: ["Redact PII", "Remove JavaScript", "Watermark"],
|
||||
rules: ["Redact PII", "Remove JavaScript"],
|
||||
scopeLabel: "All documents",
|
||||
// Default chain: redact PII (flattened to image so text is truly removed) +
|
||||
// strip JavaScript. Watermark is offered in the designer but off by default.
|
||||
defaultOperations: [
|
||||
{
|
||||
operation: TOOL_ENDPOINTS.redact,
|
||||
@@ -255,14 +395,9 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
removeFonts: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: TOOL_ENDPOINTS.watermark,
|
||||
// convertPDFToImage bakes the watermark in so it can't be stripped
|
||||
parameters: {
|
||||
convertPDFToImage: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
// The tool chain is configured per-tool in the designer (redact / sanitize /
|
||||
// watermark); no separate policy-level fields.
|
||||
fields: [],
|
||||
},
|
||||
compliance: {
|
||||
@@ -347,6 +482,45 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
},
|
||||
};
|
||||
|
||||
export const POLICY_SOURCES: PolicySource[] = [
|
||||
{
|
||||
id: "editor",
|
||||
label: "Editor",
|
||||
desc: "Documents you save or export in Stirling",
|
||||
icon: "file",
|
||||
},
|
||||
{
|
||||
id: "device",
|
||||
label: "Entire device",
|
||||
desc: "All PDFs on this machine, retroactively",
|
||||
icon: "device",
|
||||
},
|
||||
{
|
||||
id: "sharepoint",
|
||||
label: "SharePoint",
|
||||
desc: "Connected SharePoint libraries",
|
||||
icon: "globe",
|
||||
},
|
||||
{
|
||||
id: "dropbox",
|
||||
label: "Dropbox",
|
||||
desc: "Connected Dropbox folders",
|
||||
icon: "cloud",
|
||||
},
|
||||
{
|
||||
id: "gmail",
|
||||
label: "Gmail",
|
||||
desc: "PDF attachments in email",
|
||||
icon: "mail",
|
||||
},
|
||||
{
|
||||
id: "gdrive",
|
||||
label: "Google Drive",
|
||||
desc: "Connected Drive folders",
|
||||
icon: "folder",
|
||||
},
|
||||
];
|
||||
|
||||
export const POLICY_DOC_TYPES: string[] = [
|
||||
"Contracts",
|
||||
"Invoices",
|
||||
@@ -359,86 +533,80 @@ export const POLICY_DOC_TYPES: string[] = [
|
||||
];
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Seed data — real backend wire format */
|
||||
/* Seed policies — a few configured policies in the wire shape, so the store */
|
||||
/* behaves like a backend that already has policies set up. */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export function seedPolicies(): WirePolicy[] {
|
||||
/** The shipped default policies the handlers seed the store with. */
|
||||
export function seedPolicies(): Policy[] {
|
||||
return [
|
||||
{
|
||||
id: "pol_security_default",
|
||||
name: "Security Policy",
|
||||
owner: "security@acme.com",
|
||||
enabled: true,
|
||||
trigger: null,
|
||||
trigger: { event: "upload" },
|
||||
sources: [{ source: "editor" }],
|
||||
steps: POLICY_CONFIG.security.defaultOperations,
|
||||
output: {
|
||||
type: "inline",
|
||||
options: {
|
||||
runOn: "upload",
|
||||
mode: "new_version",
|
||||
name: "",
|
||||
position: "suffix",
|
||||
maxRetries: 3,
|
||||
retryDelayMinutes: 5,
|
||||
categoryId: "security",
|
||||
sources: ["src-claims"],
|
||||
scopeTypes: [],
|
||||
reviewerEmail: "security@acme.com",
|
||||
fieldValues: {},
|
||||
output: { mode: "new_version", name: "", namePosition: "suffix" },
|
||||
categoryId: "security",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-policy runtime extras keyed by policy id — the parts the wire record
|
||||
* doesn't carry (collected field values, scope, derived stats + activity).
|
||||
* In a real backend these would be derived server-side from the user's files.
|
||||
*/
|
||||
export interface PolicyRuntime {
|
||||
scopeTypes: string[];
|
||||
reviewerEmail: string;
|
||||
fieldValues: Record<string, boolean | string | string[]>;
|
||||
stats: PolicyStats;
|
||||
activity: PolicyActivityItem[];
|
||||
isDefault?: boolean;
|
||||
}
|
||||
|
||||
export function seedRuntime(): Record<string, PolicyRuntime> {
|
||||
return {
|
||||
pol_security_default: {
|
||||
scopeTypes: [],
|
||||
reviewerEmail: "security@acme.com",
|
||||
fieldValues: {},
|
||||
isDefault: true,
|
||||
stats: { enforced: 4821, dataProcessed: "2.3 GB", activeFor: "34d" },
|
||||
activity: [
|
||||
{
|
||||
doc: "Q2-vendor-agreement.pdf",
|
||||
action: "Redacted 6 PII matches • JavaScript stripped",
|
||||
time: "12m ago",
|
||||
status: "enforced",
|
||||
},
|
||||
},
|
||||
{
|
||||
doc: "patient-intake-0481.pdf",
|
||||
action: "Low-confidence match — routed for review",
|
||||
time: "1h ago",
|
||||
status: "flagged",
|
||||
},
|
||||
{
|
||||
doc: "invoice-7782.pdf",
|
||||
action: "Enforcing…",
|
||||
time: "just now",
|
||||
status: "processing",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
};
|
||||
}
|
||||
|
||||
const NOW = Date.now();
|
||||
const M = 60000;
|
||||
const H = 3600000;
|
||||
const D = 86400000;
|
||||
|
||||
/** Seed `PolicyRunView` records that drive the activity feed + stats. */
|
||||
export function seedPolicyRuns(): PolicyRunView[] {
|
||||
return [
|
||||
{
|
||||
runId: "run_001",
|
||||
policyId: "pol_security_default",
|
||||
status: "COMPLETED",
|
||||
currentStep: 2,
|
||||
stepCount: 2,
|
||||
error: null,
|
||||
outputs: [{ fileId: "f1", fileName: "Q2-vendor-agreement.pdf" }],
|
||||
createdAt: NOW - 12 * M,
|
||||
},
|
||||
{
|
||||
runId: "run_002",
|
||||
policyId: "pol_security_default",
|
||||
status: "FAILED",
|
||||
currentStep: 1,
|
||||
stepCount: 2,
|
||||
error: "Low-confidence match — routed for review",
|
||||
outputs: [{ fileId: "f2", fileName: "patient-intake-0481.pdf" }],
|
||||
createdAt: NOW - 1 * H,
|
||||
},
|
||||
{
|
||||
runId: "run_003",
|
||||
policyId: "pol_security_default",
|
||||
status: "RUNNING",
|
||||
currentStep: 1,
|
||||
stepCount: 2,
|
||||
error: null,
|
||||
outputs: [{ fileId: "f3", fileName: "invoice-7782.pdf" }],
|
||||
createdAt: NOW - 2 * M,
|
||||
},
|
||||
// Older completed runs for stats
|
||||
...Array.from({ length: 4818 }, (_, i) => ({
|
||||
runId: `run_old_${i}`,
|
||||
policyId: "pol_security_default",
|
||||
status: "COMPLETED" as const,
|
||||
currentStep: 2,
|
||||
stepCount: 2,
|
||||
error: null,
|
||||
outputs: [] as { fileId: string; fileName: string }[],
|
||||
createdAt: NOW - (34 * D + i * 10 * M),
|
||||
})),
|
||||
];
|
||||
/** Empty stats/activity for a freshly-configured policy with no runs yet. */
|
||||
export function emptyRuntime(reviewerEmail = "you@acme.com"): PolicyRuntime {
|
||||
return {
|
||||
scopeTypes: [],
|
||||
reviewerEmail,
|
||||
fieldValues: {},
|
||||
stats: { enforced: 0, dataProcessed: "0 B", activeFor: "—" },
|
||||
activity: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -31,16 +31,21 @@
|
||||
|
||||
/* Category grid */
|
||||
.portal-policies__grid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.375rem;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 0.875rem;
|
||||
}
|
||||
|
||||
/* Category card — horizontal table row */
|
||||
@media (max-width: 56rem) {
|
||||
.portal-policies__grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Category card */
|
||||
.portal-policies__card {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
@@ -48,47 +53,10 @@
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.portal-policies__card-identity {
|
||||
.portal-policies__card-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.portal-policies__card-enforces {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-4);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.portal-policies__card-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.portal-policies__card-statpair {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.0625rem;
|
||||
}
|
||||
|
||||
.portal-policies__card-statval {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.portal-policies__card-statlbl {
|
||||
font-size: 0.6875rem;
|
||||
color: var(--color-text-4);
|
||||
line-height: 1.2;
|
||||
align-items: flex-start;
|
||||
gap: 0.625rem;
|
||||
}
|
||||
|
||||
.portal-policies__cat-icon {
|
||||
@@ -98,8 +66,41 @@
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
flex-shrink: 0;
|
||||
font-size: 1.125rem;
|
||||
color: var(--color-text-2);
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.portal-policies__cat-icon--neutral {
|
||||
background: var(--color-bg-subtle);
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
.portal-policies__cat-icon--blue {
|
||||
background: var(--color-blue-light);
|
||||
color: var(--color-blue);
|
||||
}
|
||||
.portal-policies__cat-icon--purple {
|
||||
background: var(--color-purple-light);
|
||||
color: var(--color-purple);
|
||||
}
|
||||
.portal-policies__cat-icon--green {
|
||||
background: var(--color-green-light);
|
||||
color: var(--color-green-dark);
|
||||
}
|
||||
.portal-policies__cat-icon--amber {
|
||||
background: var(--color-amber-light);
|
||||
color: var(--color-amber-dark);
|
||||
}
|
||||
.portal-policies__cat-icon--red {
|
||||
background: var(--color-red-light);
|
||||
color: var(--color-red);
|
||||
}
|
||||
|
||||
.portal-policies__card-titles {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.portal-policies__card-title {
|
||||
@@ -109,6 +110,50 @@
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-policies__card-blurb {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-4);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.portal-policies__card-summary {
|
||||
margin: 0;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.5;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
|
||||
.portal-policies__card-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
margin-top: auto;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.portal-policies__card-rules {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.portal-policies__card-cta {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-blue);
|
||||
}
|
||||
|
||||
/* Configured-card stat footer */
|
||||
.portal-policies__card-stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 0.5rem;
|
||||
margin-top: auto;
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
/* Wizard + detail shared chrome */
|
||||
.portal-policies__wizard-title {
|
||||
display: inline-flex;
|
||||
@@ -151,13 +196,6 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.portal-policies__wizard-subheading {
|
||||
margin: 0.875rem 0 0;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
.portal-policies__fields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -187,6 +225,17 @@
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-policies__tool-endpoint {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: 0.6875rem;
|
||||
color: var(--color-text-4);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Sources picker */
|
||||
.portal-policies__sources {
|
||||
display: grid;
|
||||
@@ -202,12 +251,12 @@
|
||||
|
||||
.portal-policies__source {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
gap: 0.5rem;
|
||||
padding: 0.625rem;
|
||||
text-align: left;
|
||||
background: var(--color-surface);
|
||||
border: 1.5px solid var(--color-border);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
@@ -215,22 +264,6 @@
|
||||
background var(--motion-fast);
|
||||
}
|
||||
|
||||
.portal-policies__source::after {
|
||||
content: "";
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1.5px solid var(--color-border-strong);
|
||||
transition:
|
||||
border-color var(--motion-fast),
|
||||
background var(--motion-fast);
|
||||
}
|
||||
|
||||
.portal-policies__source:hover {
|
||||
background: var(--color-bg-hover);
|
||||
}
|
||||
@@ -240,26 +273,12 @@
|
||||
background: var(--color-blue-light);
|
||||
}
|
||||
|
||||
.portal-policies__source--on::after {
|
||||
content: "✓";
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
border-color: var(--color-blue);
|
||||
background: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-policies__source-icon {
|
||||
font-size: 1rem;
|
||||
line-height: 1.2;
|
||||
flex-shrink: 0;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
.portal-policies__source--on .portal-policies__source-icon {
|
||||
color: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-policies__source-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -319,13 +338,8 @@
|
||||
.portal-policies__detail-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.625rem;
|
||||
}
|
||||
|
||||
.portal-policies__detail-sep {
|
||||
color: var(--color-text-5);
|
||||
font-size: 0.75rem;
|
||||
gap: 0.625rem;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.portal-policies__detail-meta {
|
||||
@@ -333,31 +347,28 @@
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
.portal-policies__enforce-flow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.portal-policies__enforce-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.portal-policies__enforce-arrow {
|
||||
color: var(--color-text-5);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.portal-policies__detail-inline {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.625rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.portal-policies__detail-inline-label {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
.portal-policies__enforce-note {
|
||||
margin: 0.75rem 0 0;
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-4);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
flex-shrink: 0;
|
||||
width: 4.5rem;
|
||||
}
|
||||
|
||||
.portal-policies__detail-inline-value {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-2);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@@ -373,32 +384,22 @@
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-policies__activity-icon {
|
||||
.portal-policies__activity-dot {
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
margin-top: 0.125rem;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
padding-top: 0.125rem;
|
||||
margin-top: 0.375rem;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.portal-policies__activity-icon--success {
|
||||
color: var(--color-green);
|
||||
.portal-policies__activity-dot--success {
|
||||
background: var(--color-green);
|
||||
}
|
||||
.portal-policies__activity-icon--warning {
|
||||
color: var(--color-amber);
|
||||
.portal-policies__activity-dot--warning {
|
||||
background: var(--color-amber);
|
||||
}
|
||||
.portal-policies__activity-icon--info {
|
||||
color: var(--color-blue);
|
||||
}
|
||||
|
||||
@keyframes portal-policies-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.portal-policies__activity-spin {
|
||||
animation: portal-policies-spin 1s linear infinite;
|
||||
.portal-policies__activity-dot--info {
|
||||
background: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-policies__activity-text {
|
||||
@@ -426,29 +427,6 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.portal-policies__activity-retry {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
/* Error expand/collapse for long activity messages */
|
||||
.portal-policies__activity-error {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.portal-policies__activity-error-text--clamped {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.portal-policies__activity-error-toggle {
|
||||
display: block;
|
||||
margin-top: 0.125rem;
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
|
||||
/* Detail stats footer */
|
||||
.portal-policies__detail-stats {
|
||||
display: grid;
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Banner, Button, Skeleton } from "@shared/components";
|
||||
import { errorMessage } from "@portal/api/http";
|
||||
import { Skeleton } from "@shared/components";
|
||||
import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";
|
||||
import {
|
||||
buildWireFromSetup,
|
||||
buildWireFromState,
|
||||
deletePolicy,
|
||||
fetchPolicies,
|
||||
runPolicy,
|
||||
savePolicy,
|
||||
POLICY_CATEGORIES,
|
||||
POLICY_CONFIG,
|
||||
type CatalogueEntry,
|
||||
type PoliciesResponse,
|
||||
type Policy,
|
||||
type PolicySetupResult,
|
||||
} from "@portal/api/policies";
|
||||
import { CatalogueSummary } from "@portal/components/policies/CatalogueSummary";
|
||||
@@ -21,36 +18,51 @@ import { PolicyDetailPanel } from "@portal/components/policies/PolicyDetailPanel
|
||||
import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";
|
||||
import "@portal/views/Policies.css";
|
||||
|
||||
/**
|
||||
* Translate the setup flow's collected result into the backend `Policy` wire
|
||||
* record (Policy.java): the tool chain becomes the ordered pipeline `steps`,
|
||||
* the run event becomes the `trigger`, and the output settings become `output`.
|
||||
* Reuses the existing record's id on edit so the POST updates in place.
|
||||
*/
|
||||
function toWirePolicy(
|
||||
entry: CatalogueEntry,
|
||||
result: PolicySetupResult,
|
||||
): Policy {
|
||||
return {
|
||||
id: entry.policy?.state.backendId ?? "",
|
||||
name: `${entry.category.label} Policy`,
|
||||
enabled: entry.policy ? entry.policy.state.status !== "paused" : true,
|
||||
trigger: { event: result.runOn },
|
||||
sources: result.sources.map((source) => ({ source })),
|
||||
steps: result.steps,
|
||||
output: {
|
||||
mode: result.outputMode,
|
||||
name: result.outputName,
|
||||
namePosition: result.outputNamePosition,
|
||||
},
|
||||
categoryId: entry.category.id,
|
||||
};
|
||||
}
|
||||
|
||||
export function Policies() {
|
||||
const { t } = useTranslation();
|
||||
// The catalogue is refetched after every mutation by bumping this counter,
|
||||
// so the cards/detail reflect the in-memory store the handlers maintain.
|
||||
const [version, setVersion] = useState(0);
|
||||
const state = useAsync<PoliciesResponse>(() => fetchPolicies(), [version]);
|
||||
const { data, loading, error: fetchError } = state;
|
||||
const { data, loading } = state;
|
||||
const { isLoading } = useSectionFlags(state);
|
||||
|
||||
// The category whose detail panel is open (configured), and the one whose
|
||||
// setup wizard is open. Both reference a catalogue entry.
|
||||
const [detail, setDetail] = useState<CatalogueEntry | null>(null);
|
||||
const [wizard, setWizard] = useState<CatalogueEntry | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [pageError, setPageError] = useState<string | null>(null);
|
||||
|
||||
const catalogue = data?.catalogue ?? [];
|
||||
const refetch = useCallback(() => setVersion((v) => v + 1), []);
|
||||
|
||||
const displayCatalogue: CatalogueEntry[] =
|
||||
catalogue.length > 0
|
||||
? catalogue
|
||||
: POLICY_CATEGORIES.map((cat) => ({
|
||||
category: cat,
|
||||
config: POLICY_CONFIG[cat.id] ?? {
|
||||
summary: "",
|
||||
rules: [],
|
||||
scopeLabel: "",
|
||||
fields: [],
|
||||
defaultOperations: [],
|
||||
},
|
||||
policy: null,
|
||||
}));
|
||||
|
||||
// Open the detail panel for configured categories, the wizard otherwise.
|
||||
function openEntry(entry: CatalogueEntry) {
|
||||
if (entry.policy) setDetail(entry);
|
||||
else setWizard(entry);
|
||||
@@ -60,39 +72,50 @@ export function Policies() {
|
||||
entry: CatalogueEntry,
|
||||
result: PolicySetupResult,
|
||||
) {
|
||||
setPageError(null);
|
||||
try {
|
||||
await savePolicy(buildWireFromSetup(entry, result));
|
||||
setWizard(null);
|
||||
setDetail(null);
|
||||
refetch();
|
||||
} catch (e) {
|
||||
setPageError(errorMessage(e));
|
||||
}
|
||||
await savePolicy(toWirePolicy(entry, result));
|
||||
setWizard(null);
|
||||
setDetail(null);
|
||||
refetch();
|
||||
}
|
||||
|
||||
async function runLifecycle(action: () => Promise<unknown>) {
|
||||
if (busy) return;
|
||||
setPageError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await action();
|
||||
setDetail(null);
|
||||
refetch();
|
||||
} catch (e) {
|
||||
setPageError(errorMessage(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleRun() {
|
||||
const id = detail?.policy?.state.backendId;
|
||||
if (id) void runLifecycle(() => runPolicy(id));
|
||||
}
|
||||
|
||||
function handleTogglePause() {
|
||||
const entry = detail;
|
||||
const policy = entry?.policy;
|
||||
if (!entry || !policy?.state.backendId) return;
|
||||
const enabled = policy.state.status === "paused";
|
||||
// Pause/resume is a re-save with the enabled flag flipped (the backend has
|
||||
// no dedicated endpoint — every mutation routes through POST /policies).
|
||||
void runLifecycle(() =>
|
||||
savePolicy(buildWireFromState(entry, policy, enabled)),
|
||||
savePolicy({
|
||||
id: policy.state.backendId!,
|
||||
name: `${entry.category.label} Policy`,
|
||||
enabled: policy.state.status === "paused",
|
||||
trigger: { event: policy.state.runOn ?? "upload" },
|
||||
sources: policy.state.sources.map((source) => ({ source })),
|
||||
steps: policy.steps,
|
||||
output: {
|
||||
mode: policy.state.outputMode ?? "new_version",
|
||||
name: policy.state.outputName ?? "",
|
||||
namePosition: "suffix",
|
||||
},
|
||||
categoryId: entry.category.id,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -101,6 +124,7 @@ export function Policies() {
|
||||
if (id) void runLifecycle(() => deletePolicy(id));
|
||||
}
|
||||
|
||||
// Reopen the wizard for the policy currently shown in the detail panel.
|
||||
function handleEdit() {
|
||||
if (detail) {
|
||||
setWizard(detail);
|
||||
@@ -115,34 +139,19 @@ export function Policies() {
|
||||
<p className="portal-policies__sub">{t("policies.subtitle")}</p>
|
||||
</header>
|
||||
|
||||
{pageError && <Banner tone="danger" description={pageError} />}
|
||||
|
||||
<CatalogueSummary data={data} loading={loading} />
|
||||
|
||||
{isLoading && (
|
||||
<div className="portal-policies__grid" aria-hidden>
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Skeleton key={i} height="3.5rem" />
|
||||
<Skeleton key={i} height="11rem" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && fetchError && (
|
||||
<Banner
|
||||
tone="warning"
|
||||
title={t("policies.offline.title")}
|
||||
description={t("policies.offline.description")}
|
||||
action={
|
||||
<Button variant="outline" size="sm" onClick={refetch}>
|
||||
{t("policies.offline.retry")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isLoading && !fetchError && (
|
||||
{!isLoading && catalogue.length > 0 && (
|
||||
<div className="portal-policies__grid">
|
||||
{displayCatalogue.map((entry) => (
|
||||
{catalogue.map((entry) => (
|
||||
<PolicyCategoryCard
|
||||
key={entry.category.id}
|
||||
entry={entry}
|
||||
@@ -157,6 +166,7 @@ export function Policies() {
|
||||
busy={busy}
|
||||
onClose={() => setDetail(null)}
|
||||
onEdit={handleEdit}
|
||||
onRun={handleRun}
|
||||
onTogglePause={handleTogglePause}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
|
||||
@@ -23,19 +23,12 @@ export default defineConfig({
|
||||
"@shared": sharedDir,
|
||||
},
|
||||
},
|
||||
server: {
|
||||
fs: {
|
||||
// Allow Vite to serve files from the shared/ sibling directory when
|
||||
// running tests with --root portal (which would otherwise block them).
|
||||
allow: [".."],
|
||||
},
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: "jsdom",
|
||||
setupFiles: ["./src/setupTests.ts"],
|
||||
css: false,
|
||||
include: ["src/**/*.test.{ts,tsx}", "../shared/**/*.test.ts"],
|
||||
include: ["src/**/*.test.{ts,tsx}"],
|
||||
testTimeout: 10000,
|
||||
hookTimeout: 10000,
|
||||
},
|
||||
|
||||
@@ -12,7 +12,6 @@ export const AuthContext = createContext<AuthContextValue>({
|
||||
displayName: null,
|
||||
isAnonymous: false,
|
||||
isAdmin: false,
|
||||
portalAccess: false,
|
||||
role: null,
|
||||
loading: true,
|
||||
error: null,
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
// Renders children only for a user with portal access; otherwise calls onForbidden.
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { useAuth } from "@shared/auth/context";
|
||||
|
||||
export interface RequirePortalAccessProps {
|
||||
children: ReactNode;
|
||||
/** Rendered when there is no session (e.g. the login panel). */
|
||||
fallback: ReactNode;
|
||||
/** Invoked once when an authenticated user without portal access is detected. */
|
||||
onForbidden: () => void;
|
||||
/** Rendered while the session is still resolving. */
|
||||
loading?: ReactNode;
|
||||
/** Rendered for an authenticated user without portal access. */
|
||||
forbidden?: ReactNode;
|
||||
}
|
||||
|
||||
export function RequirePortalAccess({
|
||||
children,
|
||||
fallback,
|
||||
onForbidden,
|
||||
loading = null,
|
||||
forbidden = null,
|
||||
}: RequirePortalAccessProps) {
|
||||
const { session, loading: isLoading, portalAccess } = useAuth();
|
||||
|
||||
const shouldRedirect = !isLoading && !!session && !portalAccess;
|
||||
useEffect(() => {
|
||||
if (shouldRedirect) onForbidden();
|
||||
}, [shouldRedirect, onForbidden]);
|
||||
|
||||
if (isLoading) return <>{loading}</>;
|
||||
if (!session) return <>{fallback}</>;
|
||||
if (!portalAccess) return <>{forbidden}</>;
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -28,10 +28,6 @@ export {
|
||||
RequireAdmin,
|
||||
type RequireAdminProps,
|
||||
} from "@shared/auth/guards/RequireAdmin";
|
||||
export {
|
||||
RequirePortalAccess,
|
||||
type RequirePortalAccessProps,
|
||||
} from "@shared/auth/guards/RequirePortalAccess";
|
||||
|
||||
// Spring backend
|
||||
export {
|
||||
|
||||
@@ -195,7 +195,6 @@ export function SpringAuthProvider({
|
||||
displayName: deriveDisplayName(user, translate),
|
||||
isAnonymous: user?.is_anonymous === true,
|
||||
isAdmin: isAdminRole(user?.role),
|
||||
portalAccess: user?.portalAccess ?? isAdminRole(user?.role),
|
||||
role: user?.role ?? null,
|
||||
loading,
|
||||
error,
|
||||
|
||||
@@ -148,7 +148,6 @@ export function SupabaseAuthProvider({
|
||||
displayName: deriveDisplayName(user, translate),
|
||||
isAnonymous: user?.is_anonymous === true,
|
||||
isAdmin: isAdminRole(user?.role),
|
||||
portalAccess: user?.portalAccess ?? isAdminRole(user?.role),
|
||||
role: user?.role ?? null,
|
||||
loading,
|
||||
error,
|
||||
|
||||
@@ -16,8 +16,6 @@ export interface AuthUser {
|
||||
is_anonymous?: boolean;
|
||||
isFirstLogin?: boolean;
|
||||
authenticationType?: string;
|
||||
/** Whether the backend grants this user portal/processor access. */
|
||||
portalAccess?: boolean;
|
||||
app_metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -60,8 +58,6 @@ export interface AuthContextValue {
|
||||
isAnonymous: boolean;
|
||||
/** True when the current user holds an admin role. */
|
||||
isAdmin: boolean;
|
||||
/** True when the user may access the portal/processor (admins + ACL grants). */
|
||||
portalAccess: boolean;
|
||||
/** Raw backend role string, or null when signed out. */
|
||||
role: string | null;
|
||||
loading: boolean;
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { toWirePolicy, fromWirePolicy } from "@shared/policies/codec";
|
||||
import type { PolicyDecodedState } from "@shared/policies/types";
|
||||
|
||||
const FULL_STATE: PolicyDecodedState = {
|
||||
id: "pol_123",
|
||||
name: "Security Policy",
|
||||
enabled: true,
|
||||
categoryId: "security",
|
||||
sources: ["editor", "gdrive"],
|
||||
scopeTypes: ["Contracts", "Invoices"],
|
||||
reviewerEmail: "admin@example.com",
|
||||
fieldValues: { auditTrail: true, frameworks: ["HIPAA"] },
|
||||
runOn: "upload",
|
||||
outputMode: "new_version",
|
||||
outputName: "redacted",
|
||||
outputNamePosition: "prefix",
|
||||
maxRetries: 3,
|
||||
retryDelayMinutes: 5,
|
||||
steps: [
|
||||
{
|
||||
operation: "/api/v1/security/auto-redact",
|
||||
parameters: { mode: "automatic" },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("toWirePolicy", () => {
|
||||
it("sets trigger to null", () => {
|
||||
expect(toWirePolicy(FULL_STATE).trigger).toBeNull();
|
||||
});
|
||||
|
||||
it("sets output.type to inline", () => {
|
||||
expect(toWirePolicy(FULL_STATE).output.type).toBe("inline");
|
||||
});
|
||||
|
||||
it("packs metadata into output.options", () => {
|
||||
const wire = toWirePolicy(FULL_STATE);
|
||||
const opts = wire.output.options;
|
||||
expect(opts.categoryId).toBe("security");
|
||||
expect(opts.sources).toEqual(["editor", "gdrive"]);
|
||||
expect(opts.runOn).toBe("upload");
|
||||
expect(opts.mode).toBe("new_version");
|
||||
expect(opts.position).toBe("prefix");
|
||||
});
|
||||
|
||||
it("preserves steps at the top level", () => {
|
||||
const wire = toWirePolicy(FULL_STATE);
|
||||
expect(wire.steps).toEqual(FULL_STATE.steps);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fromWirePolicy → round-trip", () => {
|
||||
it("recovers all fields after encode→decode", () => {
|
||||
const wire = toWirePolicy(FULL_STATE);
|
||||
const decoded = fromWirePolicy(wire);
|
||||
expect(decoded.id).toBe(FULL_STATE.id);
|
||||
expect(decoded.categoryId).toBe(FULL_STATE.categoryId);
|
||||
expect(decoded.sources).toEqual(FULL_STATE.sources);
|
||||
expect(decoded.scopeTypes).toEqual(FULL_STATE.scopeTypes);
|
||||
expect(decoded.reviewerEmail).toBe(FULL_STATE.reviewerEmail);
|
||||
expect(decoded.fieldValues).toEqual(FULL_STATE.fieldValues);
|
||||
expect(decoded.runOn).toBe(FULL_STATE.runOn);
|
||||
expect(decoded.outputMode).toBe(FULL_STATE.outputMode);
|
||||
expect(decoded.outputName).toBe(FULL_STATE.outputName);
|
||||
expect(decoded.outputNamePosition).toBe(FULL_STATE.outputNamePosition);
|
||||
expect(decoded.maxRetries).toBe(FULL_STATE.maxRetries);
|
||||
expect(decoded.retryDelayMinutes).toBe(FULL_STATE.retryDelayMinutes);
|
||||
expect(decoded.steps).toEqual(FULL_STATE.steps);
|
||||
});
|
||||
|
||||
it("defaults runOn to upload when missing", () => {
|
||||
const wire = toWirePolicy(FULL_STATE);
|
||||
delete (wire.output.options as Record<string, unknown>).runOn;
|
||||
expect(fromWirePolicy(wire).runOn).toBe("upload");
|
||||
});
|
||||
|
||||
it("defaults outputMode to new_version when missing", () => {
|
||||
const wire = toWirePolicy(FULL_STATE);
|
||||
delete (wire.output.options as Record<string, unknown>).mode;
|
||||
expect(fromWirePolicy(wire).outputMode).toBe("new_version");
|
||||
});
|
||||
|
||||
it("preserves export runOn", () => {
|
||||
const wire = toWirePolicy({ ...FULL_STATE, runOn: "export" });
|
||||
expect(fromWirePolicy(wire).runOn).toBe("export");
|
||||
});
|
||||
|
||||
it("preserves new_file outputMode", () => {
|
||||
const wire = toWirePolicy({ ...FULL_STATE, outputMode: "new_file" });
|
||||
expect(fromWirePolicy(wire).outputMode).toBe("new_file");
|
||||
});
|
||||
|
||||
it("preserves all three outputNamePosition values", () => {
|
||||
for (const pos of ["prefix", "suffix", "auto-number"] as const) {
|
||||
const wire = toWirePolicy({ ...FULL_STATE, outputNamePosition: pos });
|
||||
expect(fromWirePolicy(wire).outputNamePosition).toBe(pos);
|
||||
}
|
||||
});
|
||||
|
||||
it("handles empty options gracefully", () => {
|
||||
const decoded = fromWirePolicy({
|
||||
id: "x",
|
||||
name: "X",
|
||||
enabled: false,
|
||||
trigger: null,
|
||||
steps: [],
|
||||
output: { type: "inline", options: {} },
|
||||
});
|
||||
expect(decoded.categoryId).toBe("");
|
||||
expect(decoded.sources).toEqual([]);
|
||||
expect(decoded.runOn).toBe("upload");
|
||||
expect(decoded.outputMode).toBe("new_version");
|
||||
});
|
||||
|
||||
it("defaults fieldValues to empty object when missing", () => {
|
||||
const wire = toWirePolicy(FULL_STATE);
|
||||
delete (wire.output.options as Record<string, unknown>).fieldValues;
|
||||
expect(fromWirePolicy(wire).fieldValues).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
/**
|
||||
* Bidirectional codec between the portal's frontend `PolicyDecodedState` and
|
||||
* the backend `WirePolicy`. All policy-level metadata rides in
|
||||
* `output.options`; `trigger` is always null (the editor fires runs on
|
||||
* upload/export via `/run`). Mirrors the editor's `buildBackendPolicy` /
|
||||
* `fromBackendPolicy` from `policyPipeline.ts`, minus the editor-only
|
||||
* `automation` blob and toolRegistry coupling.
|
||||
*/
|
||||
|
||||
import type {
|
||||
PolicyDecodedState,
|
||||
WireOutputOptions,
|
||||
WirePolicy,
|
||||
} from "@shared/policies/types";
|
||||
|
||||
const DEFAULTS = {
|
||||
maxRetries: 3,
|
||||
retryDelayMinutes: 5,
|
||||
} as const;
|
||||
|
||||
export function toWirePolicy(state: PolicyDecodedState): WirePolicy {
|
||||
const options: WireOutputOptions = {
|
||||
runOn: state.runOn,
|
||||
mode: state.outputMode,
|
||||
name: state.outputName,
|
||||
position: state.outputNamePosition,
|
||||
maxRetries: state.maxRetries,
|
||||
retryDelayMinutes: state.retryDelayMinutes,
|
||||
categoryId: state.categoryId,
|
||||
sources: state.sources,
|
||||
scopeTypes: state.scopeTypes,
|
||||
reviewerEmail: state.reviewerEmail,
|
||||
fieldValues: state.fieldValues,
|
||||
};
|
||||
return {
|
||||
id: state.id,
|
||||
name: state.name,
|
||||
owner: "",
|
||||
enabled: state.enabled,
|
||||
trigger: null,
|
||||
steps: state.steps,
|
||||
output: { type: "inline", options },
|
||||
};
|
||||
}
|
||||
|
||||
export function fromWirePolicy(policy: WirePolicy): PolicyDecodedState {
|
||||
const raw = policy.output?.options ?? {};
|
||||
const str = (v: unknown, fallback = "") =>
|
||||
typeof v === "string" ? v : fallback;
|
||||
const num = (v: unknown, fallback: number) =>
|
||||
typeof v === "number" ? v : fallback;
|
||||
const position =
|
||||
raw.position === "suffix"
|
||||
? "suffix"
|
||||
: raw.position === "auto-number"
|
||||
? "auto-number"
|
||||
: "prefix";
|
||||
return {
|
||||
id: policy.id,
|
||||
name: policy.name,
|
||||
enabled: policy.enabled,
|
||||
categoryId: str(raw.categoryId),
|
||||
sources: Array.isArray(raw.sources) ? (raw.sources as string[]) : [],
|
||||
scopeTypes: Array.isArray(raw.scopeTypes)
|
||||
? (raw.scopeTypes as string[])
|
||||
: [],
|
||||
reviewerEmail: str(raw.reviewerEmail),
|
||||
fieldValues: raw.fieldValues ?? {},
|
||||
runOn: raw.runOn === "export" ? "export" : "upload",
|
||||
outputMode: raw.mode === "new_file" ? "new_file" : "new_version",
|
||||
outputName: str(raw.name),
|
||||
outputNamePosition: position,
|
||||
maxRetries: num(raw.maxRetries, DEFAULTS.maxRetries),
|
||||
retryDelayMinutes: num(raw.retryDelayMinutes, DEFAULTS.retryDelayMinutes),
|
||||
steps: Array.isArray(policy.steps) ? policy.steps : [],
|
||||
};
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { runsToStats, runsToActivity } from "@shared/policies/runs";
|
||||
import type { PolicyRunView } from "@shared/policies/types";
|
||||
|
||||
const MIN = 60000;
|
||||
const HOUR = 3600000;
|
||||
const DAY = 86400000;
|
||||
// Use the actual current time so relative-time formatting in runs.ts is correct.
|
||||
const NOW = Date.now();
|
||||
|
||||
const completed = (
|
||||
id: string,
|
||||
ts: number,
|
||||
file = "doc.pdf",
|
||||
): PolicyRunView => ({
|
||||
runId: id,
|
||||
policyId: "pol_1",
|
||||
status: "COMPLETED",
|
||||
currentStep: 2,
|
||||
stepCount: 2,
|
||||
error: null,
|
||||
outputs: [{ fileId: "f", fileName: file }],
|
||||
createdAt: ts,
|
||||
});
|
||||
|
||||
const failed = (
|
||||
id: string,
|
||||
ts: number,
|
||||
err = "Redaction failed",
|
||||
): PolicyRunView => ({
|
||||
runId: id,
|
||||
policyId: "pol_1",
|
||||
status: "FAILED",
|
||||
currentStep: 1,
|
||||
stepCount: 2,
|
||||
error: err,
|
||||
outputs: [],
|
||||
createdAt: ts,
|
||||
});
|
||||
|
||||
const running = (id: string, ts: number, step = 1): PolicyRunView => ({
|
||||
runId: id,
|
||||
policyId: "pol_1",
|
||||
status: "RUNNING",
|
||||
currentStep: step,
|
||||
stepCount: 2,
|
||||
error: null,
|
||||
outputs: [],
|
||||
createdAt: ts,
|
||||
});
|
||||
|
||||
describe("runsToStats", () => {
|
||||
it("counts only COMPLETED runs as enforced", () => {
|
||||
const runs: PolicyRunView[] = [
|
||||
completed("a", NOW - 10 * MIN),
|
||||
completed("b", NOW - 20 * MIN),
|
||||
failed("c", NOW - 30 * MIN),
|
||||
running("d", NOW - 5 * MIN),
|
||||
];
|
||||
expect(runsToStats(runs).enforced).toBe(2);
|
||||
});
|
||||
|
||||
it("returns — for dataProcessed (not available from wire)", () => {
|
||||
expect(runsToStats([completed("a", NOW - MIN)]).dataProcessed).toBe("—");
|
||||
});
|
||||
|
||||
it("returns — for activeFor when there are no runs", () => {
|
||||
expect(runsToStats([]).activeFor).toBe("—");
|
||||
});
|
||||
|
||||
it("computes activeFor from the oldest run", () => {
|
||||
const runs = [completed("a", NOW - 2 * DAY), completed("b", NOW - 5 * DAY)];
|
||||
expect(runsToStats(runs).activeFor).toBe("5d");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runsToActivity", () => {
|
||||
it("maps COMPLETED to enforced status", () => {
|
||||
const [row] = runsToActivity([
|
||||
completed("a", NOW - 10 * MIN, "invoice.pdf"),
|
||||
]);
|
||||
expect(row.status).toBe("enforced");
|
||||
expect(row.doc).toBe("invoice.pdf");
|
||||
});
|
||||
|
||||
it("maps FAILED to flagged status with the error message", () => {
|
||||
const [row] = runsToActivity([failed("b", NOW - HOUR, "Low confidence")]);
|
||||
expect(row.status).toBe("flagged");
|
||||
expect(row.action).toBe("Low confidence");
|
||||
});
|
||||
|
||||
it("maps RUNNING to processing status", () => {
|
||||
const [row] = runsToActivity([running("c", NOW - MIN)]);
|
||||
expect(row.status).toBe("processing");
|
||||
});
|
||||
|
||||
it("maps CANCELLED to flagged status", () => {
|
||||
const run: PolicyRunView = {
|
||||
...failed("x", NOW - MIN, "Cancelled by user"),
|
||||
status: "CANCELLED",
|
||||
};
|
||||
expect(runsToActivity([run])[0].status).toBe("flagged");
|
||||
});
|
||||
|
||||
it("maps PENDING to processing status", () => {
|
||||
const run: PolicyRunView = {
|
||||
...running("x", NOW - MIN),
|
||||
status: "PENDING",
|
||||
};
|
||||
expect(runsToActivity([run])[0].status).toBe("processing");
|
||||
});
|
||||
|
||||
it("maps WAITING_FOR_INPUT to processing status", () => {
|
||||
const run: PolicyRunView = {
|
||||
...running("x", NOW - MIN),
|
||||
status: "WAITING_FOR_INPUT",
|
||||
};
|
||||
expect(runsToActivity([run])[0].status).toBe("processing");
|
||||
});
|
||||
|
||||
it("falls back to 'Enforcement failed' when FAILED run has no error message", () => {
|
||||
const run: PolicyRunView = { ...failed("x", NOW - MIN), error: null };
|
||||
expect(runsToActivity([run])[0].action).toBe("Enforcement failed");
|
||||
});
|
||||
|
||||
it("shows step progress when currentStep and stepCount are set", () => {
|
||||
const [row] = runsToActivity([running("c", NOW - MIN, 1)]);
|
||||
expect(row.action).toContain("step 1/2");
|
||||
});
|
||||
|
||||
it("falls back to Policy run when outputs is empty", () => {
|
||||
const noOutput: PolicyRunView = { ...running("x", NOW - MIN), outputs: [] };
|
||||
expect(runsToActivity([noOutput])[0].doc).toBe("Policy run");
|
||||
});
|
||||
|
||||
it("formats recent timestamps as Nm ago", () => {
|
||||
const [row] = runsToActivity([completed("a", NOW - 5 * MIN)]);
|
||||
expect(row.time).toBe("5m ago");
|
||||
});
|
||||
|
||||
it("formats hour-range timestamps as Nh ago", () => {
|
||||
const [row] = runsToActivity([completed("a", NOW - 2 * HOUR)]);
|
||||
expect(row.time).toBe("2h ago");
|
||||
});
|
||||
|
||||
it("formats day-range timestamps as Nd ago", () => {
|
||||
const [row] = runsToActivity([completed("a", NOW - 3 * DAY)]);
|
||||
expect(row.time).toBe("3d ago");
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
/**
|
||||
* Derives display data from raw backend `PolicyRunView` records. The backend
|
||||
* `GET /api/v1/policies/runs` endpoint returns these; both the portal and
|
||||
* (eventually) the editor read this same derivation rather than duplicating it.
|
||||
*/
|
||||
|
||||
import type {
|
||||
PolicyActivityItem,
|
||||
PolicyRunView,
|
||||
PolicyStats,
|
||||
} from "@shared/policies/types";
|
||||
|
||||
function relativeTime(epochMs: number): string {
|
||||
if (!epochMs) return "Just now";
|
||||
const mins = Math.floor((Date.now() - epochMs) / 60000);
|
||||
if (mins < 1) return "Just now";
|
||||
if (mins < 60) return `${mins}m ago`;
|
||||
const hrs = Math.floor(mins / 60);
|
||||
if (hrs < 24) return `${hrs}h ago`;
|
||||
return `${Math.floor(hrs / 24)}d ago`;
|
||||
}
|
||||
|
||||
function durationSince(epochMs: number): string {
|
||||
if (!epochMs) return "—";
|
||||
const ms = Date.now() - epochMs;
|
||||
const days = Math.floor(ms / 86400000);
|
||||
if (days >= 1) return `${days}d`;
|
||||
const hrs = Math.floor(ms / 3600000);
|
||||
return hrs >= 1 ? `${hrs}h` : "Today";
|
||||
}
|
||||
|
||||
function activityStatus(run: PolicyRunView): PolicyActivityItem["status"] {
|
||||
if (run.status === "COMPLETED") return "enforced";
|
||||
if (run.status === "FAILED" || run.status === "CANCELLED") return "flagged";
|
||||
return "processing";
|
||||
}
|
||||
|
||||
function activityAction(run: PolicyRunView): string {
|
||||
const s = activityStatus(run);
|
||||
if (s === "enforced") return "Enforced";
|
||||
if (s === "flagged") return run.error ?? "Enforcement failed";
|
||||
const { currentStep, stepCount } = run;
|
||||
return currentStep && stepCount
|
||||
? `Enforcing… · step ${currentStep}/${stepCount}`
|
||||
: "Enforcing…";
|
||||
}
|
||||
|
||||
export function runsToActivity(runs: PolicyRunView[]): PolicyActivityItem[] {
|
||||
return runs.map((run) => ({
|
||||
doc: run.outputs[0]?.fileName ?? "Policy run",
|
||||
action: activityAction(run),
|
||||
time: relativeTime(run.createdAt),
|
||||
status: activityStatus(run),
|
||||
}));
|
||||
}
|
||||
|
||||
export function runsToStats(runs: PolicyRunView[]): PolicyStats {
|
||||
const completed = runs.filter((r) => r.status === "COMPLETED");
|
||||
const oldest = runs.reduce((min, r) => Math.min(min, r.createdAt), Infinity);
|
||||
return {
|
||||
enforced: completed.length,
|
||||
dataProcessed: "—",
|
||||
activeFor: isFinite(oldest) ? durationSince(oldest) : "—",
|
||||
};
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
/**
|
||||
* Wire types for the Stirling policy API (`/api/v1/policies`), the decoded
|
||||
* frontend shape, and the display types used to render stats and activity.
|
||||
*
|
||||
* The backend stores all portal-level metadata (categoryId, sources, scope,
|
||||
* reviewer, fieldValues, runOn, output settings) inside `output.options` — the
|
||||
* same "options bag" the editor uses. `trigger` is always null for
|
||||
* portal/editor-authored policies; the editor fires runs on upload/export via
|
||||
* `/run`, so there is no server-side trigger.
|
||||
*/
|
||||
|
||||
// ── Wire types (match Policy.java / PipelineStep.java / PolicyRunView.java) ──
|
||||
|
||||
export interface WirePipelineStep {
|
||||
operation: string;
|
||||
parameters: Record<string, unknown>;
|
||||
fileParameters?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface WireOutputOptions {
|
||||
runOn: "upload" | "export";
|
||||
mode: "new_file" | "new_version";
|
||||
name: string;
|
||||
position: "prefix" | "suffix" | "auto-number";
|
||||
maxRetries?: number;
|
||||
retryDelayMinutes?: number;
|
||||
categoryId: string;
|
||||
sources: string[];
|
||||
scopeTypes: string[];
|
||||
reviewerEmail: string;
|
||||
fieldValues: Record<string, boolean | string | string[]>;
|
||||
}
|
||||
|
||||
export interface WireOutputSpec {
|
||||
type: "inline";
|
||||
options: Partial<WireOutputOptions>;
|
||||
}
|
||||
|
||||
export interface WirePolicy {
|
||||
id: string;
|
||||
name: string;
|
||||
owner?: string;
|
||||
enabled: boolean;
|
||||
trigger: null;
|
||||
steps: WirePipelineStep[];
|
||||
output: WireOutputSpec;
|
||||
teamId?: string;
|
||||
}
|
||||
|
||||
// ── Run view (mirrors PolicyRunView.java) ─────────────────────────────────────
|
||||
|
||||
export type PolicyRunStatus =
|
||||
| "PENDING"
|
||||
| "RUNNING"
|
||||
| "WAITING_FOR_INPUT"
|
||||
| "COMPLETED"
|
||||
| "FAILED"
|
||||
| "CANCELLED";
|
||||
|
||||
export interface PolicyRunView {
|
||||
runId: string;
|
||||
policyId: string | null;
|
||||
status: PolicyRunStatus;
|
||||
currentStep: number;
|
||||
stepCount: number;
|
||||
error: string | null;
|
||||
errorCode?: string | null;
|
||||
errorSubscribed?: boolean | null;
|
||||
outputs: { fileId: string; fileName: string }[];
|
||||
/** Creation timestamp in epoch milliseconds. */
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
// ── Frontend decoded shape ────────────────────────────────────────────────────
|
||||
|
||||
/** Policy settings unpacked from the wire record's `output.options` bag. */
|
||||
export interface PolicyDecodedState {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
categoryId: string;
|
||||
sources: string[];
|
||||
scopeTypes: string[];
|
||||
reviewerEmail: string;
|
||||
fieldValues: Record<string, boolean | string | string[]>;
|
||||
runOn: "upload" | "export";
|
||||
outputMode: "new_file" | "new_version";
|
||||
outputName: string;
|
||||
outputNamePosition: "prefix" | "suffix" | "auto-number";
|
||||
maxRetries: number;
|
||||
retryDelayMinutes: number;
|
||||
steps: WirePipelineStep[];
|
||||
}
|
||||
|
||||
// ── Display types (returned by runs.ts derivations) ───────────────────────────
|
||||
|
||||
export interface PolicyStats {
|
||||
/** Completed enforcement runs. */
|
||||
enforced: number;
|
||||
/** Human-formatted total data processed (e.g. "2.3 GB"), or "—" when unknown. */
|
||||
dataProcessed: string;
|
||||
/** Human-formatted duration since first run (e.g. "34d"), or "—". */
|
||||
activeFor: string;
|
||||
}
|
||||
|
||||
export interface PolicyActivityItem {
|
||||
doc: string;
|
||||
action: string;
|
||||
/** Relative timestamp, e.g. "2h ago". */
|
||||
time: string;
|
||||
status: "enforced" | "flagged" | "processing";
|
||||
}
|
||||
+11
-11
@@ -1,24 +1,24 @@
|
||||
# Prints one free TCP port per preferred port given as an argument.
|
||||
#
|
||||
# For each element of -Preferred, emits that port if it's free; otherwise
|
||||
# emits a random free port in 20000-49999. Uses Get-NetTCPConnection to read
|
||||
# the OS socket table directly — more reliable than TcpListener binding on
|
||||
# Windows where SO_REUSEADDR can cause false "free" results. Tracks picks
|
||||
# within this run so outputs are guaranteed distinct from each other.
|
||||
# emits a random free port in 20000-49999. Probes by attempting to bind a
|
||||
# TcpListener on loopback. Tracks picks within this run so outputs are
|
||||
# guaranteed distinct from each other.
|
||||
param([Parameter(ValueFromRemainingArguments = $true)][int[]]$Preferred)
|
||||
|
||||
$script:picked = @()
|
||||
|
||||
# Build a set of ports currently in LISTEN or ESTABLISHED state once upfront.
|
||||
$usedPorts = [System.Collections.Generic.HashSet[int]]::new()
|
||||
Get-NetTCPConnection -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.State -in 'Listen', 'Established' } |
|
||||
ForEach-Object { $null = $usedPorts.Add($_.LocalPort) }
|
||||
|
||||
function Test-PortFree {
|
||||
param([int]$Port)
|
||||
if ($script:picked -contains $Port) { return $false }
|
||||
return -not $usedPorts.Contains($Port)
|
||||
try {
|
||||
$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, $Port)
|
||||
$listener.Start()
|
||||
$listener.Stop()
|
||||
return $true
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RandomFreePort {
|
||||
|
||||
Reference in New Issue
Block a user