Attack pattern

Source Code Prompt Injection

How repository content and designated instruction files reach coding assistants, influence plans and edits, and require provenance, separated authority and deterministic authorization.

By Norbert HofmannPublished: 2026-09-20Last reviewed: 2026-09-20Level: IntermediateAudience: Security Engineers, Developers, AI Engineers
Variant
Indirect
Vector
Repository and code-adjacent content
Targets
LLM, RAG System, AI Agent, Tool
OWASP
LLM01:2026 Prompt Injection
Table of contents

What Is Source Code Prompt Injection?

Source code prompt injection is indirect prompt injection through repository material that a coding assistant or agent reads, searches, indexes, summarizes or places in model context. The influencing language may occur in a comment, docstring, README, configuration file, test fixture, example, generated file, issue or pull-request description, or an explicitly supported repository instruction file.

The primitive is semantic influence, not executable code. A contributor-controlled text span can change a model's interpretation, plan or proposed patch even when every file parses correctly and no malicious program runs. Security impact requires more: reachable data or capabilities and an absent, overbroad or failed application control.

Related but distinct security problems
ClassDefining mechanismBoundary
Source Code Prompt InjectionRepository text influences model reasoning or a proposed actionContent, instruction authority and application authorization
Code injection or RCEInput becomes executable instructions for an interpreter or processorSafe parsing, execution and memory boundaries
Malicious code executionExisting source, binary or script is actually executedSandboxing, review and runtime controls
Software supply-chain compromiseA dependency, package, build input or distribution path is subvertedArtifact integrity, provenance and build security
Document Prompt InjectionGeneral file content reaches model context through parsing or conversionDocument parts and transformations
Tool Output InjectionA tool response carries instruction-like contentTool response provenance and use
Persistent Prompt InjectionInfluence survives in memory, indexes or other reusable stateLifecycle, lineage and invalidation

A compromised repository, dependency or package description can deliver content into scope, but that compromise is not itself prompt injection. This article begins where repository or task material becomes model-visible and can influence the coding workflow.

The Repository and Coding-Agent Pipeline

Repository content to controlled effect
UntrustedUser Task
UntrustedRepository / Task Content
SystemCheckout / Worktree
SystemSearch / Index / Selection
Variable trustModel Context
Variable trustPlan / Patch Proposal
SystemPolicy / Approval
Variable trustBounded Effect

Products assemble this path differently. Some inspect only open files, some search a local checkout, some query a remote index, and some combine repository files with issue or pull-request context. Trusted processors can faithfully transport untrusted text; their operational trust does not elevate the authority of their output.

Repository Content Surfaces

01
SurfaceComments and docstrings

Natural language adjacent to symbols and often retrieved with the code it explains.

02
SurfaceREADME and documentation

Broad project context that may be loaded early or matched by repository search.

03
SurfaceConfiguration text

Names, descriptions and comments in manifests, policy files and build configuration.

04
SurfaceTests, fixtures and examples

Representative data that may be read as requirements rather than merely test material.

05
SurfaceGenerated and vendored code

Large inherited surfaces with different authorship and review expectations.

06
SurfaceInstruction files

Explicit workflow instructions supported by a particular product and therefore a distinct authority surface.

07
SurfaceIssues and pull requests

Task descriptions, review comments and patch context when a product deliberately ingests them.

08
SurfaceWorkspace state

Local modifications, untracked files and generated outputs that differ from the pinned commit.

09
SurfaceSearch and symbol results

Selected spans and metadata returned by repository retrieval or code intelligence.

10
SurfaceDependencies and submodules

Additional repositories or package content reachable only when the configured workflow traverses them.

Source Text Is Data by Default

Code, comments, documentation, test data and configuration are evidence about the repository. Their authorship, location, successful compilation, signature or inclusion in an internal repository does not make their natural-language statements authoritative instructions for an AI system.

User task text is also input rather than application authority. The application defines the permitted objective and capability envelope; deterministic controls decide which resources and effects are allowed. Neither the user's wording nor repository text can expand that envelope.

Designated Repository Instructions as a Separate Authority Class

Some products intentionally support repository instruction mechanisms. For GitHub Copilot, GitHub documents .github/copilot-instructions.md, path-specific .github/instructions/**/*.instructions.md files and agent instruction files such as AGENTS.md. Support, combination and precedence vary by Copilot feature and surface. Such files can carry higher workflow instruction authority only where that concrete product surface recognizes them.

