Skip to main content

taudit_core/
graph.rs

1use serde::{Deserialize, Serialize, Serializer};
2use std::collections::{BTreeMap, HashMap};
3
4/// Unique identifier for a node in the authority graph.
5pub type NodeId = usize;
6
7/// Unique identifier for an edge in the authority graph.
8pub type EdgeId = usize;
9
10// ── Metadata key constants ─────────────────────────────
11// Avoids stringly-typed bugs across crate boundaries.
12
13pub const META_DIGEST: &str = "digest";
14pub const META_PERMISSIONS: &str = "permissions";
15pub const META_IDENTITY_SCOPE: &str = "identity_scope";
16pub const META_INFERRED: &str = "inferred";
17/// Marks an Image node as a job container (not a `uses:` action).
18pub const META_CONTAINER: &str = "container";
19/// Marks an Identity node as OIDC-capable (`permissions: id-token: write`).
20pub const META_OIDC: &str = "oidc";
21/// Marks a Secret node whose value is interpolated into a CLI flag argument (e.g. `-var "key=$(SECRET)"`).
22/// CLI flag values appear in pipeline log output even when ADO secret masking is active,
23/// because the command string is logged before masking runs and Terraform itself logs `-var` values.
24pub const META_CLI_FLAG_EXPOSED: &str = "cli_flag_exposed";
25/// Graph-level metadata: identifies the trigger type (e.g. `pull_request_target`, `pr`).
26pub const META_TRIGGER: &str = "trigger";
27/// Marks a Step that writes to the environment gate (`$GITHUB_ENV`, ADO `##vso[task.setvariable]`).
28pub const META_WRITES_ENV_GATE: &str = "writes_env_gate";
29/// Marks a Step that reads from the runner-managed environment via an
30/// `env.<NAME>` template reference — `${{ env.X }}` in a `with:` value,
31/// inline script body, or step `env:` mapping. Distinct from `secrets.X`
32/// references (which produce a HasAccessTo edge to a Secret node) — `env.X`
33/// references can be sourced from the ambient runner environment, including
34/// values laundered through `$GITHUB_ENV` by an earlier step. Stamped by
35/// the GHA parser so `secret_via_env_gate_to_untrusted_consumer` can find
36/// the gate-laundering chain that the explicit-secret rules miss.
37pub const META_READS_ENV: &str = "reads_env";
38/// Marks a Step that performs cryptographic provenance attestation (e.g. `actions/attest-build-provenance`).
39pub const META_ATTESTS: &str = "attests";
40/// Marks a Secret node sourced from an ADO variable group (vs inline pipeline variable).
41pub const META_VARIABLE_GROUP: &str = "variable_group";
42/// Marks an Image node as a self-hosted agent pool (pool.name on ADO; runs-on: self-hosted on GHA).
43pub const META_SELF_HOSTED: &str = "self_hosted";
44/// Marks a Step that performs a `checkout: self` (ADO) or default `actions/checkout` on a PR context.
45pub const META_CHECKOUT_SELF: &str = "checkout_self";
46/// Marks an Identity node as an ADO service connection.
47pub const META_SERVICE_CONNECTION: &str = "service_connection";
48/// Marks an Identity node as implicitly injected by the platform (e.g. ADO System.AccessToken).
49/// Implicit tokens are structurally accessible to all tasks by platform design — exposure
50/// to untrusted steps is Info-level (structural) rather than Critical (misconfiguration).
51pub const META_IMPLICIT: &str = "implicit";
52/// Marks a Step that belongs to an ADO deployment job whose `environment:` is
53/// configured with required approvals — a manual gate that breaks automatic
54/// authority propagation. Findings whose path crosses such a node have their
55/// severity reduced by one step (Critical → High → Medium → Low).
56pub const META_ENV_APPROVAL: &str = "env_approval";
57/// Records the parent job name on every Step node, enabling per-job subgraph
58/// filtering (e.g. `taudit map --job build`) and downstream consumers that
59/// need to attribute steps back to their containing job. Set by both the GHA
60/// and ADO parsers on every Step they create within a job's scope.
61pub const META_JOB_NAME: &str = "job_name";
62/// Graph-level metadata: JSON-encoded array of `resources.repositories[]`
63/// entries declared by the pipeline. Each entry is an object with fields
64/// `alias`, `repo_type`, `name`, optional `ref`, and `used` (true when the
65/// alias is referenced via `template: x@alias`, `extends: x@alias`, or
66/// `checkout: alias` somewhere in the same pipeline file). Set by the ADO
67/// parser; consumed by `template_extends_unpinned_branch`.
68pub const META_REPOSITORIES: &str = "repositories";
69/// Records the raw inline script body of a Step (the text from
70/// `script:` / `bash:` / `powershell:` / `pwsh:` / `run:` / task
71/// `inputs.script` / `inputs.Inline` / `inputs.inlineScript`). Stamped by
72/// parsers when the step has an inline script. Consumed by script-aware
73/// rules: `vm_remote_exec_via_pipeline_secret`,
74/// `short_lived_sas_in_command_line`, `secret_to_inline_script_env_export`,
75/// `secret_materialised_to_workspace_file`, `keyvault_secret_to_plaintext`,
76/// `add_spn_with_inline_script`, `parameter_interpolation_into_shell`.
77/// Stored verbatim — rules apply their own pattern matching.
78pub const META_SCRIPT_BODY: &str = "script_body";
79/// Records the name of the ADO service connection a step uses (the value of
80/// `inputs.azureSubscription` / `inputs.connectedServiceName*`). Set on the
81/// Step node itself (in addition to the Identity node it links to) so rules
82/// can pattern-match on the connection name without traversing edges.
83pub const META_SERVICE_CONNECTION_NAME: &str = "service_connection_name";
84/// Marks a Step as performing `terraform apply ... -auto-approve` (either via
85/// an inline script or via a `TerraformCLI` / `TerraformTask` task with
86/// `command: apply` and `commandOptions` containing `auto-approve`).
87pub const META_TERRAFORM_AUTO_APPROVE: &str = "terraform_auto_approve";
88/// Marks a Step task that runs with `addSpnToEnvironment: true`, exposing
89/// the federated SPN (idToken / servicePrincipalKey / servicePrincipalId /
90/// tenantId) to the inline script body via environment variables.
91pub const META_ADD_SPN_TO_ENV: &str = "add_spn_to_environment";
92/// Graph-level metadata: identifies the source platform of the parsed
93/// pipeline. Set by every parser to its `platform()` value
94/// (`"github-actions"`, `"azure-devops"`, `"gitlab"`). Allows platform-scoped
95/// rules to gate their detection without parsing the source file path.
96pub const META_PLATFORM: &str = "platform";
97/// Graph-level metadata: marks a GitHub Actions workflow as having NO
98/// top-level `permissions:` block declared. Set by the GHA parser when
99/// `workflow.permissions` is absent so rules can detect the negative-space
100/// "no permissions block at all" pattern (which leaves `GITHUB_TOKEN` at its
101/// broad platform default — `contents: write`, `packages: write`, etc.).
102pub const META_NO_WORKFLOW_PERMISSIONS: &str = "no_workflow_permissions";
103/// Marks a Step in a GHA workflow as carrying an `if:` condition that
104/// references the standard fork-check pattern
105/// (`github.event.pull_request.head.repo.fork == false` or the equivalent
106/// `head.repo.full_name == github.repository`). Stamped by the GHA parser so
107/// rules can credit the step with the compensating control without
108/// re-parsing the YAML expression. Bool stored as `"true"`.
109pub const META_FORK_CHECK: &str = "fork_check";
110/// Marks a GitLab CI job (Step node) whose `rules:` or `only:` clause
111/// restricts execution to protected branches — either via an explicit
112/// `if: $CI_COMMIT_REF_PROTECTED == "true"` rule, an `if: $CI_COMMIT_BRANCH
113/// == $CI_DEFAULT_BRANCH` rule, or an `only: [main, ...]` allowlist of
114/// platform-protected refs. Set by the GitLab parser. Absence on a
115/// deployment job is a control gap.
116pub const META_RULES_PROTECTED_ONLY: &str = "rules_protected_only";
117/// Graph-level metadata: comma-joined list of every entry under `on:` (e.g.
118/// `pull_request_target,issue_comment,workflow_run`). Distinct from
119/// `META_TRIGGER` (singular) which is set only for `pull_request_target` /
120/// ADO `pr` to preserve the existing `trigger_context_mismatch` contract.
121/// Consumers of this list (e.g. `risky_trigger_with_authority`) must split on
122/// `,` and treat each token as a trigger name.
123pub const META_TRIGGERS: &str = "triggers";
124/// Graph-level metadata: comma-joined list of `workflow_dispatch.inputs.*`
125/// names declared by the workflow. Empty / absent if the workflow has no
126/// `workflow_dispatch` trigger. Consumed by
127/// `manual_dispatch_input_to_url_or_command` to taint-track input flow into
128/// command lines, URLs, and `actions/checkout` refs.
129pub const META_DISPATCH_INPUTS: &str = "dispatch_inputs";
130/// Graph-level metadata: pipe-delimited list of `<job>\t<name>\t<source>`
131/// records, one per `jobs.<id>.outputs.<name>`. Records are joined with `|`,
132/// fields within a record with `\t`. `source` is one of `secret` (value
133/// reads `secrets.*`), `oidc` (value references `steps.*.outputs.*` from a
134/// step that holds an OIDC identity), `step_output` (any other
135/// `steps.*.outputs.*`), or `literal`. Plain-text rather than JSON to keep
136/// the parser crate free of `serde_json`. Consumed by
137/// `sensitive_value_in_job_output`.
138pub const META_JOB_OUTPUTS: &str = "job_outputs";
139/// Step-level metadata: the value passed to `actions/checkout`'s `with.ref`
140/// input (verbatim, including any `${{ … }}` expressions). Stamped only on
141/// `actions/checkout` steps that supply a `ref:`. Consumed by
142/// `manual_dispatch_input_to_url_or_command`.
143pub const META_CHECKOUT_REF: &str = "checkout_ref";
144/// Marks the synthetic Step node created for a job that delegates to a
145/// reusable workflow with `secrets: inherit`. The whole secret bag forwards
146/// to the callee regardless of what the callee actually consumes — when the
147/// caller is fired by an attacker-controllable trigger this is a wide-open
148/// exfiltration path. Set on the synthetic step node by the GHA parser.
149pub const META_SECRETS_INHERIT: &str = "secrets_inherit";
150/// Marks a Step that downloads a workflow artifact (typically
151/// `actions/download-artifact` or `dawidd6/action-download-artifact`).
152/// In `workflow_run`-triggered consumers, the originating run's artifacts
153/// were produced from PR context — the consumer must treat their content as
154/// untrusted input even when the consumer itself runs with elevated perms.
155pub const META_DOWNLOADS_ARTIFACT: &str = "downloads_artifact";
156/// Marks a Step whose body interprets artifact (or other untrusted file)
157/// content into a privileged sink — `unzip`/`tar -x`, `cat`/`jq` piping
158/// into `>> $GITHUB_ENV`/`>> $GITHUB_OUTPUT`, `eval`, posting to a PR
159/// comment via `actions/github-script` `body:`/`issue_body:`, or evaluating
160/// extracted text. Combined with `META_DOWNLOADS_ARTIFACT` upstream in the
161/// same job and a `workflow_run`/`pull_request_target` trigger this is the
162/// classic mypy_primer / coverage-comment artifact-RCE pattern.
163pub const META_INTERPRETS_ARTIFACT: &str = "interprets_artifact";
164/// Marks a Step that uses an interactive debug action (mxschmitt/action-tmate,
165/// lhotari/action-upterm, actions/tmate, etc.). The cell value is the action
166/// reference (e.g. `mxschmitt/action-tmate@v3`). A successful debug session
167/// gives the operator an external SSH endpoint with the runner's full
168/// environment loaded — every secret in scope, the checked-out HEAD, and
169/// write access to whatever the GITHUB_TOKEN holds.
170pub const META_INTERACTIVE_DEBUG: &str = "interactive_debug";
171/// Marks a Step that calls `actions/cache` (or `actions/cache/save` /
172/// `actions/cache/restore`). The cell value is the raw `key:` input from
173/// the step's `with:` block. Consumed by `pr_specific_cache_key_in_default_branch_consumer`
174/// to detect PR-derived cache keys (head_ref, head.ref, actor) that a
175/// default-branch run can later restore — classic cache poisoning.
176pub const META_CACHE_KEY: &str = "cache_key";
177/// Records the OIDC audience (`aud:`) value of an `id_tokens:` entry on an
178/// Identity node. GitLab CI emits one Identity per `id_tokens:` key; the
179/// audience is what trades for downstream cloud creds (Vault path, AWS role,
180/// etc), so audience reuse across MR-context and protected-context jobs is
181/// the precise privilege-overscope signal. Set by the GitLab parser.
182pub const META_OIDC_AUDIENCE: &str = "oidc_audience";
183/// Records a Step's `environment:url:` value verbatim. Stamped by the GitLab
184/// parser when the job declares an `environment:` mapping with a `url:`
185/// field. Consumed by `untrusted_ci_var_in_shell_interpolation` because
186/// `environment:url:` is rendered by the GitLab UI and any predefined-CI-var
187/// interpolated into it is a stored-XSS / open-redirect sink.
188pub const META_ENVIRONMENT_URL: &str = "environment_url";
189/// Graph-level metadata: JSON-encoded array of `include:` entries declared by
190/// a GitLab CI pipeline. Each entry is an object with fields:
191/// - `kind`: one of `local`, `remote`, `template`, `project`, `component`
192/// - `target`: the path/URL/project string
193/// - `git_ref`: the resolved `ref:` value (only meaningful for `project` and
194///   `remote`) — empty string when the include omits a `ref:`
195///
196/// Set by the GitLab parser; consumed by `unpinned_include_remote_or_branch_ref`.
197pub const META_GITLAB_INCLUDES: &str = "gitlab_includes";
198/// Marks a Step (GitLab job) that declares one or more `services:` entries
199/// matching `docker:*-dind` or `docker:dind`. Combined with secret-bearing
200/// HasAccessTo edges it indicates a runtime sandbox-escape primitive — any
201/// inline build step can `docker run -v /:/host` from inside dind.
202pub const META_GITLAB_DIND_SERVICE: &str = "gitlab_dind_service";
203/// Marks a Step (GitLab job) declared with `allow_failure: true`. Used by
204/// `security_job_silently_skipped` to detect scanner jobs that pass silently.
205pub const META_GITLAB_ALLOW_FAILURE: &str = "gitlab_allow_failure";
206/// Records the comma-joined list of `extends:` template names a GitLab job
207/// inherits from. Used by scanner-name pattern matching in
208/// `security_job_silently_skipped` because GitLab security templates are
209/// usually consumed via `extends:` rather than by job-name match.
210pub const META_GITLAB_EXTENDS: &str = "gitlab_extends";
211/// Marks a Step (GitLab job) that defines a `trigger:` block (downstream /
212/// child pipeline). Value is `"static"` for a fixed downstream `project:` or
213/// `include:` of in-tree YAML, and `"dynamic"` when the include source is an
214/// `artifact:` (dynamic child pipelines — code-injection sink).
215pub const META_GITLAB_TRIGGER_KIND: &str = "gitlab_trigger_kind";
216/// Records the literal `cache.key:` value declared on a GitLab job (or the
217/// empty string if no cache is declared). Consumed by
218/// `cache_key_crosses_trust_boundary` to detect cross-trust cache keys.
219pub const META_GITLAB_CACHE_KEY: &str = "gitlab_cache_key";
220/// Records the `cache.policy:` value declared on a GitLab job
221/// (`pull` / `push` / `pull-push` / `pull_push`). When absent, the GitLab
222/// runtime default is `pull-push`. Consumed by
223/// `cache_key_crosses_trust_boundary`.
224pub const META_GITLAB_CACHE_POLICY: &str = "gitlab_cache_policy";
225/// Records the deployment environment name on a Step
226/// (e.g. GitLab `environment.name:` / GHA `environment:`).
227/// Used by rules that gate on production-like environment names.
228pub const META_ENVIRONMENT_NAME: &str = "environment_name";
229/// Records the GitLab `artifacts.reports.dotenv:` file path for a Step.
230/// When set, the file's `KEY=value` lines are silently exported as
231/// pipeline variables for every downstream job that consumes this job
232/// via `needs:` or `dependencies:`. Consumed by
233/// `dotenv_artifact_flows_to_privileged_deployment`.
234pub const META_DOTENV_FILE: &str = "dotenv_file";
235/// Records, on a Step, the upstream job names this step consumes via
236/// GitLab `needs:` or `dependencies:`. Comma-separated job names.
237/// Used to build dotenv-flow dependency chains across stages.
238pub const META_NEEDS: &str = "needs";
239
240// ── Shared helpers ─────────────────────────────────────
241
242/// Serialize a `HashMap<String, V>` with keys in sorted order. The
243/// in-memory representation stays a `HashMap` (cheaper insertion, hot
244/// path on every parser); only the serialized form is canonicalised.
245/// This is the single point of determinism control for graph metadata
246/// emitted via JSON / SARIF / CloudEvents — without it, HashMap iteration
247/// order leaks per-process randomness into every diff and cache key.
248fn serialize_string_map_sorted<S, V>(
249    map: &HashMap<String, V>,
250    serializer: S,
251) -> Result<S::Ok, S::Error>
252where
253    S: Serializer,
254    V: Serialize,
255{
256    let sorted: BTreeMap<&String, &V> = map.iter().collect();
257    sorted.serialize(serializer)
258}
259
260/// Returns true if `ref_str` is a SHA-pinned action reference.
261/// Checks: contains `@`, part after `@` is >= 40 hex chars.
262/// Single source of truth — used by both parser and rules.
263///
264/// This is a *structural* check — it accepts any 40+ hex character suffix
265/// without verifying the SHA refers to a real commit. For a semantic check
266/// that rejects obviously-bogus values like all-zero, see
267/// [`is_pin_semantically_valid`].
268pub fn is_sha_pinned(ref_str: &str) -> bool {
269    ref_str.contains('@')
270        && ref_str
271            .split('@')
272            .next_back()
273            .map(|s| s.len() >= 40 && s.chars().all(|c| c.is_ascii_hexdigit()))
274            .unwrap_or(false)
275}
276
277/// Returns true if `image` is pinned to a Docker digest.
278/// Docker digest format: `image@sha256:<64-hex-chars-lowercase>`.
279///
280/// Truncated digests (e.g. `alpine@sha256:abc`) and uppercase hex are
281/// rejected — Docker requires the full 64-character lowercase hex form.
282pub fn is_docker_digest_pinned(image: &str) -> bool {
283    image.contains("@sha256:")
284        && image
285            .split("@sha256:")
286            .nth(1)
287            .map(|h| {
288                h.len() == 64
289                    && h.chars()
290                        .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
291            })
292            .unwrap_or(false)
293}
294
295/// Returns true if `ref_str` looks both structurally pinned AND semantically
296/// plausible. Layered on top of [`is_sha_pinned`] / [`is_docker_digest_pinned`]:
297/// a structurally valid pin can still be obviously bogus (e.g. an all-zero SHA
298/// is syntactically a 40-char hex string but does not refer to any real
299/// commit; an attacker could use it to fake a "pinned" appearance).
300///
301/// Rules that want to flag impersonation attempts (rather than just laziness)
302/// should call this in addition to / instead of the structural check.
303///
304/// Rejects:
305/// - All-zero SHA-1 references (`actions/foo@0000…0000`).
306/// - All-zero sha256 docker digests (`image@sha256:0000…0000`).
307///
308/// Anything else that passes the structural check passes here.
309pub fn is_pin_semantically_valid(ref_str: &str) -> bool {
310    // Docker digest form takes priority (the `@sha256:` prefix is unambiguous).
311    if ref_str.contains("@sha256:") {
312        if !is_docker_digest_pinned(ref_str) {
313            return false;
314        }
315        let digest = ref_str.split("@sha256:").nth(1).unwrap_or("");
316        return !digest.chars().all(|c| c == '0');
317    }
318
319    if !is_sha_pinned(ref_str) {
320        return false;
321    }
322    let sha = ref_str.split('@').next_back().unwrap_or("");
323    !sha.chars().all(|c| c == '0')
324}
325
326// ── Graph-level precision markers ───────────────────────
327
328/// How complete is this authority graph? Parsers set this based on whether
329/// they could fully resolve all authority relationships in the pipeline YAML.
330///
331/// A `Partial` graph is still useful — it just tells the consumer that some
332/// authority paths may be missing. This is better than silent incompleteness.
333#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
334#[serde(rename_all = "snake_case")]
335pub enum AuthorityCompleteness {
336    /// Parser resolved all authority relationships.
337    Complete,
338    /// Parser found constructs it couldn't fully resolve (e.g. secrets in
339    /// shell strings, composite actions, reusable workflows). The graph
340    /// captures what it can, but edges may be missing.
341    Partial,
342    /// Parser couldn't determine completeness.
343    Unknown,
344}
345
346/// How broad is an identity's scope? Classifies the risk surface of tokens,
347/// service principals, and OIDC identities.
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
349#[serde(rename_all = "snake_case")]
350pub enum IdentityScope {
351    /// Wide permissions: write-all, admin, or unscoped tokens.
352    Broad,
353    /// Narrow permissions: contents:read, specific scopes.
354    Constrained,
355    /// Scope couldn't be determined — treat as risky.
356    Unknown,
357}
358
359impl IdentityScope {
360    /// Classify an identity scope from a permissions string.
361    pub fn from_permissions(perms: &str) -> Self {
362        let p = perms.to_lowercase();
363        if p.contains("write-all") || p.contains("admin") || p == "{}" || p.is_empty() {
364            IdentityScope::Broad
365        } else if p.contains("write") {
366            // Any write permission = broad (conservative)
367            IdentityScope::Broad
368        } else if p.contains("read") {
369            IdentityScope::Constrained
370        } else {
371            IdentityScope::Unknown
372        }
373    }
374}
375
376// ── Node types ──────────────────────────────────────────
377
378/// Semantic kind of a graph node.
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
380#[serde(rename_all = "snake_case")]
381pub enum NodeKind {
382    Step,
383    Secret,
384    Artifact,
385    Identity,
386    Image,
387}
388
389/// Trust classification. Explicit on every node — not inferred from kind.
390#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
391#[serde(rename_all = "snake_case")]
392pub enum TrustZone {
393    /// Code/config authored by the repo owner.
394    FirstParty,
395    /// Marketplace actions, external images (pinned).
396    ThirdParty,
397    /// Unpinned actions, fork PRs, user input.
398    Untrusted,
399}
400
401impl TrustZone {
402    /// Returns true if `self` is a lower trust level than `other`.
403    pub fn is_lower_than(&self, other: &TrustZone) -> bool {
404        self.rank() < other.rank()
405    }
406
407    fn rank(&self) -> u8 {
408        match self {
409            TrustZone::FirstParty => 2,
410            TrustZone::ThirdParty => 1,
411            TrustZone::Untrusted => 0,
412        }
413    }
414}
415
416/// A node in the authority graph.
417#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct Node {
419    pub id: NodeId,
420    pub kind: NodeKind,
421    pub name: String,
422    pub trust_zone: TrustZone,
423    /// Flexible metadata: pinning status, digest, scope, permissions, etc.
424    /// Serialized in sorted-key order so JSON / SARIF / CloudEvents output
425    /// is byte-deterministic across runs (HashMap iteration is randomised
426    /// per process, which would otherwise break diffs and cache keys).
427    #[serde(serialize_with = "serialize_string_map_sorted")]
428    pub metadata: HashMap<String, String>,
429}
430
431// ── Edge types ──────────────────────────────────────────
432
433/// Edge semantics model authority/data flow — not syntactic YAML relations.
434/// Design test: "Can authority propagate along this edge?"
435#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
436#[serde(rename_all = "snake_case")]
437pub enum EdgeKind {
438    /// Step -> Secret or Identity (authority granted at runtime).
439    HasAccessTo,
440    /// Step -> Artifact (data flows out).
441    Produces,
442    /// Artifact -> Step (authority flows from artifact to consuming step).
443    Consumes,
444    /// Step -> Image/Action (execution delegation).
445    UsesImage,
446    /// Step -> Step (cross-job or action boundary).
447    DelegatesTo,
448    /// Step -> Secret or Identity (credential written to disk, outliving the step's lifetime).
449    /// Distinct from HasAccessTo: disk persistence is accessible to all subsequent steps
450    /// and processes with filesystem access, not just the step that created it.
451    PersistsTo,
452}
453
454/// A directed edge in the authority graph.
455#[derive(Debug, Clone, Serialize, Deserialize)]
456pub struct Edge {
457    pub id: EdgeId,
458    pub from: NodeId,
459    pub to: NodeId,
460    pub kind: EdgeKind,
461}
462
463// ── Pipeline source ─────────────────────────────────────
464
465/// Where the pipeline definition came from.
466#[derive(Debug, Clone, Serialize, Deserialize)]
467pub struct PipelineSource {
468    pub file: String,
469    #[serde(skip_serializing_if = "Option::is_none")]
470    pub repo: Option<String>,
471    #[serde(skip_serializing_if = "Option::is_none")]
472    pub git_ref: Option<String>,
473    /// SHA of the commit being analyzed; reproducibility hint when set.
474    /// Parsers leave None; CI integrations populate this from the build env.
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub commit_sha: Option<String>,
477}
478
479// ── The graph ───────────────────────────────────────────
480
481/// Pipeline-level parameter declaration captured from a top-level
482/// `parameters:` block. Used by rules that need to reason about whether
483/// caller-supplied parameter values are constrained (`values:` allowlist)
484/// or free-form (no allowlist on a string parameter — shell-injection risk).
485#[derive(Debug, Clone, Serialize, Deserialize)]
486pub struct ParamSpec {
487    /// Declared parameter type (`string`, `number`, `boolean`, `object`, etc.).
488    /// Empty string when the YAML omitted `type:` (ADO defaults to string).
489    pub param_type: String,
490    /// True when the parameter declares a `values:` allowlist that constrains
491    /// the set of acceptable inputs. When true, free-form shell injection is
492    /// not possible because the runtime rejects any value outside the list.
493    pub has_values_allowlist: bool,
494}
495
496/// Directed authority graph. Nodes are pipeline elements (steps, secrets,
497/// artifacts, identities, images). Edges model authority/data flow.
498#[derive(Debug, Clone, Serialize, Deserialize)]
499pub struct AuthorityGraph {
500    pub source: PipelineSource,
501    pub nodes: Vec<Node>,
502    pub edges: Vec<Edge>,
503    /// How complete is this graph? Set by the parser based on what it could resolve.
504    pub completeness: AuthorityCompleteness,
505    /// Human-readable reasons why the graph is Partial (if applicable).
506    #[serde(default, skip_serializing_if = "Vec::is_empty")]
507    pub completeness_gaps: Vec<String>,
508    /// Graph-level metadata set by parsers (e.g. trigger type, platform-specific flags).
509    /// Serialized in sorted-key order — see `Node.metadata` rationale.
510    #[serde(
511        default,
512        skip_serializing_if = "HashMap::is_empty",
513        serialize_with = "serialize_string_map_sorted"
514    )]
515    pub metadata: HashMap<String, String>,
516    /// Top-level pipeline `parameters:` declarations, keyed by parameter name.
517    /// Populated by parsers that surface parameter metadata (currently ADO).
518    /// Empty for platforms / pipelines that don't declare parameters.
519    /// Serialized in sorted-key order — see `Node.metadata` rationale.
520    #[serde(
521        default,
522        skip_serializing_if = "HashMap::is_empty",
523        serialize_with = "serialize_string_map_sorted"
524    )]
525    pub parameters: HashMap<String, ParamSpec>,
526}
527
528impl AuthorityGraph {
529    pub fn new(source: PipelineSource) -> Self {
530        Self {
531            source,
532            nodes: Vec::new(),
533            edges: Vec::new(),
534            completeness: AuthorityCompleteness::Complete,
535            completeness_gaps: Vec::new(),
536            metadata: HashMap::new(),
537            parameters: HashMap::new(),
538        }
539    }
540
541    /// Mark the graph as partially complete with a reason.
542    pub fn mark_partial(&mut self, reason: impl Into<String>) {
543        self.completeness = AuthorityCompleteness::Partial;
544        self.completeness_gaps.push(reason.into());
545    }
546
547    /// Add a node, returns its ID.
548    pub fn add_node(
549        &mut self,
550        kind: NodeKind,
551        name: impl Into<String>,
552        trust_zone: TrustZone,
553    ) -> NodeId {
554        let id = self.nodes.len();
555        self.nodes.push(Node {
556            id,
557            kind,
558            name: name.into(),
559            trust_zone,
560            metadata: HashMap::new(),
561        });
562        id
563    }
564
565    /// Add a node with metadata, returns its ID.
566    pub fn add_node_with_metadata(
567        &mut self,
568        kind: NodeKind,
569        name: impl Into<String>,
570        trust_zone: TrustZone,
571        metadata: HashMap<String, String>,
572    ) -> NodeId {
573        let id = self.nodes.len();
574        self.nodes.push(Node {
575            id,
576            kind,
577            name: name.into(),
578            trust_zone,
579            metadata,
580        });
581        id
582    }
583
584    /// Add a directed edge, returns its ID.
585    pub fn add_edge(&mut self, from: NodeId, to: NodeId, kind: EdgeKind) -> EdgeId {
586        let id = self.edges.len();
587        self.edges.push(Edge { id, from, to, kind });
588        id
589    }
590
591    /// Outgoing edges from a node.
592    pub fn edges_from(&self, id: NodeId) -> impl Iterator<Item = &Edge> {
593        self.edges.iter().filter(move |e| e.from == id)
594    }
595
596    /// Incoming edges to a node.
597    pub fn edges_to(&self, id: NodeId) -> impl Iterator<Item = &Edge> {
598        self.edges.iter().filter(move |e| e.to == id)
599    }
600
601    /// All authority-bearing source nodes (Secret + Identity).
602    /// These are the BFS start set for propagation analysis.
603    pub fn authority_sources(&self) -> impl Iterator<Item = &Node> {
604        self.nodes
605            .iter()
606            .filter(|n| matches!(n.kind, NodeKind::Secret | NodeKind::Identity))
607    }
608
609    /// All nodes of a given kind.
610    pub fn nodes_of_kind(&self, kind: NodeKind) -> impl Iterator<Item = &Node> {
611        self.nodes.iter().filter(move |n| n.kind == kind)
612    }
613
614    /// All nodes in a given trust zone.
615    pub fn nodes_in_zone(&self, zone: TrustZone) -> impl Iterator<Item = &Node> {
616        self.nodes.iter().filter(move |n| n.trust_zone == zone)
617    }
618
619    /// Get a node by ID.
620    pub fn node(&self, id: NodeId) -> Option<&Node> {
621        self.nodes.get(id)
622    }
623
624    /// Get an edge by ID.
625    pub fn edge(&self, id: EdgeId) -> Option<&Edge> {
626        self.edges.get(id)
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633
634    #[test]
635    fn build_simple_graph() {
636        let mut g = AuthorityGraph::new(PipelineSource {
637            file: "deploy.yml".into(),
638            repo: None,
639            git_ref: None,
640            commit_sha: None,
641        });
642
643        let secret = g.add_node(NodeKind::Secret, "AWS_KEY", TrustZone::FirstParty);
644        let step_build = g.add_node(NodeKind::Step, "build", TrustZone::FirstParty);
645        let artifact = g.add_node(NodeKind::Artifact, "dist.tar.gz", TrustZone::FirstParty);
646        let step_deploy = g.add_node(NodeKind::Step, "deploy", TrustZone::ThirdParty);
647
648        g.add_edge(step_build, secret, EdgeKind::HasAccessTo);
649        g.add_edge(step_build, artifact, EdgeKind::Produces);
650        g.add_edge(artifact, step_deploy, EdgeKind::Consumes);
651
652        assert_eq!(g.nodes.len(), 4);
653        assert_eq!(g.edges.len(), 3);
654        assert_eq!(g.authority_sources().count(), 1);
655        assert_eq!(g.edges_from(step_build).count(), 2);
656        assert_eq!(g.edges_from(artifact).count(), 1); // Consumes flows artifact -> step
657    }
658
659    #[test]
660    fn completeness_default_is_complete() {
661        let g = AuthorityGraph::new(PipelineSource {
662            file: "test.yml".into(),
663            repo: None,
664            git_ref: None,
665            commit_sha: None,
666        });
667        assert_eq!(g.completeness, AuthorityCompleteness::Complete);
668        assert!(g.completeness_gaps.is_empty());
669    }
670
671    #[test]
672    fn mark_partial_records_reason() {
673        let mut g = AuthorityGraph::new(PipelineSource {
674            file: "test.yml".into(),
675            repo: None,
676            git_ref: None,
677            commit_sha: None,
678        });
679        g.mark_partial("secrets in run: block inferred, not precisely mapped");
680        assert_eq!(g.completeness, AuthorityCompleteness::Partial);
681        assert_eq!(g.completeness_gaps.len(), 1);
682    }
683
684    #[test]
685    fn identity_scope_from_permissions() {
686        assert_eq!(
687            IdentityScope::from_permissions("write-all"),
688            IdentityScope::Broad
689        );
690        assert_eq!(
691            IdentityScope::from_permissions("{ contents: write }"),
692            IdentityScope::Broad
693        );
694        assert_eq!(
695            IdentityScope::from_permissions("{ contents: read }"),
696            IdentityScope::Constrained
697        );
698        assert_eq!(
699            IdentityScope::from_permissions("{ id-token: write }"),
700            IdentityScope::Broad
701        );
702        assert_eq!(IdentityScope::from_permissions(""), IdentityScope::Broad);
703        assert_eq!(
704            IdentityScope::from_permissions("custom-scope"),
705            IdentityScope::Unknown
706        );
707    }
708
709    #[test]
710    fn trust_zone_ordering() {
711        assert!(TrustZone::Untrusted.is_lower_than(&TrustZone::FirstParty));
712        assert!(TrustZone::ThirdParty.is_lower_than(&TrustZone::FirstParty));
713        assert!(TrustZone::Untrusted.is_lower_than(&TrustZone::ThirdParty));
714        assert!(!TrustZone::FirstParty.is_lower_than(&TrustZone::FirstParty));
715    }
716
717    // ── Pin validation (fuzz B3 regression) ─────────────────
718
719    #[test]
720    fn is_sha_pinned_accepts_lowercase_40_hex() {
721        // 40 lowercase hex — the canonical legitimate form.
722        assert!(is_sha_pinned(
723            "actions/checkout@abc1234567890abcdef1234567890abcdef123456"
724        ));
725        // Mixed case is still structurally pinned (legitimate — Git accepts both).
726        assert!(is_sha_pinned(
727            "actions/checkout@ABCDEF1234567890abcdef1234567890ABCDEF12"
728        ));
729    }
730
731    #[test]
732    fn is_sha_pinned_structural_accepts_all_zero() {
733        // Structural check is intentionally permissive — semantic rejection
734        // happens in is_pin_semantically_valid. Documented in B3.
735        assert!(is_sha_pinned(
736            "actions/setup-python@0000000000000000000000000000000000000000"
737        ));
738    }
739
740    #[test]
741    fn is_sha_pinned_rejects_short_or_non_hex() {
742        assert!(!is_sha_pinned("actions/checkout@v4"));
743        assert!(!is_sha_pinned("actions/setup-node@a1b2c3"));
744        // 60 chars but not all hex.
745        assert!(!is_sha_pinned(
746            "actions/checkout@somethingthatlookslikeashabutisntsha1234567890abcdef"
747        ));
748    }
749
750    #[test]
751    fn is_pin_semantically_valid_rejects_all_zero_sha() {
752        // Fuzz B3 reproducer.
753        assert!(!is_pin_semantically_valid(
754            "actions/setup-python@0000000000000000000000000000000000000000"
755        ));
756    }
757
758    #[test]
759    fn is_pin_semantically_valid_accepts_real_looking_sha() {
760        assert!(is_pin_semantically_valid(
761            "actions/checkout@abc1234567890abcdef1234567890abcdef123456"
762        ));
763    }
764
765    #[test]
766    fn is_pin_semantically_valid_rejects_unpinned() {
767        assert!(!is_pin_semantically_valid("actions/checkout@v4"));
768        assert!(!is_pin_semantically_valid("actions/setup-node@a1b2c3"));
769    }
770
771    #[test]
772    fn is_docker_digest_pinned_rejects_truncated() {
773        // Fuzz B3 reproducer: previously accepted, now rejected.
774        assert!(!is_docker_digest_pinned("alpine@sha256:abc"));
775        // 65 chars (one too long).
776        assert!(!is_docker_digest_pinned(
777            "alpine@sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcde"
778        ));
779        // 63 chars (one short).
780        assert!(!is_docker_digest_pinned(
781            "alpine@sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abc"
782        ));
783    }
784
785    #[test]
786    fn is_docker_digest_pinned_accepts_full_64_lowercase() {
787        // Exactly 64 lowercase hex chars after `@sha256:`.
788        assert!(is_docker_digest_pinned(
789            "alpine@sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
790        ));
791    }
792
793    #[test]
794    fn is_docker_digest_pinned_rejects_uppercase() {
795        // Docker requires lowercase — uppercase indicates a hand-crafted /
796        // tampered string and should not pass.
797        assert!(!is_docker_digest_pinned(
798            "alpine@sha256:ABC123DEF456ABC123DEF456ABC123DEF456ABC123DEF456ABC123DEF456ABCD"
799        ));
800    }
801
802    #[test]
803    fn is_pin_semantically_valid_rejects_all_zero_docker_digest() {
804        assert!(!is_pin_semantically_valid(
805            "alpine@sha256:0000000000000000000000000000000000000000000000000000000000000000"
806        ));
807    }
808
809    #[test]
810    fn is_pin_semantically_valid_accepts_real_docker_digest() {
811        assert!(is_pin_semantically_valid(
812            "alpine@sha256:abc123def456abc123def456abc123def456abc123def456abc123def456abcd"
813        ));
814    }
815}