Repository Public License
1import Foundation2import Testing3@testable import FlowEngine45@Suite struct FlowValidationTests {6 @Test func everyBuiltInExampleValidatesAndFormatsToItself() throws {7 #expect(FlowEngine.examples.count >= 4)8 #expect(Set(FlowEngine.examples.map(\.id)).count == FlowEngine.examples.count)9 for example in FlowEngine.examples {10 let compilation = FlowCompiler.compile(example.source)11 #expect(compilation.diagnostics.isEmpty, "\(example.id): \(compilation.diagnostics)")12 let program = try #require(compilation.validated)13 #expect(program.name == example.title)14 #expect(program.worstCaseSteps <= program.limits.maximumSteps)15 #expect(FlowFormatter.format(source: example.source) == example.source, "\(example.id) is not in canonical format")16 }17 }1819 static let prelude = "flow \"x\" version 1\nallow domains \"example.org\"\n"2021 @Test(arguments: [22 ("let a = b", "undefined-name"),23 ("let a = 1\nlet a = 2", "duplicate-name"),24 ("let for = 1", "reserved-name"),25 ("let steps = 1", "reserved-name"),26 ("open \"https://example.org\" as flow", "reserved-name"),27 ("let a = 1\nif a { notify \"x\" }", "type-mismatch"),28 ("if 1 > \"a\" { notify \"x\" }", "type-mismatch"),29 ("if \"a\" == 1 { notify \"x\" }", "type-mismatch"),30 ("if not 3 { notify \"x\" }", "type-mismatch"),31 ("if true and 3 { notify \"x\" }", "type-mismatch"),32 ("for x in 5 limit 2 { notify \"x\" }", "type-mismatch"),33 ("let a = [1, \"two\"]", "type-mismatch"),34 ("open 5", "type-mismatch"),35 ("let t = \"https://example.org\"\nopen t", "type-mismatch"),36 ("notify \"a\" as result", "no-result"),37 ("open \"https://example.org\" as p\nextract article p", "unexpected-argument"),38 ("open \"https://example.org\" as p\nextract article", "missing-argument"),39 ("open \"https://example.org\" as p\nextract article from p from p", "duplicate-argument"),40 ("let r = \"text\"\nexport r as pdf to downloads", "invalid-option"),41 ("let r = \"text\"\nexport r as markdown to desktop", "invalid-option"),42 ("let r = \"text\"\nsummarize r with footnotes", "invalid-option"),43 ("open \"https://example.org\" as p\nlet a = p.body", "unknown-member"),44 ("let a = 1\nlet b = a.title", "unknown-member"),45 ("let a = shout(\"x\")", "unknown-function"),46 ("let a = count()", "wrong-argument-count"),47 ("let a = count(1, 2)", "wrong-argument-count"),48 ("let a = count(5)", "type-mismatch"),49 ("let a = join([1, 2], \",\")", "type-mismatch"),50 ("let a = first(\"text\")", "type-mismatch"),51 ("let a = \"{items}\"\ncollect 1 into items", "type-mismatch"),52 ("collect 1 into items\ncollect \"a\" into items", "type-mismatch"),53 ("let items = 1\ncollect 2 into items", "duplicate-name"),54 ("for x in [1] limit 0 { notify \"x\" }", "loop-limit-out-of-range"),55 ("for x in [1] limit 101 { notify \"x\" }", "loop-limit-out-of-range"),56 ("for x in [1] limit 5 parallel 9 { notify \"x\" }", "parallel-width-out-of-range"),57 ("parallel limit 0 { notify \"x\" }", "parallel-width-out-of-range"),58 ("parallel limit 9 { notify \"x\" }", "parallel-width-out-of-range"),59 ("wait 61s", "limit-out-of-range"),60 ("wait 5", "type-mismatch"),61 ("open \"ftp://example.org/file\"", "invalid-url"),62 ("open \"javascript:alert(1)\"", "invalid-url"),63 ("open \"file:///etc/passwd\"", "invalid-url"),64 ("open \"data:text/html,<script>\"", "invalid-url"),65 ("open \"example.org/page\"", "invalid-url"),66 ("open \"https://\"", "invalid-url"),67 ("open \"https://user:pw@example.org/\"", "invalid-url"),68 ("open \"https://example.org:port/\"", "invalid-url"),69 ("open \"https://evil.test/\"", "domain-not-allowed"),70 ("open \"https://example.org.evil.test/\"", "domain-not-allowed"),71 ("open \"https://notexample.org/\"", "domain-not-allowed"),72 ("download \"https://evil.test/a.zip\"", "domain-not-allowed"),73 ("let h = \"evil.test\"\nopen \"https://{h}/\"", "dynamic-host"),74 ("let h = \"evil.test\"\nopen \"https://example.org.{h}/\"", "dynamic-host"),75 ("let h = \"x\"\nopen \"{h}\"", "dynamic-host"),76 ("let u = url(\"https://evil.test/\")", "domain-not-allowed"),77 ("if url(\"https://example.org\") == \"https://evil.test\" { notify \"x\" }", "domain-not-allowed"),78 ] as [(String, String)])79 func invalidProgramsAreRejected(body: String, code: String) {80 let compilation = FlowCompiler.compile(Self.prelude + body)81 #expect(compilation.errors.contains { $0.code == code }, "expected \(code), got \(compilation.errors.map(\.description)) for: \(body)")82 #expect(compilation.validated == nil)83 #expect(compilation.errors.allSatisfy { $0.hint?.isEmpty == false })84 }8586 @Test(arguments: [87 ("flow \"x\" version 2\nnotify \"a\"", "unsupported-version"),88 ("flow \"x\" version 1\nopen \"https://example.org\"", "missing-allow-domains"),89 ("flow \"x\" version 1\nparam u: text\nopen url(u)", "missing-allow-domains"),90 ("flow \"x\" version 1\nallow domains \"com\"\nnotify \"a\"", "invalid-domain"),91 ("flow \"x\" version 1\nallow domains \"https://example.org\"\nnotify \"a\"", "invalid-domain"),92 ("flow \"x\" version 1\nallow domains \"*.example.org\"\nnotify \"a\"", "invalid-domain"),93 ("flow \"x\" version 1\nallow domains \"exa mple.org\"\nnotify \"a\"", "invalid-domain"),94 ("flow \"x\" version 1\nallow domains \"10.0.0.1\"\nnotify \"a\"", "invalid-domain"),95 ("flow \"x\" version 1\nallow domains \"\"\nnotify \"a\"", "invalid-domain"),96 ("flow \"x\" version 1\nlimit steps 501\nnotify \"a\"", "limit-out-of-range"),97 ("flow \"x\" version 1\nlimit steps 0\nnotify \"a\"", "limit-out-of-range"),98 ("flow \"x\" version 1\nlimit duration 2h\nnotify \"a\"", "invalid-unit"),99 ("flow \"x\" version 1\nlimit duration 61m\nnotify \"a\"", "limit-out-of-range"),100 ("flow \"x\" version 1\nlimit timeout 301s\nnotify \"a\"", "limit-out-of-range"),101 ("flow \"x\" version 1\nlimit steps 5\nlimit steps 6\nnotify \"a\"", "duplicate-limit"),102 ("flow \"x\" version 1\nparam a: list\nnotify \"a\"", "unknown-type"),103 ("flow \"x\" version 1\nparam a: number = \"five\"\nnotify \"a\"", "invalid-default"),104 ("flow \"x\" version 1\nparam a: text\nparam a: text\nnotify \"a\"", "duplicate-name"),105 ("flow \"x\" version 1\nparam a: text = \"{a}\"\nnotify \"a\"", "invalid-default"),106 ("flow \"x\" version 1\nallow domains \"example.org\"\nparam u: url = \"https://evil.test/\"\nnotify \"a\"", "domain-not-allowed"),107 ] as [(String, String)])108 func invalidHeadersAreRejected(source: String, code: String) {109 let compilation = FlowCompiler.compile(source)110 #expect(compilation.errors.contains { $0.code == code }, "expected \(code), got \(compilation.errors.map(\.description))")111 #expect(compilation.validated == nil)112 }113114 @Test func thereIsNoWayToDefineOrLoadCode() {115 // None of these constructs exists in the grammar; each is a syntax or name error, never something that runs.116 let attempts = ["func helper() { notify \"x\" }", "def f: notify \"x\"", "import \"https://example.org/lib.flow\"",117 "include \"other\"", "eval \"notify 1\"", "run \"script.js\"", "let f = notify", "let a = helper()",118 "let a = js(\"alert(1)\")", "load \"https://example.org/code\"", "while true { notify \"x\" }",119 "loop { notify \"x\" }", "goto start", "call me", "let a = [notify]"]120 for attempt in attempts {121 let compilation = FlowCompiler.compile(Self.prelude + attempt)122 #expect(compilation.validated == nil, "\(attempt) must not validate")123 }124 // A workflow cannot name itself or another workflow: there is no such action in the registry.125 #expect(FlowActionRegistry.standard.names.allSatisfy { !$0.contains("flow") && !$0.contains("run") && !$0.contains("eval") })126 #expect(FlowActionRegistry.standard.names == ["ask", "bookmark", "click", "close", "download", "export", "extract article", "extract links",127 "extract text", "fill", "notify", "open", "save note", "submit", "summarize", "wait"])128 }129130 @Test func aCollectionCanBeReadBeforeTheStatementThatFillsIt() throws {131 let program = try validated(Self.prelude + """132 for n in [1, 2, 3] limit 3 {133 if count(seen) < 2 { collect n into seen }134 }135 let total = count(seen)136 """)137 #expect(program.collections == ["seen": .list(.number)])138 }139140 @Test func scopesEndWithTheirBlock() {141 #expect(codes(Self.prelude + "for n in [1] limit 1 { let inner = n }\nlet a = inner").contains("undefined-name"))142 #expect(codes(Self.prelude + "if true { let inner = 1 }\nlet a = inner").contains("undefined-name"))143 #expect(codes(Self.prelude + "for n in [1] limit 1 { notify \"x\" }\nlet a = n").contains("undefined-name"))144 #expect(codes(Self.prelude + "let a = 1\nif true { let a = 2 }").contains("duplicate-name"))145 #expect(codes(Self.prelude + "for n in [1] limit 1 { let v = n }\nfor n in [2] limit 1 { let v = n }").isEmpty)146 }147148 @Test func parallelBranchesCannotSeeEachOtherButTheirResultsOutliveTheBlock() throws {149 let program = try validated(Self.prelude + """150 parallel limit 2 {151 open "https://example.org/a" as a152 open "https://example.org/b" as b153 }154 extract article from a as first155 extract article from b as second156 """)157 #expect(program.worstCaseSteps == 4)158 #expect(codes(Self.prelude + "parallel limit 2 {\nopen \"https://example.org/a\" as a\nextract article from a as b\n}").contains("undefined-name"))159 #expect(codes(Self.prelude + "parallel limit 2 {\nopen \"https://example.org/a\" as a\nopen \"https://example.org/b\" as a\n}").contains("duplicate-name"))160 let many = (0..<17).map { "notify \"\($0)\"" }.joined(separator: "\n")161 #expect(codes(Self.prelude + "parallel limit 2 {\n\(many)\n}").contains("too-many-branches"))162 }163164 @Test func worstCaseStepsMultiplyLoopLimitsAndWarnWhenOverBudget() throws {165 let compilation = FlowCompiler.compile(Self.prelude + """166 limit steps 20167 for a in [1, 2] limit 10 {168 for b in [1, 2] limit 4 { notify "x" }169 if a > 1 { notify "y"; notify "z" } else { notify "w" }170 }171 """)172 let program = try #require(compilation.validated)173 #expect(program.worstCaseSteps == 10 * (4 + 2))174 #expect(compilation.warnings.map(\.code) == ["step-budget"])175 #expect(FlowCompiler.compile("flow \"x\" version 1").warnings.map(\.code) == ["empty-flow"])176 #expect(FlowCompiler.compile("flow \"x\" version 1\nallow domains \"a.org\", \"A.org\"\nnotify \"x\"").warnings.map(\.code) == ["duplicate-domain"])177 }178179 @Test func defaultsApplyWhenNoLimitIsDeclared() throws {180 let program = try validated("flow \"x\" version 1\nnotify \"a\"")181 #expect(program.limits == FlowLimits(maximumSteps: 50, maximumDurationSeconds: 300, stepTimeoutSeconds: 30))182 #expect(program.policy.domains.isEmpty)183 }184185 @Test func domainPolicyMatchesHostsAndSubdomainsOnly() {186 let policy = FlowDomainPolicy(domains: ["Example.org", "wikipedia.org"])187 let allowed = ["https://example.org", "http://example.org/a?b#c", "https://www.example.org:8443/x", "https://a.b.example.org/",188 "https://EXAMPLE.ORG/", "https://en.wikipedia.org/wiki/Swift", "https://example.org./"]189 let refused = ["https://example.org.evil.test/", "https://evil.test/example.org", "https://notexample.org/", "https://example.orgx/",190 "ftp://example.org/", "file:///example.org", "javascript:alert(1)", "https://user@example.org/", "https://user:pw@example.org/",191 "https://evil.test/?u=https://example.org", "https://evil.test#example.org", "data:text/html,example.org", "//example.org/x", "example.org"]192 for text in allowed { #expect(policy.allows(URL(string: text)!), "\(text)") }193 for text in refused { #expect(!(URL(string: text).map(policy.allows) ?? false), "\(text)") }194 #expect(!FlowDomainPolicy(domains: []).allows(URL(string: "https://example.org")!))195 #expect(FlowDomainPolicy.problem(with: "localhost") == nil && FlowDomainPolicy.problem(with: "xn--bcher-kva.example") == nil)196 }197198 @Test func registryAcceptsWellFormedActionsAndRejectsAmbiguousOnes() throws {199 let translate = FlowActionDefinition(name: "translate", summary: "Translate text.",200 parameters: [FlowParameter("content", label: nil, .value([.text])),201 FlowParameter("language", label: "into_language", .option(["french", "english"]))],202 result: .text, capability: .ai)203 let registry = try FlowActionRegistry.standard.adding([translate])204 let program = try validated("flow \"x\" version 1\ntranslate \"hello\" into_language french as t\nnotify t", registry: registry)205 #expect(program.capabilities == [.ai, .notify])206 #expect(translate.signature == "translate <text> into_language french|english → text")207 // The standard registry does not know it.208 #expect(codes("flow \"x\" version 1\ntranslate \"hello\" into_language french as t").contains("unknown-action"))209 func rejected(_ definition: FlowActionDefinition) -> Bool { (try? FlowActionRegistry.standard.adding([definition])) == nil }210 #expect(rejected(FlowActionDefinition(name: "open", summary: "", capability: .navigate)))211 #expect(rejected(FlowActionDefinition(name: "wait", summary: "", capability: .notify)))212 #expect(rejected(FlowActionDefinition(name: "extract", summary: "", capability: .read)))213 #expect(rejected(FlowActionDefinition(name: "open tab", summary: "", capability: .navigate)))214 #expect(rejected(FlowActionDefinition(name: "for", summary: "", capability: .notify)))215 #expect(rejected(FlowActionDefinition(name: "Shout", summary: "", capability: .notify)))216 #expect(rejected(FlowActionDefinition(name: "a b c", summary: "", capability: .notify)))217 #expect(rejected(FlowActionDefinition(name: "run-script", summary: "", capability: .notify)))218 #expect(rejected(FlowActionDefinition(name: "ping", summary: "", capability: nil)))219 #expect(rejected(FlowActionDefinition(name: "ping", summary: "", parameters: [FlowParameter("a", label: nil, .value([.text])), FlowParameter("b", label: nil, .value([.text]))], capability: .notify)))220 #expect(rejected(FlowActionDefinition(name: "ping", summary: "", parameters: [FlowParameter("a", label: "in", .value([.text]))], capability: .notify)))221 #expect(rejected(FlowActionDefinition(name: "ping", summary: "", parameters: [FlowParameter("a", label: "to", .value([]))], capability: .notify)))222 #expect(rejected(FlowActionDefinition(name: "ping", summary: "", parameters: [FlowParameter("a", label: "as", .option(["x"]))], result: .text, capability: .notify)))223 }224225 @Test func standardActionsDeclareCapabilitiesAndConfirmations() {226 let registry = FlowActionRegistry.standard227 #expect(registry.definition(named: "open")?.capability == .navigate)228 #expect(registry.definition(named: "extract article")?.capability == .read)229 #expect(registry.definition(named: "summarize")?.capability == .ai)230 #expect(registry.definition(named: "export")?.capability == .writeFile)231 #expect(registry.definition(named: "wait")?.capability == nil)232 let confirming = registry.names.filter { registry.definition(named: $0)?.confirmation == .always }233 #expect(confirming == ["click", "download", "submit"])234 #expect(registry.definition(named: "submit")?.capability == .submitForm)235 }236}237