That authority is bounded. It never outranks system or application policy and never grants authorization for data access or side effects. Provenance, path, applicable scope, product-specific precedence and write permissions form a separate security boundary. Support and combination rules vary by product and surface, so they must be tested rather than generalized.

Branch, Ref, Commit and Worktree State

A repository name alone does not identify the material an agent saw. Branches, tags and pull-request refs can resolve to different commits; a local worktree can contain staged, unstaged or untracked changes; submodules can point elsewhere. An assessment must record the resolved commit and working state before reasoning about provenance.

Untrusted fork or pull-request content should not silently inherit the integrity or provenance status of an approved or pinned base state. Ordinary source remains data on either side. Where designated instruction files are supported, systems should explicitly define whether effective instructions come from the approved or pinned base state, the proposed change or both, and expose that choice to policy and review.

Search, Indexing and Context Selection

Coding systems often select context through filename search, symbol graphs, lexical or semantic indexes, open-editor state and model-directed follow-up searches. Relevance determines reachability, not trust. A result may be highly relevant and still be contributor-controlled task data.

Selection can be iterative: an included span can influence which symbol, file or directory the model asks to inspect next. Defenders should record every query and result set, constrain traversable scopes, and preserve the authority label of each returned span. For protected repositories or paths, indexing and retrieval should enforce the initiating principal's applicable access or a narrower delegated scope.

What Actually Becomes Model-Visible

Repository state and model-visible context
LayerEvidence to retainSecurity question
Repository stateOwner, repository, ref, commit, worktree statusWhich exact state was eligible for reading?
Retrieved spansPath, blob hash, line range, query and index versionWhich portions were selected and under whose permissions?
Context assemblyExact text, wrappers, ordering and authority labelsWhat did the model actually receive?
Plan and diffProposed steps, patch, tool parameters and destinationsHow did the proposal depart from the authorized task?

Provenance and Derived Repository Artifacts

Each model-visible span should retain repository identity, owner, branch or ref, resolved commit SHA, file path, blob or content hash, line or span identity, retrieval query, index generation and worktree status where available. Issue, pull-request and task context need their own author, event and permission provenance.

Summaries, symbol indexes, embeddings, caches and memory are derived artifacts. They should carry lineage to their source spans and access labels. Removing or correcting a repository file does not automatically remove old index generations, summaries or memory; response requires explicit invalidation and verified rebuild while preserving evidence.

Attacker Prerequisites and Reachability

A realistic assessment begins by identifying content the tester is authorized to control: a fixture on a test branch, a synthetic fork, a test issue, or a dependency fixture in an isolated project. The content must then become reachable under a plausible task, branch, file-selection and indexing configuration.

Write access alone is insufficient. The relevant ref must be checked out or indexed, the file type must be eligible, the span must survive selection and truncation, and the resulting context must influence a model operation. A security effect additionally requires a reachable capability and a failed deterministic control.

Offensive Perspective on Repository Ingestion

Authorized Red Teams should map controllable content to realistic entry points and measure each barrier independently. Useful questions concern which identity can modify which surface, which ref the system resolves, how retrieval selects spans, whether authority labels survive assembly, and what capability exists after influence.

The objective is not to optimize wording. It is to discover unsafe composition: untrusted repository material reaching an instruction-sensitive model, an influenced proposal reaching excessive tools or data, and application policy failing to contain it. This article therefore omits reusable prompts, malicious code, concealment, persistence techniques and exploitation sequences.

Source Code Prompt Injection Success Chain

Separately testable gates
UntrustedControlled Repo / Task Content
Variable trustRepository Reachability
SystemRef / Worktree Resolution
SystemSearch / File Selection
Variable trustContent or Supported Instructions in Context
Variable trustPlan / Edit Influence
Variable trustCapability Reach
SystemPolicy / Approval
Variable trustEffect

The chain branches after influence. A read-only assistant may only produce an answer or proposal. Another system may separately offer scoped file writes, shell or package tools, network calls, commits, pushes, pull requests, CI triggers or merge operations. None of these capabilities is universal, and each is a separate gate.

