diff --git a/docs/services/codepipeline.md b/docs/services/codepipeline.md index 9fcee353ec..c7bd07de4a 100644 --- a/docs/services/codepipeline.md +++ b/docs/services/codepipeline.md @@ -72,6 +72,12 @@ as `Approved` or `Rejected`, limits `result.summary` to 512 characters, returns `InvalidApprovalTokenException` for unknown tokens, and returns `ApprovalAlreadyCompletedException` if the same approval token is reused after completion. +## V2 stage conditions + +V2 stage condition blocks (`beforeEntry` and `onSuccess`) are evaluated during execution. Two rule providers evaluate for real: **LambdaInvoke** (invokes the configured local Lambda function; the rule passes when the invocation succeeds) and **VariableCheck** (compares a `#{variables.name}` reference with `EQ`, `NE`, `CONTAINS`, or `MATCHES`; `MATCHES` rejects a pattern or value longer than 256 characters). `Commands`, `DeploymentWindow` and `CloudWatchAlarm` rules are accepted but pass permissively. A `VariableCheck` reference resolves against the start request's variables and the pipeline's declared defaults; a reference that cannot be resolved (including action output variables) fails the rule. Every rule run is recorded on the execution and returned by `ListRuleExecutions`; `ListRuleTypes` returns the AWS rule catalog. + +A failed `beforeEntry` or `onSuccess` condition applies its declared `result`: `FAIL` (the default) stops the execution, and `SKIP` skips the stage when it is on a `beforeEntry` condition. A failed `onSuccess` condition always fails the stage, because the stage has already run. `OverrideStageCondition` marks the condition overridden and, when the execution failed on exactly that condition, resumes it from the overridden stage. `onFailure` conditions and the `ROLLBACK` result are not acted on; a stage failure is recorded as a plain failure. + ## Events and notifications Executions publish the real `aws.codepipeline` state-change events to the **default diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java index 09484faea2..55d8ed631a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java +++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineService.java @@ -66,6 +66,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; import java.util.zip.CRC32; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; @@ -121,8 +122,14 @@ public class CodePipelineService { private final Map runtimeArtifacts = new ConcurrentHashMap<>(); // An execution's status turns Failed as soon as one action fails, while its runner is still waiting // on sibling actions. Retries check this set so they never overlap a runner that has not finished. - private final Set activeRuns = ConcurrentHashMap.newKeySet(); + final Set activeRuns = ConcurrentHashMap.newKeySet(); private final long sourcePollIntervalMs; + // Test hooks, set only through the package-private constructor: a shortened wait, and a probe + // for the gap before the override timeout cleanup. + private final long runFinishWaitNanos; + private final Runnable beforeOverrideTimeoutCleanup; + + private static final long DEFAULT_RUN_FINISH_WAIT_NANOS = TimeUnit.SECONDS.toNanos(5); /** Matches the {@code source-poll-interval-ms} default in application.yml. */ private static final long DEFAULT_SOURCE_POLL_INTERVAL_MS = 500L; @@ -135,7 +142,8 @@ public class CodePipelineService { CodeBuildService codeBuildService, CodeDeployService codeDeployService, LambdaService lambdaService, S3Service s3Service) { this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service, - detachedEventPublisher(mapper), DEFAULT_SOURCE_POLL_INTERVAL_MS); + detachedEventPublisher(mapper), DEFAULT_SOURCE_POLL_INTERVAL_MS, + DEFAULT_RUN_FINISH_WAIT_NANOS, () -> { }); } public CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper, @@ -153,7 +161,8 @@ public class CodePipelineService { EmulatorConfig config, CodePipelineEventPublisher eventPublisher) { this(storageFactory, mapper, codeBuildService, codeDeployService, lambdaService, s3Service, eventPublisher, - resolveSourcePollInterval(config.services().codepipeline().sourcePollIntervalMs())); + resolveSourcePollInterval(config.services().codepipeline().sourcePollIntervalMs()), + DEFAULT_RUN_FINISH_WAIT_NANOS, () -> { }); } /** @@ -179,10 +188,11 @@ public class CodePipelineService { } @SuppressWarnings("unchecked") - private CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper, - CodeBuildService codeBuildService, CodeDeployService codeDeployService, - LambdaService lambdaService, S3Service s3Service, - CodePipelineEventPublisher eventPublisher, long sourcePollIntervalMs) { + CodePipelineService(StorageFactory storageFactory, ObjectMapper mapper, + CodeBuildService codeBuildService, CodeDeployService codeDeployService, + LambdaService lambdaService, S3Service s3Service, + CodePipelineEventPublisher eventPublisher, long sourcePollIntervalMs, + long runFinishWaitNanos, Runnable beforeOverrideTimeoutCleanup) { this.pipelineStore = storageFactory.create( "codepipeline", "codepipeline-pipelines.json", new TypeReference>() {}); this.executionStore = storageFactory.create( @@ -196,6 +206,8 @@ public class CodePipelineService { this.s3Service = s3Service; this.eventPublisher = eventPublisher; this.sourcePollIntervalMs = sourcePollIntervalMs; + this.runFinishWaitNanos = runFinishWaitNanos; + this.beforeOverrideTimeoutCleanup = beforeOverrideTimeoutCleanup; } public JsonNode handle(String action, JsonNode request, String region, String account) { @@ -224,7 +236,7 @@ public class CodePipelineService { case "GetActionType" -> getActionType(request, region, account); case "DeleteCustomActionType" -> deleteCustomActionType(request, region, account); case "ListActionTypes" -> listActionTypes(request, region, account); - case "ListRuleTypes" -> emptyPage("ruleTypes"); + case "ListRuleTypes" -> listRuleTypes(); case "PollForJobs" -> pollForJobs(request, region, account, false); case "PollForThirdPartyJobs" -> pollForJobs(request, region, account, true); case "AcknowledgeJob", "AcknowledgeThirdPartyJob" -> acknowledgeJob(request, region, account); @@ -568,7 +580,7 @@ public class CodePipelineService { execution.setLastUpdateTime(execution.getStartTime()); execution.setSourceRevisions(new ArrayList<>()); execution.setSourceRevisionOverrides(sourceRevisionOverrides(request, pipeline)); - execution.setVariables(variableList(request.path("variables"))); + execution.setVariables(variableList(request.path("variables"), pipeline.getDeclaration().path("variables"))); Map trigger = new LinkedHashMap<>(); trigger.put("triggerType", triggerType); trigger.put("triggerDetail", triggerDetail); @@ -590,9 +602,7 @@ public class CodePipelineService { execution.setLastUpdateTime(now()); putExecution(execution); eventPublisher.pipelineStateChange(execution, "FAILED"); - throw new AwsException("ConflictException", - "Your request cannot be handled because the pipeline is busy handling ongoing activities. " - + "Try again later.", 400); + throw pipelineBusy(); } return mapper.createObjectNode().put("pipelineExecutionId", execution.getPipelineExecutionId()); } @@ -875,13 +885,17 @@ public class CodePipelineService { execution.setStatusSummary("Stage retry could not be scheduled."); execution.setLastUpdateTime(now()); putExecution(execution); - throw new AwsException("ConflictException", - "Your request cannot be handled because the pipeline is busy handling ongoing activities. " - + "Try again later.", 400); + throw pipelineBusy(); } return mapper.createObjectNode().put("pipelineExecutionId", executionId); } + private static AwsException pipelineBusy() { + return new AwsException("ConflictException", + "Your request cannot be handled because the pipeline is busy handling ongoing activities. " + + "Try again later.", 400); + } + // Runs under startLocks so two concurrent retries cannot both pass the status checks, // and so a retry counts against the same active-execution cap StartPipelineExecution enforces. private Map admitRetry(CodePipelinePipeline pipeline, CodePipelineExecution execution, @@ -959,13 +973,195 @@ public class CodePipelineService { } private ObjectNode overrideStageCondition(JsonNode request, String region, String account) { - requireExecution(account, region, text(request, "pipelineName"), text(request, "pipelineExecutionId")); + String pipelineName = text(request, "pipelineName"); + String stageName = text(request, "stageName"); + String conditionType = text(request, "conditionType"); + if (!"BEFORE_ENTRY".equals(conditionType) && !"ON_SUCCESS".equals(conditionType)) { + throw new AwsException("ValidationException", + "conditionType must be BEFORE_ENTRY or ON_SUCCESS", 400); + } + CodePipelinePipeline pipeline = requirePipeline(account, region, pipelineName); + JsonNode stage = stageByName(pipeline, stageName); + CodePipelineExecution execution = requireExecution( + account, region, pipelineName, text(request, "pipelineExecutionId")); + if (!Objects.equals(execution.getPipelineVersion(), pipeline.getVersion())) { + throw new AwsException("ConditionNotOverridableException", + "The pipeline structure changed after this execution started", 400); + } + // A run that failed on this very condition resumes from the overridden stage, skipping the + // stage's already-succeeded actions; admission shares the retry path's lock and run tracking. + // The run marks itself Failed slightly before it leaves activeRuns; an override landing in that + // window waits (outside the lock, which finishExecutionRun needs) for the run to finish, so it + // resumes instead of storing a flag nothing will read. + String conditionFailedSummary = "Condition " + conditionType + " failed in stage " + stageName + "."; + boolean[] runStillFinishing = new boolean[1]; + Map resumed = null; + long finishDeadline = System.nanoTime() + runFinishWaitNanos; + do { + runStillFinishing[0] = false; + resumed = startLocks.withLock(lockKey(execution), () -> { + synchronized (execution) { + execution.getConditionOverrides().put(stageName + "/" + conditionType, true); + } + boolean failedOnThisCondition = "Failed".equals(execution.getStatus()) + && conditionFailedSummary.equals(execution.getStatusSummary()); + if (failedOnThisCondition && activeRuns.contains(runKey(execution))) { + runStillFinishing[0] = true; + return null; + } + if (!failedOnThisCondition) { + putExecution(execution); + return null; + } + execution.setStatus("InProgress"); + execution.setStatusSummary("Condition " + conditionType + " overridden in stage " + + stageName + "."); + execution.setStopRequested(false); + execution.setAbandon(false); + execution.setLastUpdateTime(now()); + putExecution(execution); + activeRuns.add(runKey(execution)); + return latestActionStatuses(execution, stageName); + }); + if (runStillFinishing[0]) { + try { + TimeUnit.MILLISECONDS.sleep(10); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + } while (runStillFinishing[0] && System.nanoTime() - finishDeadline < 0); + if (runStillFinishing[0]) { + beforeOverrideTimeoutCleanup.run(); + // Another override may have resumed the run since this waiter's last check; clear the flag + // only under the resume lock and only while the run is still failed on this condition. + startLocks.withLock(lockKey(execution), () -> { + synchronized (execution) { + if ("Failed".equals(execution.getStatus()) + && conditionFailedSummary.equals(execution.getStatusSummary())) { + execution.getConditionOverrides().remove(stageName + "/" + conditionType); + putExecution(execution); + } + } + return null; + }); + throw pipelineBusy(); + } + Map resumeStatuses = resumed; + if (resumeStatuses != null) { + try { + executor.submit(() -> runRetriedStage(pipeline, execution, stage, "FAILED_ACTIONS", + resumeStatuses)); + } catch (RejectedExecutionException exception) { + activeRuns.remove(runKey(execution)); + execution.setStatus("Failed"); + execution.setStatusSummary("Stage resume could not be scheduled."); + execution.setLastUpdateTime(now()); + putExecution(execution); + throw pipelineBusy(); + } + } return mapper.createObjectNode(); } private ObjectNode listRuleExecutions(JsonNode request, String region, String account) { - requirePipeline(account, region, text(request, "pipelineName")); - return emptyPage("ruleExecutionDetails"); + String pipelineName = text(request, "pipelineName"); + requirePipeline(account, region, pipelineName); + String executionFilter = request.path("filter").path("pipelineExecutionId").asText(null); + List details = new ArrayList<>(); + for (CodePipelineExecution execution : executions(account, region, pipelineName)) { + if (executionFilter != null + && !executionFilter.equals(execution.getPipelineExecutionId())) { + continue; + } + List> ruleSnapshot = new ArrayList<>(); + synchronized (execution) { + for (Map rule : execution.getRuleExecutions()) { + ruleSnapshot.add(new LinkedHashMap<>(rule)); + } + } + for (Map rule : ruleSnapshot) { + ObjectNode detail = mapper.createObjectNode(); + detail.put("pipelineExecutionId", execution.getPipelineExecutionId()); + detail.put("ruleExecutionId", Objects.toString(rule.get("ruleExecutionId"), null)); + if (execution.getPipelineVersion() != null) { + detail.put("pipelineVersion", execution.getPipelineVersion()); + } + detail.put("stageName", Objects.toString(rule.get("stageName"), null)); + detail.put("ruleName", Objects.toString(rule.get("ruleName"), null)); + detail.put("status", Objects.toString(rule.get("status"), null)); + if (rule.get("startTime") instanceof Number start) { + detail.put("startTime", start.doubleValue()); + } + if (rule.get("lastUpdateTime") instanceof Number updated) { + detail.put("lastUpdateTime", updated.doubleValue()); + } + ObjectNode input = detail.putObject("input"); + input.putObject("ruleTypeId") + .put("category", "Rule") + .put("owner", "AWS") + .put("provider", Objects.toString(rule.get("ruleProvider"), "")) + .put("version", "1"); + detail.putObject("output").putObject("executionResult") + .put("externalExecutionSummary", Objects.toString(rule.get("summary"), "")); + details.add(detail); + } + } + Page page = page(request, details.size(), 100); + ObjectNode response = mapper.createObjectNode(); + ArrayNode array = response.putArray("ruleExecutionDetails"); + for (int i = page.start(); i < page.end(); i++) { + array.add(details.get(i)); + } + addNextToken(response, page, details.size()); + return response; + } + + /** The AWS-owned rule types available for V2 stage conditions. */ + private ObjectNode listRuleTypes() { + ObjectNode response = mapper.createObjectNode(); + ArrayNode ruleTypes = response.putArray("ruleTypes"); + ruleTypes.add(ruleTypeNode("LambdaInvoke", + "Invokes a Lambda function and passes when the invocation succeeds", + List.of("FunctionName"))); + ruleTypes.add(ruleTypeNode("VariableCheck", + "Compares a pipeline variable against a value with EQ, NE, CONTAINS or MATCHES", + List.of("Variable", "Value", "Operator"))); + ruleTypes.add(ruleTypeNode("Commands", + "Runs shell commands (accepted but not evaluated by the emulator)", + List.of("Commands"))); + ruleTypes.add(ruleTypeNode("DeploymentWindow", + "Restricts deployments to a time window (accepted but not evaluated by the emulator)", + List.of("Cron", "TimeZone"))); + ruleTypes.add(ruleTypeNode("CloudWatchAlarm", + "Passes when a CloudWatch alarm is in the expected state (accepted but not evaluated by the emulator)", + List.of("AlarmName", "AlarmStates"))); + return response; + } + + private ObjectNode ruleTypeNode(String provider, String description, List properties) { + ObjectNode node = mapper.createObjectNode(); + node.putObject("id") + .put("category", "Rule") + .put("owner", "AWS") + .put("provider", provider) + .put("version", "1"); + ObjectNode settings = node.putObject("settings"); + settings.put("thirdPartyConfigurationUrl", ""); + ArrayNode props = node.putArray("ruleConfigurationProperties"); + for (String property : properties) { + props.addObject() + .put("name", property) + .put("required", true) + .put("key", true) + .put("secret", false) + .put("description", description); + } + node.putObject("inputArtifactDetails") + .put("minimumCount", 0) + .put("maximumCount", 1); + return node; } private ObjectNode createCustomActionType(JsonNode request, String region, String account) { @@ -1200,22 +1396,9 @@ public class CodePipelineService { String stageName = stage.path("name").asText(); try { int stageIndex = stageIndex(pipeline, stageName); - execution.setCurrentStage(stageName); - execution.getStageExecutionStatuses().put(stageName, "InProgress"); - execution.setLastUpdateTime(now()); - putExecution(execution); - runStage(pipeline, execution, stage, retryMode, previousStatuses); - if ("Failed".equals(execution.getStatus())) { - execution.getStageExecutionStatuses().put(stageName, "Failed"); + if (!runStageInRun(pipeline, execution, stage, retryMode, previousStatuses)) { return; } - if (finishIfStopped(execution)) { - return; - } - execution.getStageExecutionStatuses().put(stageName, "Succeeded"); - execution.setCurrentStage(null); - execution.setLastUpdateTime(now()); - putExecution(execution); runStagesFrom(pipeline, execution, stageIndex + 1); } catch (Exception e) { if (execution.getCurrentStage() != null) { @@ -1239,31 +1422,261 @@ public class CodePipelineService { if (finishIfStopped(execution)) { return; } - execution.setCurrentStage(stageName); - execution.getStageExecutionStatuses().put(stageName, "InProgress"); - execution.setLastUpdateTime(now()); - putExecution(execution); - eventPublisher.stageStateChange(execution, stageName, "STARTED"); - runStage(pipeline, execution, stage); - if ("Failed".equals(execution.getStatus())) { - execution.getStageExecutionStatuses().put(stageName, "Failed"); - eventPublisher.stageStateChange(execution, stageName, "FAILED"); + if (!runStageInRun(pipeline, execution, stage, "ALL_ACTIONS", Map.of())) { return; } - if (finishIfStopped(execution)) { - eventPublisher.stageStateChange(execution, stageName, "STOPPED"); - return; - } - execution.getStageExecutionStatuses().put(stageName, "Succeeded"); - execution.setCurrentStage(null); - execution.setLastUpdateTime(now()); - putExecution(execution); - eventPublisher.stageStateChange(execution, stageName, "SUCCEEDED"); } execution.setStatus("Succeeded"); execution.setStatusSummary("Pipeline execution succeeded."); } + /** + * Runs one stage of an execution, between its V2 {@code beforeEntry} and {@code onSuccess} + * conditions. + * + * @return {@code false} when the execution must not continue to the next stage + */ + private boolean runStageInRun(CodePipelinePipeline pipeline, CodePipelineExecution execution, JsonNode stage, + String retryMode, Map previousStatuses) { + String stageName = stage.path("name").asText(); + execution.setCurrentStage(stageName); + execution.getStageExecutionStatuses().put(stageName, "InProgress"); + execution.setLastUpdateTime(now()); + putExecution(execution); + + // Evaluated before STARTED is published: AWS documents no skipped-stage event, so a stage + // skipped by its beforeEntry condition emits no stage events at all. + ConditionOutcome entry = evaluateConditions(execution, stage, "BEFORE_ENTRY"); + if (entry == ConditionOutcome.SKIP_STAGE) { + execution.getStageExecutionStatuses().put(stageName, "Skipped"); + execution.setCurrentStage(null); + execution.setLastUpdateTime(now()); + putExecution(execution); + return true; + } + eventPublisher.stageStateChange(execution, stageName, "STARTED"); + if (entry == ConditionOutcome.FAIL) { + failForCondition(execution, stageName, "BEFORE_ENTRY"); + execution.getStageExecutionStatuses().put(stageName, "Failed"); + eventPublisher.stageStateChange(execution, stageName, "FAILED"); + return false; + } + + runStage(pipeline, execution, stage, retryMode, previousStatuses); + if ("Failed".equals(execution.getStatus())) { + execution.getStageExecutionStatuses().put(stageName, "Failed"); + eventPublisher.stageStateChange(execution, stageName, "FAILED"); + return false; + } + if (finishIfStopped(execution)) { + eventPublisher.stageStateChange(execution, stageName, "STOPPED"); + return false; + } + + // A SKIP result only makes sense before entry; after the stage ran it cannot be skipped, so a + // failed onSuccess condition fails the stage whatever its declared result. + if (evaluateConditions(execution, stage, "ON_SUCCESS") != ConditionOutcome.PASS) { + failForCondition(execution, stageName, "ON_SUCCESS"); + execution.getStageExecutionStatuses().put(stageName, "Failed"); + eventPublisher.stageStateChange(execution, stageName, "FAILED"); + return false; + } + execution.getStageExecutionStatuses().put(stageName, "Succeeded"); + execution.setCurrentStage(null); + execution.setLastUpdateTime(now()); + putExecution(execution); + eventPublisher.stageStateChange(execution, stageName, "SUCCEEDED"); + return true; + } + + // ---------------------------------------------------------------- V2 stage conditions + + private enum ConditionOutcome { PASS, FAIL, SKIP_STAGE } + + /** + * Evaluates the stage's {@code beforeEntry}/{@code onSuccess} condition block. Rules run + * through the AWS rule providers we emulate: {@code LambdaInvoke} (real invocation via the + * Lambda service) and {@code VariableCheck} (pipeline-variable comparison); other providers + * pass permissively. A condition overridden via OverrideStageCondition always passes. + */ + private ConditionOutcome evaluateConditions(CodePipelineExecution execution, JsonNode stage, + String conditionType) { + JsonNode block = stage.path(conditionBlockField(conditionType)); + if (block.isMissingNode() || !block.has("conditions")) { + return ConditionOutcome.PASS; + } + if (Boolean.TRUE.equals(execution.getConditionOverrides() + .get(stage.path("name").asText() + "/" + conditionType))) { + return ConditionOutcome.PASS; + } + for (JsonNode condition : block.path("conditions")) { + boolean passed = true; + for (JsonNode rule : condition.path("rules")) { + if (!evaluateRule(execution, stage.path("name").asText(), conditionType, rule)) { + passed = false; + } + } + if (!passed) { + return "SKIP".equals(condition.path("result").asText("FAIL")) && "BEFORE_ENTRY".equals(conditionType) + ? ConditionOutcome.SKIP_STAGE : ConditionOutcome.FAIL; + } + } + return ConditionOutcome.PASS; + } + + private static String conditionBlockField(String conditionType) { + return switch (conditionType) { + case "BEFORE_ENTRY" -> "beforeEntry"; + case "ON_SUCCESS" -> "onSuccess"; + case "ON_FAILURE" -> "onFailure"; + default -> throw new AwsException("ValidationException", + "Unknown condition type " + conditionType, 400); + }; + } + + private boolean evaluateRule(CodePipelineExecution execution, String stageName, + String conditionType, JsonNode rule) { + Map record = new LinkedHashMap<>(); + record.put("ruleExecutionId", UUID.randomUUID().toString()); + record.put("ruleName", rule.path("name").asText()); + record.put("stageName", stageName); + record.put("conditionType", conditionType); + record.put("ruleProvider", rule.path("ruleTypeId").path("provider").asText()); + record.put("startTime", now()); + record.put("status", "InProgress"); + synchronized (execution) { + execution.getRuleExecutions().add(record); + putExecution(execution); + } + boolean passed; + String summary; + try { + String provider = rule.path("ruleTypeId").path("provider").asText(); + passed = switch (provider) { + case "LambdaInvoke" -> lambdaRulePasses(execution, rule); + case "VariableCheck" -> variableCheckPasses(execution, rule); + // Commands / DeploymentWindow / CloudWatchAlarm and unknown providers pass permissively. + default -> true; + }; + summary = passed ? "Rule passed." : "Rule condition was not met."; + } catch (Exception e) { + passed = false; + summary = Objects.toString(e.getMessage(), "Rule evaluation failed"); + } + synchronized (execution) { + record.put("status", passed ? "Succeeded" : "Failed"); + record.put("summary", summary); + record.put("lastUpdateTime", now()); + putExecution(execution); + } + return passed; + } + + private boolean lambdaRulePasses(CodePipelineExecution execution, JsonNode rule) { + String functionName = rule.path("configuration").path("FunctionName").asText(null); + if (functionName == null) { + throw new AwsException("ValidationException", + "LambdaInvoke rules require configuration.FunctionName", 400); + } + ObjectNode event = mapper.createObjectNode(); + event.put("ruleName", rule.path("name").asText()); + event.put("pipelineName", execution.getPipelineName()); + event.put("pipelineExecutionId", execution.getPipelineExecutionId()); + InvokeResult result = lambdaService.invoke(execution.getRegion(), functionName, + event.toString().getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse); + return result.getFunctionError() == null && result.getStatusCode() < 400; + } + + /** Above this length, a MATCHES pattern or subject is rejected rather than risking + * catastrophic regex backtracking on pipeline-declared input. */ + private static final int MAX_VARIABLE_CHECK_MATCH_LENGTH = 256; + + private static final long MATCHES_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(1); + + /** A regex subject whose {@code charAt} throws once the deadline passes, so a catastrophically + * backtracking pattern aborts instead of holding the run forever. */ + private static final class DeadlineCharSequence implements CharSequence { + private final CharSequence delegate; + private final long deadlineNanos; + + DeadlineCharSequence(CharSequence delegate, long deadlineNanos) { + this.delegate = delegate; + this.deadlineNanos = deadlineNanos; + } + + @Override + public char charAt(int index) { + if (System.nanoTime() - deadlineNanos > 0) { + throw new IllegalStateException("MATCHES pattern evaluation timed out"); + } + return delegate.charAt(index); + } + + @Override + public int length() { + return delegate.length(); + } + + @Override + public CharSequence subSequence(int start, int end) { + return new DeadlineCharSequence(delegate.subSequence(start, end), deadlineNanos); + } + + @Override + public String toString() { + return delegate.toString(); + } + } + + private boolean variableCheckPasses(CodePipelineExecution execution, JsonNode rule) { + JsonNode config = rule.path("configuration"); + String variable = resolveVariableReference(execution, config.path("Variable").asText("")); + String value = config.path("Value").asText(""); + return switch (config.path("Operator").asText("EQ")) { + case "EQ" -> variable.equals(value); + case "NE" -> !variable.equals(value); + case "CONTAINS" -> variable.contains(value); + case "MATCHES" -> { + if (value.length() > MAX_VARIABLE_CHECK_MATCH_LENGTH + || variable.length() > MAX_VARIABLE_CHECK_MATCH_LENGTH) { + throw new AwsException("ValidationException", + "VariableCheck MATCHES pattern or value exceeds " + + MAX_VARIABLE_CHECK_MATCH_LENGTH + " characters", 400); + } + yield Pattern.compile(value).matcher(new DeadlineCharSequence(variable, + System.nanoTime() + MATCHES_TIMEOUT_NANOS)).matches(); + } + default -> throw new AwsException("ValidationException", + "Unknown VariableCheck operator", 400); + }; + } + + /** Resolves {@code #{variables.name}} references against the execution's variables. */ + private String resolveVariableReference(CodePipelineExecution execution, String reference) { + String name = reference; + if (reference.startsWith("#{") && reference.endsWith("}")) { + name = reference.substring(2, reference.length() - 1); + if (name.startsWith("variables.")) { + name = name.substring("variables.".length()); + } + } + for (Map variable : execution.getVariables()) { + if (variable.get("name").equals(name)) { + return variable.getOrDefault("resolvedValue", ""); + } + } + // An unresolved reference must fail the rule, not compare as its own placeholder text. + throw new AwsException("ValidationException", + "VariableCheck variable " + reference + " could not be resolved", 400); + } + + private void failForCondition(CodePipelineExecution execution, String stageName, String conditionType) { + execution.setStatus("Failed"); + execution.setStatusSummary( + "Condition " + conditionType + " failed in stage " + stageName + "."); + putExecution(execution); + } + private void finishExecutionRun(CodePipelineExecution execution) { startLocks.withLock(lockKey(execution), () -> { try { @@ -2038,9 +2451,12 @@ public class CodePipelineService { } private void putExecution(CodePipelineExecution execution) { - executionStore.putForAccount(execution.getAccountId(), - executionKey(execution.getRegion(), execution.getPipelineName(), - execution.getPipelineExecutionId()), execution); + // Serializing the execution walks its rule records, which evaluateRule mutates under this lock. + synchronized (execution) { + executionStore.putForAccount(execution.getAccountId(), + executionKey(execution.getRegion(), execution.getPipelineName(), + execution.getPipelineExecutionId()), execution); + } } private void storeItem(String account, String region, String type, String id, @@ -2207,7 +2623,7 @@ public class CodePipelineService { node.remove(List.of("accountId", "region", "startTime", "lastUpdateTime", "sourceRevisions", "sourceRevisionOverrides", "actionExecutions", "currentStage", "stopRequested", "abandon", "rollbackTargetPipelineExecutionId", "stageExecutionStatuses", - "artifactsReleased")); + "artifactsReleased", "ruleExecutions", "conditionOverrides")); if (execution.getRollbackTargetPipelineExecutionId() != null) { node.putObject("rollbackMetadata").put( "rollbackTargetPipelineExecutionId", execution.getRollbackTargetPipelineExecutionId()); @@ -2422,15 +2838,26 @@ public class CodePipelineService { execution.getSourceRevisions().add(sourceRevision); } - private List> variableList(JsonNode node) { + /** The request's variables, plus the declared default of every pipeline variable it omits. */ + private List> variableList(JsonNode node, JsonNode declared) { List> result = new ArrayList<>(); + Set supplied = new HashSet<>(); if (node != null && node.isArray()) { for (JsonNode variable : node) { + supplied.add(variable.path("name").asText()); result.add(Map.of( "name", variable.path("name").asText(), "resolvedValue", variable.path("value").asText())); } } + if (declared != null && declared.isArray()) { + for (JsonNode variable : declared) { + String name = variable.path("name").asText(); + if (!supplied.contains(name) && variable.hasNonNull("defaultValue")) { + result.add(Map.of("name", name, "resolvedValue", variable.path("defaultValue").asText())); + } + } + } return result; } diff --git a/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.java b/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.java index 2978731eaa..5ea450a7e8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.java +++ b/src/main/java/io/github/hectorvent/floci/services/codepipeline/model/CodePipelineExecution.java @@ -37,6 +37,9 @@ public class CodePipelineExecution { private volatile boolean abandon; private volatile boolean artifactsReleased; private String rollbackTargetPipelineExecutionId; + private List> ruleExecutions = new ArrayList<>(); + /** Overridden stage conditions, keyed {@code /}. */ + private Map conditionOverrides = new LinkedHashMap<>(); public String getAccountId() { return accountId; @@ -223,6 +226,22 @@ public class CodePipelineExecution { this.rollbackTargetPipelineExecutionId = rollbackTargetPipelineExecutionId; } + public List> getRuleExecutions() { + return ruleExecutions; + } + + public void setRuleExecutions(List> ruleExecutions) { + this.ruleExecutions = ruleExecutions; + } + + public Map getConditionOverrides() { + return conditionOverrides; + } + + public void setConditionOverrides(Map conditionOverrides) { + this.conditionOverrides = conditionOverrides; + } + @RegisterForReflection @JsonInclude(JsonInclude.Include.NON_NULL) public static class ActionExecution { diff --git a/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineV2ConditionsTest.java b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineV2ConditionsTest.java new file mode 100644 index 0000000000..0ca8a30c48 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/codepipeline/CodePipelineV2ConditionsTest.java @@ -0,0 +1,493 @@ +package io.github.hectorvent.floci.services.codepipeline; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.codebuild.CodeBuildService; +import io.github.hectorvent.floci.services.codepipeline.model.CodePipelineExecution; +import io.github.hectorvent.floci.services.codedeploy.CodeDeployService; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.s3.model.S3Object; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Duration; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * V2 stage condition evaluation: beforeEntry/onSuccess rules (VariableCheck, LambdaInvoke), + * the FAIL and SKIP results, rule-execution records, and OverrideStageCondition resume. + */ +class CodePipelineV2ConditionsTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + + private final ObjectMapper mapper = new ObjectMapper(); + private LambdaService lambdaService; + private S3Service s3Service; + private CodePipelineService service; + private InMemoryStorageFactory storageFactory; + + @BeforeEach + void setUp() { + lambdaService = mock(LambdaService.class); + s3Service = mock(S3Service.class); + S3Object object = mock(S3Object.class); + when(object.getData()).thenReturn("artifact".getBytes()); + when(object.getETag()).thenReturn("etag-1"); + when(object.getVersionId()).thenReturn("v1"); + when(object.getLastModified()).thenReturn(Instant.now()); + when(s3Service.getObject(anyString(), anyString())).thenReturn(object); + // The S3 source action reads a pinned version, and CreatePipeline baselines source polling. + when(s3Service.getObject(anyString(), anyString(), any())).thenReturn(object); + when(s3Service.headObject(anyString(), anyString())).thenReturn(object); + lambdaReturns(null); + + storageFactory = new InMemoryStorageFactory(); + service = new CodePipelineService(storageFactory, mapper, mock(CodeBuildService.class), + mock(CodeDeployService.class), lambdaService, s3Service); + } + + private void lambdaReturns(String functionError) { + InvokeResult result = mock(InvokeResult.class); + when(result.getStatusCode()).thenReturn(200); + when(result.getFunctionError()).thenReturn(functionError); + when(result.getRequestId()).thenReturn("req-1"); + when(lambdaService.invoke(anyString(), anyString(), any(byte[].class), any(InvocationType.class))) + .thenReturn(result); + } + + // ---------------------------------------------------------------- helpers + + private ObjectNode sourceStage() { + ObjectNode stage = mapper.createObjectNode(); + stage.put("name", "Fetch"); + ObjectNode action = stage.putArray("actions").addObject(); + action.put("name", "S3Source"); + action.putObject("actionTypeId") + .put("category", "Source").put("owner", "AWS").put("provider", "S3").put("version", "1"); + action.putObject("configuration").put("S3Bucket", "bucket").put("S3ObjectKey", "app.zip"); + action.putArray("outputArtifacts").addObject().put("name", "SourceOut"); + action.put("runOrder", 1); + return stage; + } + + private ObjectNode lambdaStage(String stageName) { + ObjectNode stage = mapper.createObjectNode(); + stage.put("name", stageName); + ObjectNode action = stage.putArray("actions").addObject(); + action.put("name", stageName + "Fn"); + action.putObject("actionTypeId") + .put("category", "Invoke").put("owner", "AWS").put("provider", "Lambda").put("version", "1"); + action.putObject("configuration").put("FunctionName", "fn-" + stageName); + action.put("runOrder", 1); + return stage; + } + + /** Adds a one-rule condition to the stage's {@code block} (beforeEntry or onSuccess). */ + private ObjectNode addRule(ObjectNode stage, String block, String result, String provider) { + ObjectNode condition = stage.putObject(block).putArray("conditions").addObject(); + condition.put("result", result); + ObjectNode rule = condition.putArray("rules").addObject(); + rule.put("name", "rule-" + provider); + rule.putObject("ruleTypeId") + .put("category", "Rule").put("owner", "AWS").put("provider", provider).put("version", "1"); + return rule.putObject("configuration"); + } + + private ObjectNode pipelineDeclaration(String name, ObjectNode... stages) { + ObjectNode declaration = mapper.createObjectNode(); + declaration.put("name", name); + declaration.put("roleArn", "arn:aws:iam::000000000000:role/cp"); + declaration.putObject("artifactStore").put("type", "S3").put("location", "bucket"); + ArrayNode stageArray = declaration.putArray("stages"); + for (ObjectNode stage : stages) { + stageArray.add(stage); + } + return declaration; + } + + private void createPipeline(String name, ObjectNode... stages) { + service.handle("CreatePipeline", mapper.createObjectNode().set("pipeline", pipelineDeclaration(name, stages)), + REGION, ACCOUNT); + } + + private String startExecution(String pipelineName) { + JsonNode result = service.handle("StartPipelineExecution", + mapper.createObjectNode().put("name", pipelineName), REGION, ACCOUNT); + return result.path("pipelineExecutionId").asText(); + } + + private JsonNode awaitStatus(String pipelineName, String executionId, String expected) { + long deadline = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(10); + while (System.currentTimeMillis() < deadline) { + JsonNode execution = service.handle("GetPipelineExecution", mapper.createObjectNode() + .put("pipelineName", pipelineName).put("pipelineExecutionId", executionId), + REGION, ACCOUNT).path("pipelineExecution"); + if (expected.equals(execution.path("status").asText())) { + return execution; + } + try { + TimeUnit.MILLISECONDS.sleep(50); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + return fail("Execution " + executionId + " did not reach " + expected + " in time"); + } + + private JsonNode ruleExecutions(String pipelineName) { + return service.handle("ListRuleExecutions", + mapper.createObjectNode().put("pipelineName", pipelineName), REGION, ACCOUNT) + .path("ruleExecutionDetails"); + } + + // ---------------------------------------------------------------- tests + + @Test + void onSuccessVariableCheckFailureFailsExecutionAndOverrideResumes() { + // Catches: a failed onSuccess VariableCheck not failing the run, or OverrideStageCondition + // not resuming an execution that failed on exactly that condition. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "onSuccess", "FAIL", "VariableCheck") + .put("Variable", "#{variables.env}").put("Value", "prod").put("Operator", "EQ"); + createPipeline("conditional", sourceStage(), deploy); + + // Start without the expected variable: the ON_SUCCESS condition fails the run. + String executionId = startExecution("conditional"); + JsonNode failed = awaitStatus("conditional", executionId, "Failed"); + assertEquals("Condition ON_SUCCESS failed in stage Deploy.", failed.path("statusSummary").asText()); + assertEquals(1, ruleExecutions("conditional").size()); + assertEquals("Failed", ruleExecutions("conditional").get(0).path("status").asText()); + + // Overriding the failed condition resumes the execution to success. + service.handle("OverrideStageCondition", mapper.createObjectNode() + .put("pipelineName", "conditional") + .put("pipelineExecutionId", executionId) + .put("stageName", "Deploy") + .put("conditionType", "ON_SUCCESS"), REGION, ACCOUNT); + awaitStatus("conditional", executionId, "Succeeded"); + } + + @Test + void variableCheckMatchesRejectsAnOverlongPatternInsteadOfRunningIt() { + // Catches: an unbounded MATCHES regex being evaluated against pipeline-declared input. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "onSuccess", "FAIL", "VariableCheck") + .put("Variable", "#{variables.env}").put("Value", "a".repeat(257)).put("Operator", "MATCHES"); + createPipeline("matches-overlong", sourceStage(), deploy); + + ObjectNode start = mapper.createObjectNode().put("name", "matches-overlong"); + start.putArray("variables").addObject().put("name", "env").put("value", "prod"); + String executionId = service.handle("StartPipelineExecution", start, REGION, ACCOUNT) + .path("pipelineExecutionId").asText(); + awaitStatus("matches-overlong", executionId, "Failed"); + JsonNode rules = ruleExecutions("matches-overlong"); + assertEquals(1, rules.size()); + assertEquals("Failed", rules.get(0).path("status").asText()); + assertEquals("VariableCheck MATCHES pattern or value exceeds 256 characters", + rules.get(0).path("output").path("executionResult").path("externalExecutionSummary").asText()); + } + + @Test + void variableCheckMatchesFailsARuleWhosePatternBacktracksCatastrophically() { + // Catches: a short but pathological MATCHES pattern spinning forever inside the run. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "beforeEntry", "FAIL", "VariableCheck") + .put("Variable", "#{variables.env}").put("Value", "(a+)+\\1").put("Operator", "MATCHES"); + createPipeline("matches-redos", sourceStage(), deploy); + + ObjectNode start = mapper.createObjectNode().put("name", "matches-redos"); + start.putArray("variables").addObject().put("name", "env").put("value", "a".repeat(30) + "!"); + String executionId = service.handle("StartPipelineExecution", start, REGION, ACCOUNT) + .path("pipelineExecutionId").asText(); + assertTimeoutPreemptively(Duration.ofSeconds(10), () -> { + awaitStatus("matches-redos", executionId, "Failed"); + }); + JsonNode rules = ruleExecutions("matches-redos"); + assertEquals("Failed", rules.get(0).path("status").asText()); + assertEquals("MATCHES pattern evaluation timed out", + rules.get(0).path("output").path("executionResult").path("externalExecutionSummary").asText()); + } + + @Test + void variableCheckMatchesPassesWhenTheVariableMatchesThePattern() { + // Catches: MATCHES comparing literally instead of as a full-string regex. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "beforeEntry", "FAIL", "VariableCheck") + .put("Variable", "#{variables.env}").put("Value", "pr.*").put("Operator", "MATCHES"); + createPipeline("matches-ok", sourceStage(), deploy); + + ObjectNode start = mapper.createObjectNode().put("name", "matches-ok"); + start.putArray("variables").addObject().put("name", "env").put("value", "prod"); + String executionId = service.handle("StartPipelineExecution", start, REGION, ACCOUNT) + .path("pipelineExecutionId").asText(); + awaitStatus("matches-ok", executionId, "Succeeded"); + assertEquals("Succeeded", ruleExecutions("matches-ok").get(0).path("status").asText()); + } + + @Test + void beforeEntrySkipConditionSkipsStage() { + // Catches: a failed beforeEntry condition with result SKIP running or failing the stage. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "beforeEntry", "SKIP", "VariableCheck") + .put("Variable", "#{variables.go}").put("Value", "yes").put("Operator", "EQ"); + createPipeline("skipper", sourceStage(), deploy); + + String executionId = startExecution("skipper"); + awaitStatus("skipper", executionId, "Succeeded"); + JsonNode actions = service.handle("ListActionExecutions", + mapper.createObjectNode().put("pipelineName", "skipper"), REGION, ACCOUNT) + .path("actionExecutionDetails"); + assertFalse(actions.findValuesAsText("stageName").contains("Deploy")); + } + + @Test + @SuppressWarnings("unchecked") + void beforeEntrySkipEmitsNoStageEventsForTheSkippedStage() { + // Catches: a stage skipped by beforeEntry publishing a STARTED stage event with no terminal event. + EventBridgeService eventBridge = mock(EventBridgeService.class); + service = new CodePipelineService(storageFactory, mapper, mock(CodeBuildService.class), + mock(CodeDeployService.class), lambdaService, s3Service, + new CodePipelineEventPublisher(eventBridge, null, mapper), 500L, + TimeUnit.SECONDS.toNanos(5), () -> { }); + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "beforeEntry", "SKIP", "VariableCheck") + .put("Variable", "#{variables.go}").put("Value", "yes").put("Operator", "EQ"); + createPipeline("skip-events", sourceStage(), deploy); + + String executionId = startExecution("skip-events"); + awaitStatus("skip-events", executionId, "Succeeded"); + + ArgumentCaptor>> events = ArgumentCaptor.forClass(List.class); + verify(eventBridge, atLeastOnce()).putEvents(events.capture(), anyString(), anyString()); + List deployStageStates = new ArrayList<>(); + for (List> batch : events.getAllValues()) { + for (Map entry : batch) { + if ("CodePipeline Stage Execution State Change".equals(entry.get("DetailType"))) { + JsonNode detail = parseDetail((String) entry.get("Detail")); + if ("Deploy".equals(detail.path("stage").asText())) { + deployStageStates.add(detail.path("state").asText()); + } + } + } + } + assertEquals(List.of(), deployStageStates); + } + + private JsonNode parseDetail(String detail) { + try { + return mapper.readTree(detail); + } catch (IOException e) { + return fail("Unparseable event detail: " + detail); + } + } + + @Test + void failedLambdaInvokeRuleFailsTheCondition() { + // Catches: a LambdaInvoke rule passing although the function returned a function error. + lambdaReturns("Unhandled"); + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "beforeEntry", "FAIL", "LambdaInvoke").put("FunctionName", "gate-fn"); + createPipeline("lambda-gated", sourceStage(), deploy); + + String executionId = startExecution("lambda-gated"); + JsonNode failed = awaitStatus("lambda-gated", executionId, "Failed"); + assertEquals("Condition BEFORE_ENTRY failed in stage Deploy.", failed.path("statusSummary").asText()); + } + + @Test + void listRuleTypesReturnsTheAwsRuleCatalog() { + // Catches: ListRuleTypes returning an empty page instead of the AWS rule providers. + JsonNode result = service.handle("ListRuleTypes", mapper.createObjectNode(), REGION, ACCOUNT); + List providers = result.path("ruleTypes").findValuesAsText("provider"); + assertEquals(List.of("LambdaInvoke", "VariableCheck", "Commands", "DeploymentWindow", "CloudWatchAlarm"), providers); + } + + @Test + void listRuleExecutionsSurfacesRecordedRules() { + // Catches: ListRuleExecutions dropping the recorded rule runs or their provider. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "onSuccess", "FAIL", "LambdaInvoke").put("FunctionName", "gate-fn"); + createPipeline("ruled", sourceStage(), deploy); + + String executionId = startExecution("ruled"); + awaitStatus("ruled", executionId, "Succeeded"); + + JsonNode details = ruleExecutions("ruled"); + assertEquals(1, details.size()); + JsonNode detail = details.get(0); + assertEquals("rule-LambdaInvoke", detail.path("ruleName").asText()); + assertEquals("Deploy", detail.path("stageName").asText()); + assertEquals("Succeeded", detail.path("status").asText()); + assertEquals("LambdaInvoke", detail.path("input").path("ruleTypeId").path("provider").asText()); + assertEquals(executionId, detail.path("pipelineExecutionId").asText()); + } + + @Test + void onSuccessSkipConditionFailsTheStageBecauseTheStageAlreadyRan() { + // Catches: a failed onSuccess condition with result SKIP being recorded as a Succeeded stage. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "onSuccess", "SKIP", "VariableCheck") + .put("Variable", "#{variables.go}").put("Value", "yes").put("Operator", "EQ"); + createPipeline("on-success-skip", sourceStage(), deploy); + + String executionId = startExecution("on-success-skip"); + JsonNode failed = awaitStatus("on-success-skip", executionId, "Failed"); + assertEquals("Condition ON_SUCCESS failed in stage Deploy.", failed.path("statusSummary").asText()); + } + + @Test + void variableCheckUsesTheDeclaredDefaultWhenTheStartRequestOmitsTheVariable() { + // Catches: a pipeline variable's declared default being ignored by VariableCheck. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "beforeEntry", "FAIL", "VariableCheck") + .put("Variable", "#{variables.env}").put("Value", "prod").put("Operator", "EQ"); + ObjectNode declaration = pipelineDeclaration("defaulted", sourceStage(), deploy); + declaration.putArray("variables").addObject().put("name", "env").put("defaultValue", "prod"); + service.handle("CreatePipeline", mapper.createObjectNode().set("pipeline", declaration), REGION, ACCOUNT); + + String executionId = startExecution("defaulted"); + awaitStatus("defaulted", executionId, "Succeeded"); + } + + @Test + void variableCheckNotEqualsDoesNotPassOnAnUnresolvedReference() { + // Catches: an unresolved variable reference comparing as its placeholder text, so NE passes. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "beforeEntry", "FAIL", "VariableCheck") + .put("Variable", "#{variables.missing}").put("Value", "x").put("Operator", "NE"); + createPipeline("unresolved", sourceStage(), deploy); + + String executionId = startExecution("unresolved"); + awaitStatus("unresolved", executionId, "Failed"); + assertEquals("Failed", ruleExecutions("unresolved").get(0).path("status").asText()); + } + + @Test + void overrideIsRejectedWhenThePipelineChangedAfterTheExecutionFailed() { + // Catches: an override resuming an older execution against a newer pipeline declaration. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "onSuccess", "FAIL", "VariableCheck") + .put("Variable", "#{variables.env}").put("Value", "prod").put("Operator", "EQ"); + createPipeline("versioned", sourceStage(), deploy); + String executionId = startExecution("versioned"); + awaitStatus("versioned", executionId, "Failed"); + + ObjectNode changed = pipelineDeclaration("versioned", sourceStage(), lambdaStage("Deploy")); + service.handle("UpdatePipeline", mapper.createObjectNode().set("pipeline", changed), REGION, ACCOUNT); + + AwsException thrown = assertThrows(AwsException.class, () -> service.handle("OverrideStageCondition", + mapper.createObjectNode().put("pipelineName", "versioned") + .put("pipelineExecutionId", executionId).put("stageName", "Deploy") + .put("conditionType", "ON_SUCCESS"), REGION, ACCOUNT)); + assertEquals("ConditionNotOverridableException", thrown.getErrorCode()); + } + + @Test + void getPipelineExecutionDoesNotExposeInternalConditionState() { + // Catches: ruleExecutions and conditionOverrides leaking into the GetPipelineExecution response. + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "onSuccess", "FAIL", "LambdaInvoke").put("FunctionName", "gate-fn"); + createPipeline("clean-response", sourceStage(), deploy); + String executionId = startExecution("clean-response"); + JsonNode execution = awaitStatus("clean-response", executionId, "Succeeded"); + assertFalse(execution.has("ruleExecutions")); + assertFalse(execution.has("conditionOverrides")); + } + + @Test + void overrideWaiterTimingOutDoesNotEraseAnOverrideAnotherRequestAccepted() { + // Catches: a timed-out override waiter removing the flag of a concurrent override that already + // resumed the run. + // Shorten the finish wait; just before the waiter cleans up, the run finishes and a second + // override resumes it. + AtomicBoolean cleanupProbed = new AtomicBoolean(); + AtomicReference pendingOverride = new AtomicReference<>(); + service = new CodePipelineService(storageFactory, mapper, mock(CodeBuildService.class), + mock(CodeDeployService.class), lambdaService, s3Service, + new CodePipelineEventPublisher(null, null, mapper), 500L, + TimeUnit.MILLISECONDS.toNanos(200), () -> { + if (cleanupProbed.compareAndSet(false, true)) { + ObjectNode request = pendingOverride.get(); + service.activeRuns.remove(ACCOUNT + ":" + request.path("pipelineExecutionId").asText()); + service.handle("OverrideStageCondition", request, REGION, ACCOUNT); + } + }); + ObjectNode deploy = lambdaStage("Deploy"); + addRule(deploy, "onSuccess", "FAIL", "VariableCheck") + .put("Variable", "#{variables.env}").put("Value", "prod").put("Operator", "EQ"); + createPipeline("override-race", sourceStage(), deploy); + String executionId = startExecution("override-race"); + awaitStatus("override-race", executionId, "Failed"); + + ObjectNode override = mapper.createObjectNode().put("pipelineName", "override-race") + .put("pipelineExecutionId", executionId).put("stageName", "Deploy") + .put("conditionType", "ON_SUCCESS"); + pendingOverride.set(override); + // The run looks like it is still finishing, so the first override waits and then times out. + String runKey = ACCOUNT + ":" + executionId; + service.activeRuns.add(runKey); + + AwsException thrown = assertThrows(AwsException.class, + () -> service.handle("OverrideStageCondition", override, REGION, ACCOUNT)); + assertEquals("ConflictException", thrown.getErrorCode()); + + CodePipelineExecution stored = storageFactory.executionBackend().scanAllAccounts().get(0); + assertEquals(Boolean.TRUE, stored.getConditionOverrides().get("Deploy/ON_SUCCESS")); + } + + private static final class InMemoryStorageFactory extends StorageFactory { + private final List> created = new ArrayList<>(); + + private InMemoryStorageFactory() { + super(null, null); + } + + @SuppressWarnings("unchecked") + AccountAwareStorageBackend executionBackend() { + return (AccountAwareStorageBackend) created.stream() + .filter(backend -> backend.scanAllAccounts().stream() + .anyMatch(CodePipelineExecution.class::isInstance)) + .findFirst().orElseThrow(); + } + + @Override + public AccountAwareStorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + AccountAwareStorageBackend backend = AccountAwareStorageBackend.inMemory(ACCOUNT); + created.add(backend); + return backend; + } + } +}