Repository Public License
1// ORIX Secure2// File: Packages/ORIXReporting/Sources/ORIXWorkflow/WorkflowDefinition.swift3// Description: The description of an ORIX Secure Actions workflow: step kinds, steps, definitions, and the validation rules4// that make a destructive step impossible to define without a confirmation gate and a prior review.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureModel1011/// The kind of work a step does. An open set: the app registers a handler per kind.12public struct WorkflowStepKind: RawRepresentable, Hashable, Codable, Sendable, ExpressibleByStringLiteral, CustomStringConvertible {13 public var rawValue: String14 public init(rawValue: String) { self.rawValue = rawValue }15 public init(_ rawValue: String) { self.rawValue = rawValue }16 public init(stringLiteral value: String) { self.rawValue = value }17 public var description: String { rawValue }1819 public static let securityAssessment: WorkflowStepKind = "security.assessment"20 public static let storageOverview: WorkflowStepKind = "storage.overview"21 public static let photosScan: WorkflowStepKind = "photos.scan"22 public static let photosReview: WorkflowStepKind = "photos.review"23 public static let photosDelete: WorkflowStepKind = "photos.delete"24 public static let networkDiagnostics: WorkflowStepKind = "network.diagnostics"25 public static let urlInspect: WorkflowStepKind = "url.inspect"26 public static let checklistReview: WorkflowStepKind = "checklist.review"27 public static let reportGenerate: WorkflowStepKind = "report.generate"28}2930public struct WorkflowStep: Identifiable, Hashable, Codable, Sendable {31 public var id: UUID32 public var kind: WorkflowStepKind33 public var title: String34 public var parameters: [String: String]35 /// The runner asks the user before running the step.36 public var requiresConfirmation: Bool37 /// The step deletes or changes user data. Must have `requiresConfirmation`.38 public var isDestructive: Bool39 /// The workflow goes on to the next step when this one fails.40 public var continueOnFailure: Bool41 /// When the user declines the confirmation, the rest of the workflow is not run (default) or goes on.42 public var stopsWorkflowWhenDeclined: Bool43 /// Seconds after which the step is cancelled and marked failed. `nil` means no limit.44 public var timeout: TimeInterval?4546 public init(47 id: UUID = UUID(),48 kind: WorkflowStepKind,49 title: String,50 parameters: [String: String] = [:],51 requiresConfirmation: Bool = false,52 isDestructive: Bool = false,53 continueOnFailure: Bool = false,54 stopsWorkflowWhenDeclined: Bool = true,55 timeout: TimeInterval? = nil56 ) {57 self.id = id58 self.kind = kind59 self.title = title60 self.parameters = parameters61 self.requiresConfirmation = requiresConfirmation62 self.isDestructive = isDestructive63 self.continueOnFailure = continueOnFailure64 self.stopsWorkflowWhenDeclined = stopsWorkflowWhenDeclined65 self.timeout = timeout66 }6768 private enum CodingKeys: String, CodingKey {69 case id, kind, title, parameters, requiresConfirmation, isDestructive, continueOnFailure, stopsWorkflowWhenDeclined, timeout70 }7172 public init(from decoder: Decoder) throws {73 let container = try decoder.container(keyedBy: CodingKeys.self)74 id = try container.decode(UUID.self, forKey: .id)75 kind = try container.decode(WorkflowStepKind.self, forKey: .kind)76 title = try container.decode(String.self, forKey: .title)77 parameters = try container.decodeIfPresent([String: String].self, forKey: .parameters) ?? [:]78 // Safety flags have no permissive default: a file that omits them is rejected rather than guessed.79 requiresConfirmation = try container.decode(Bool.self, forKey: .requiresConfirmation)80 isDestructive = try container.decode(Bool.self, forKey: .isDestructive)81 continueOnFailure = try container.decodeIfPresent(Bool.self, forKey: .continueOnFailure) ?? false82 stopsWorkflowWhenDeclined = try container.decodeIfPresent(Bool.self, forKey: .stopsWorkflowWhenDeclined) ?? true83 timeout = try container.decodeIfPresent(TimeInterval.self, forKey: .timeout)84 }8586 /// The rules a step must satisfy on its own.87 public func validate(rules: WorkflowRules = .standard) throws {88 if kind.rawValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { throw WorkflowValidationError.emptyStepKind(stepTitle: title) }89 if title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { throw WorkflowValidationError.emptyStepTitle(kind: kind) }90 if rules.destructiveKinds.contains(kind), !isDestructive { throw WorkflowValidationError.destructiveKindNotFlagged(stepTitle: title, kind: kind) }91 if isDestructive, !requiresConfirmation { throw WorkflowValidationError.destructiveWithoutConfirmation(stepTitle: title) }92 if let timeout, !(timeout.isFinite && timeout > 0) { throw WorkflowValidationError.invalidTimeout(stepTitle: title) }93 }94}9596/// What the app declares about step kinds: which ones are destructive and which review must come first.97public struct WorkflowRules: Sendable, Hashable {98 /// Kinds that delete or change user data whatever the step says about itself.99 public var destructiveKinds: Set<WorkflowStepKind>100 /// For a destructive kind, the review kind that must appear earlier in the workflow (and succeed at run time).101 public var requiredPredecessors: [WorkflowStepKind: WorkflowStepKind]102 public var maximumStepCount: Int103104 public init(destructiveKinds: Set<WorkflowStepKind> = [], requiredPredecessors: [WorkflowStepKind: WorkflowStepKind] = [:], maximumStepCount: Int = 24) {105 self.destructiveKinds = destructiveKinds106 self.requiredPredecessors = requiredPredecessors107 self.maximumStepCount = maximumStepCount108 }109110 /// The rules of the built-in kinds: deleting photos is destructive and needs a photo review first.111 public static let standard = WorkflowRules(destructiveKinds: [.photosDelete], requiredPredecessors: [.photosDelete: .photosReview])112}113114public enum WorkflowValidationError: Error, Sendable, Equatable, LocalizedError {115 case emptyName116 case noSteps117 case tooManySteps(count: Int, maximum: Int)118 case duplicateStepIdentifier(stepTitle: String)119 case emptyStepTitle(kind: WorkflowStepKind)120 case emptyStepKind(stepTitle: String)121 case invalidTimeout(stepTitle: String)122 case destructiveWithoutConfirmation(stepTitle: String)123 case destructiveKindNotFlagged(stepTitle: String, kind: WorkflowStepKind)124 case destructiveWithoutDeclaredReview(stepTitle: String, kind: WorkflowStepKind)125 case missingReviewPredecessor(stepTitle: String, required: WorkflowStepKind)126127 public var errorDescription: String? {128 switch self {129 case .emptyName: L("The workflow needs a name.")130 case .noSteps: L("The workflow has no step.")131 case .tooManySteps(let count, let maximum): L("The workflow has \(count) steps; the maximum is \(maximum).")132 case .duplicateStepIdentifier(let title): L("The step “\(title)” appears twice with the same identifier.")133 case .emptyStepTitle(let kind): L("A step of kind “\(kind.rawValue)” has no title.")134 case .emptyStepKind(let title): L("The step “\(title)” has no kind.")135 case .invalidTimeout(let title): L("The time limit of the step “\(title)” is not valid.")136 case .destructiveWithoutConfirmation(let title): L("The step “\(title)” deletes or changes data and must ask for confirmation.")137 case .destructiveKindNotFlagged(let title, let kind): L("The step “\(title)” (\(kind.rawValue)) deletes or changes data and must be marked as such.")138 case .destructiveWithoutDeclaredReview(let title, let kind): L("The step “\(title)” (\(kind.rawValue)) deletes or changes data, but no review step is declared for this kind.")139 case .missingReviewPredecessor(let title, let required): L("The step “\(title)” must come after a review step (\(required.rawValue)).")140 }141 }142}143144public extension CodingUserInfoKey {145 /// Put a `WorkflowRules` value under this key to decode definitions against rules other than `.standard`.146 static let workflowRules = CodingUserInfoKey(rawValue: "ai.spboucher.orix.secure.workflowRules")147}148149/// A workflow. Immutable and validated on creation and on decoding, so an instance always satisfies the rules it was150/// built with; the runner validates it again against the rules of its own registry.151public struct WorkflowDefinition: Identifiable, Hashable, Codable, Sendable {152 public let id: UUID153 public let name: String154 public let summary: String155 /// SF Symbol name.156 public let systemImage: String157 public let steps: [WorkflowStep]158 public let isBuiltIn: Bool159160 public init(id: UUID = UUID(), name: String, summary: String, systemImage: String = "bolt.shield", steps: [WorkflowStep], isBuiltIn: Bool = false, rules: WorkflowRules = .standard) throws {161 self.init(unchecked: id, name: name, summary: summary, systemImage: systemImage, steps: steps, isBuiltIn: isBuiltIn)162 try validate(rules: rules)163 }164165 /// For the built-in library only; the test suite validates every built-in definition.166 init(unchecked id: UUID, name: String, summary: String, systemImage: String, steps: [WorkflowStep], isBuiltIn: Bool) {167 self.id = id168 self.name = name169 self.summary = summary170 self.systemImage = systemImage171 self.steps = steps172 self.isBuiltIn = isBuiltIn173 }174175 private enum CodingKeys: String, CodingKey {176 case id, name, summary, systemImage, steps, isBuiltIn177 }178179 public init(from decoder: Decoder) throws {180 let container = try decoder.container(keyedBy: CodingKeys.self)181 id = try container.decode(UUID.self, forKey: .id)182 name = try container.decode(String.self, forKey: .name)183 summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? ""184 systemImage = try container.decodeIfPresent(String.self, forKey: .systemImage) ?? "bolt.shield"185 steps = try container.decode([WorkflowStep].self, forKey: .steps)186 isBuiltIn = try container.decodeIfPresent(Bool.self, forKey: .isBuiltIn) ?? false187 let rules = (CodingUserInfoKey.workflowRules.flatMap { decoder.userInfo[$0] } as? WorkflowRules) ?? .standard188 do {189 try validate(rules: rules)190 } catch {191 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Invalid workflow definition: \(error.localizedDescription)", underlyingError: error))192 }193 }194195 public func validate(rules: WorkflowRules = .standard) throws {196 if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { throw WorkflowValidationError.emptyName }197 if steps.isEmpty { throw WorkflowValidationError.noSteps }198 if steps.count > rules.maximumStepCount { throw WorkflowValidationError.tooManySteps(count: steps.count, maximum: rules.maximumStepCount) }199 var seen = Set<UUID>()200 var earlierKinds = Set<WorkflowStepKind>()201 for step in steps {202 if !seen.insert(step.id).inserted { throw WorkflowValidationError.duplicateStepIdentifier(stepTitle: step.title) }203 try step.validate(rules: rules)204 if step.isDestructive {205 guard let required = rules.requiredPredecessors[step.kind] else {206 throw WorkflowValidationError.destructiveWithoutDeclaredReview(stepTitle: step.title, kind: step.kind)207 }208 if !earlierKinds.contains(required) { throw WorkflowValidationError.missingReviewPredecessor(stepTitle: step.title, required: required) }209 }210 earlierKinds.insert(step.kind)211 }212 }213214 /// A validated copy with some fields replaced (definitions are immutable).215 public func updating(name: String? = nil, summary: String? = nil, systemImage: String? = nil, steps: [WorkflowStep]? = nil, rules: WorkflowRules = .standard) throws -> WorkflowDefinition {216 try WorkflowDefinition(id: id, name: name ?? self.name, summary: summary ?? self.summary, systemImage: systemImage ?? self.systemImage, steps: steps ?? self.steps, isBuiltIn: isBuiltIn, rules: rules)217 }218219 /// An editable user copy of a definition (new identifiers, not built-in).220 public func duplicated(name: String, rules: WorkflowRules = .standard) throws -> WorkflowDefinition {221 let copies = steps.map { step in222 var copy = step223 copy.id = UUID()224 return copy225 }226 return try WorkflowDefinition(name: name, summary: summary, systemImage: systemImage, steps: copies, isBuiltIn: false, rules: rules)227 }228}229