Model influence is not security impact. End-to-end impact requires one complete capability branch, a missing or failed policy decision, and an actual security-relevant effect. Reports should state the deepest observed gate rather than imply later effects.

Competing Constraints for an Attacker

01
ConstraintRef not reached

The system uses a protected commit rather than contributor-controlled fork or branch state.

02
ConstraintFile not selected

File filters, task scope or retrieval ranking exclude the controlled span.

03
ConstraintContext competition

Relevant code, explicit task scope and supported instructions outweigh unrelated text.

04
ConstraintAuthority remains visible

The application labels ordinary content as data and validates designated instruction provenance.

05
ConstraintCapability absent

The assistant cannot write, execute, connect, commit or publish.

06
ConstraintPolicy denies

Path, command, package, destination or repository policy blocks the proposal independently of the model.

07
ConstraintReview catches drift

An exact diff and provenance-aware review reveal unrelated scope expansion before mutation or merge.

Offensive Review Questions

Authorized repository assessment

  • Who can modify ordinary source content, and who can modify each designated instruction file?
  • Which branches, refs, commits and forks are ingested, and is untrusted PR or fork content isolated from the approved or pinned base state?
  • Which file types, directories, generated files, vendor trees, dependencies and submodules are indexed or retrieved?
  • Can comments, docs, configuration, tests or fixtures alter task scope or steer later repository searches?
  • Are supported instruction files authenticated and protected, and are their scope and product-specific precedence visible?
  • Can context select tools, shell arguments, file paths, package sources or network destinations, and are these independently authorized?
  • Does the runtime expose ambient secrets, registry tokens, cloud credentials or sensitive local files?
  • Are proposal, file write, command, commit, push, PR creation, CI trigger and merge distinct capabilities?
  • Do approvals bind to the exact diff, ref, action and destination and expire when any of them changes?
  • Does provenance survive context assembly, and do summaries, indexes or memory persist after source removal?
  • Can telemetry separate inclusion, influence, proposal, write, command, commit, push, PR, CI, merge and final effect?

Worked Scenario: Bounded Validation Update

01Authorized task

An internal coding agent is asked to update one validation function in a synthetic test repository.

02Controlled content

A contributor-controlled fixture, comment or documentation span contains instruction-like language that redirects scope toward a synthetic secret file or unrelated CI configuration. No reusable payload is included.

03Observed influence

The model proposes an out-of-scope read or CI edit, demonstrating plan influence without proving security impact.

04Deterministic containment

Policy denies secret paths, network access and CI files. The agent can only propose a bounded diff on an isolated branch and cannot commit, push or merge it.

05Review evidence

Span provenance, the exact context, plan drift and the proposed diff expose the deviation to a human reviewer.

The test uses synthetic data, bounded permissions and reversible effects. Influence is recorded as a model-level finding; the denied capability path demonstrates containment.

Capabilities, Effects and Authorization Boundaries

Do not collapse coding-agent capabilities
StagePossible effectIndependent control
ProposalTextual plan or suggested patchTask scope and provenance review
File writeWorkspace mutationAllowed repository, path and operation
Shell / tool / packageLocal execution or dependency changeExecutable, arguments, package source and sandbox policy
NetworkRead or egress to a destinationDestination, protocol, data class and initiating principal
CommitNew repository objectExact diff, identity, branch and signing policy
Push / PRRemote publication or review requestRepository, ref, destination and token scope
CI / mergeAutomated execution or protected-state changeWorkflow permissions, branch protection and separate approval

Approval should bind to the exact immutable diff, ref, action and destination. Re-evaluate authorization if any parameter or repository state changes. Repository instructions and model output remain proposals to this control plane, never authorization inputs.

Detection and Telemetry

Evidence from task to effect
  1. 01
    Initiation

    Principal, session, task, authorized scope and application policy version.

  2. 02
    Repository state

    Owner, repository, branch, ref, resolved commit SHA and worktree status.

  3. 03
    Source provenance

    Path, blob or content hash, line range, authoring surface and authority class.

  4. 04
    Retrieval

    Repository search or index query, index version, candidates and selected spans.

  5. 05
    Model context

    Exact context, ordering, wrappers and labels, with sensitive-data controls.

  6. 06
    Proposal and mutation

    Plan, patch, proposed and executed writes, commands, tools, packages and network destinations.

  7. 07
    Decision and effect

    Policy result, bound approval, commit SHA, push, PR, CI, merge and final side effect.

Useful signals include plan drift, source-authority mismatch, unexpected refs or untracked files, a widened diff, new path or destination requests, and mismatch between approved and executed actions. Telemetry should establish sequence without claiming it proves internal model causality.

Prevention and Secure Architecture

  1. 01
    Classify authority

    Treat source text as data and supported repository instructions as a distinct, bounded class below application policy.

  2. 02
    Protect instruction sources

    Restrict and review who can modify designated instruction files; expose their scope and effective precedence.

  3. 03
    Preserve span provenance

    Carry repository, ref, commit, path, blob hash, line range, query and index version into context and logs.

  4. 04
    Resolve intended base state

    Pin or verify branch and ref where required, and isolate fork, PR and local worktree content without treating repository integrity as instruction authority.

  5. 05
    Minimize context

    Retrieve only task-relevant files and spans under the initiating identity's permissions.

  6. 06
    Isolate execution

    Use an isolated workspace or container without ambient secrets or sensitive local files.

  7. 07
    Authorize deterministically

    Enforce file, path, tool, shell, package and network rules outside the model, including egress allowlists.

  8. 08
    Stage higher-impact changes

    Require proposal and review before mutation, and separate write, commit, push, PR and merge rights.

  9. 09
    Bind approvals

    Approve the exact diff, ref, action and destination; re-evaluate when repository state changes.

  10. 10
    Validate downstream

    Use branch protection, code review, CI and security scans as additional validation, not prompt-injection prevention.

Risky
  1. Mixed Repository Context
  2. Coding Agent
  3. Ambient Secrets and Tools
  4. Push / CI / Merge

Unlabelled content reaches a broadly capable runtime and model proposals flow toward mutation.

Stronger
  1. Pinned State + Provenance
  2. Authority-Aware Context
  3. LLM Proposal
  4. Diff / Path / Tool Policy
  5. Bound Approval
  6. Isolated Scoped Action

Content, instruction authority, proposal, authorization and execution remain separate.

The Defense Hub places these controls in the broader architecture for provenance, least privilege, information flow, action control and recovery.

Controlled Security Testing

Use synthetic repositories, identities, secrets and destinations; isolate execution; cap permissions; and make every effect reversible. Vary content class, ref, worktree state, retrieval method, instruction-file support and capability set. Record a denominator for each metric.

Separate source-code security metrics
MetricExplicit denominator
Repository / Content Reachability RateEligible controlled repository states or content cases tested
Context-Inclusion RateReachable cases evaluated for exact model-context inclusion
Injection Influence RateIncluded cases evaluated for changed answer, plan or patch
Unauthorized File-Write RateInfluenced cases proposing a prohibited write
Unauthorized Command / Tool RateInfluenced cases proposing a prohibited command or tool call
Policy Bypass RateProhibited proposals submitted to deterministic policy
Synthetic Secret Disclosure / Exfiltration Success RateControlled attempts with a reachable synthetic secret and forbidden destination
Unsafe Change Acceptance RateUnsafe synthetic diffs entering the defined review or merge decision
Detection RecallKnown synthetic injection cases
False-Positive RateBenign repository tasks evaluated
Containment RateInfluenced cases with an available prohibited effect

Do not combine the metrics. High influence with zero policy bypass is materially different from low reachability with untested authorization.

Incident Response

Source-code injection response checklist

  • Stop autonomous mutation and outbound actions while preserving the workspace and logs.
  • Record initiating identity, task, repository, ref, commit and complete worktree status.
  • Preserve source spans, paths, blob hashes, line ranges, queries, index version and exact model context.
  • Preserve plans, patches, writes, commands, tool calls, packages, destinations, policy decisions and approvals.
  • Trace resulting commits, pushes, pull requests, CI runs, merges and downstream artifacts.
  • Separate observed model influence from executed effects and confirmed data exposure.
  • Rotate credentials only when evidence supports exposure, use or loss of control.
  • Quarantine affected refs or artifacts without destroying evidence.
  • Invalidate and rebuild poisoned summaries, indexes, caches and memory from verified source state.
  • Retest the failed gate with synthetic content and bounded permissions before restoration.

Common Misconceptions

Frequent repository-security errors

  • Treating all repository files as equally authoritative instructions.
  • Treating a signed commit, internal repository or approved dependency as application authority.
  • Calling semantic model influence code injection, RCE or malware execution.
  • Assuming every coding assistant can write files, run commands, access networks, push or merge.
  • Applying product-specific instruction precedence to every tool or interface.
  • Allowing retrieved text to select shell arguments, paths, packages or destinations without policy.
  • Using branch protection or CI as a substitute for controlling the model-to-action boundary.
  • Deleting a source span while retaining summaries, indexes, caches or memory derived from it.

Standards and Research Context

Reviewed standards and guidance

OWASP GenAI Security Project
LLM01:2026 Prompt Injection
NIST
NIST AI 100-2e2025, NIST Glossary: indirect prompt injection
Microsoft
Defend against indirect prompt injection attacks, Input, Context, and Retrieval Hygiene
GitHub
Coding agent risks and mitigations, Repository custom instructions, Custom instruction support
Research
Greshake et al. 2023

OWASP LLM01:2026 classifies indirect injection through external sources. NIST defines indirect prompt injection as prompt injection executed through resource control, while resource control separately describes attacker control of external resources consumed at inference time. These define mechanism, not downstream impact.

Microsoft treats prompts, documents, retrieved chunks, tool results and memory writes as untrusted and recommends provenance, permission-aware indexing and validation at each read and write. GitHub documents concrete custom-instruction mechanisms and mitigations for its own Copilot surfaces. Those product behaviours are examples, not universal permissions or precedence rules.

Greshake et al. reports the practical viability of indirect prompt injection against real-world LLM-integrated systems, including code-completion engines. The paper supports the threat model; this page does not reproduce attack strings or procedures.

Frequently Asked Questions

Is Source Code Prompt Injection the same as code injection or RCE?

No. Source Code Prompt Injection uses repository language to influence a model. Code injection or RCE requires data to become executable instructions in a runtime. One workflow can face both risks, but they need different controls.

Are comments, docstrings and README files only data?

They are untrusted task data by default. They can provide useful evidence about a project, but cannot authorize sensitive data access or actions.

Do repository instruction files always have higher authority?

No. They have workflow authority only when the specific product supports them, within its documented scope. They never outrank application policy or deterministic authorization.

Are signed commits or trusted repositories safe instruction sources?

No. Integrity and provenance help identify content; they do not automatically grant every sentence authority over an AI workflow.

What changes with forks, pull requests and local changes?

They introduce repository states with different authors, permissions and review status. Record the exact ref, commit and worktree and isolate untrusted proposed state from protected base state.

Can repository search or indexing make influence persistent?

Yes. Summaries, indexes, embeddings, caches or memory can preserve derived content beyond the source revision and expose it to later tasks or users.

Do branch protection, review and CI prevent prompt injection?

No. They can catch or block unsafe changes downstream, but they do not prevent untrusted text from influencing a model. They complement context and authorization controls.

How should coding agents be authorized?

Use the initiating principal's current permissions, task-scoped short-lived capabilities, isolated execution, deterministic path, tool and destination policy, and approval bound to the exact diff, ref and action.

References

  1. LLM01:2026 Prompt InjectionOWASP GenAI Security Project · GuidanceReviewed 2026-09-20
  2. Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations, NIST AI 100-2e2025NIST · Standard · 2025-03Reviewed 2026-09-20
  3. indirect prompt injectionNIST Glossary · Technical documentationReviewed 2026-09-20
  4. Defend against indirect prompt injection attacksMicrosoft Learn · GuidanceReviewed 2026-09-20
  5. Input, Context, and Retrieval HygieneMicrosoft Learn · GuidanceReviewed 2026-09-20
  6. Risks and mitigations for GitHub Copilot coding agentGitHub Docs · GuidanceReviewed 2026-09-20
  7. Application card: GitHub Copilot AgentsGitHub Docs · GuidanceReviewed 2026-09-20
  8. Adding repository custom instructions for GitHub CopilotGitHub Docs · Technical documentationReviewed 2026-09-20
  9. Support for different types of custom instructionsGitHub Docs · Technical documentationReviewed 2026-09-20
  10. AGENTS.mdOpen format · Technical documentationReviewed 2026-09-20
  11. Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt InjectionKai Greshake et al. · Research publication · 2023Reviewed 2026-09-20