Repository Security and Supply-Chain ProtectionIntroductionGit repositories are no longer merely collections of source files. They are authoritative records of software design, configuration, infrastructure code, dependency declarations, deployment automation, and sometimes credentials. A compromise of a repository can therefore affect confidentiality, integrity, availability, regulatory compliance, and customer trust. Repository security is the discipline of protecting the code, identities, metadata, build processes, and external components associated with version control. In a DevOps environment, security must be integrated into the development lifecycle rather than applied only before release. Developers, operations engineers, security teams, and automated systems all interact with repositories. Each interaction creates an opportunity either to enforce trust or to introduce risk. The central security objective is to ensure that only authorised actors can perform permitted actions, that important changes can be attributed and verified, and that suspicious activity can be detected and contained. This chapter focuses on Git and hosting platforms such as GitHub and GitLab. Platform names and interface details change over time, so the underlying principles are more important than any particular menu or command. Learning ObjectivesBy the end of this chapter, a learner should be able to: - Explain the security risks associated with repositories and software supply chains.
- Configure and manage SSH keys, personal access tokens, deploy keys, and service identities safely.
- Describe signed commits and tags and explain what they do and do not prove.
- Prevent, detect, and respond to secrets committed to repositories.
- Apply least privilege, protected branches, approval rules, and audit logging.
- Interpret dependency scanning, secret-scanning, and code-security alerts.
- Respond systematically to compromised credentials or manipulated Git history.
1. The Repository as a Security BoundaryA repository has several security dimensions: - Confidentiality: preventing unauthorised disclosure of source code, credentials, customer data, and internal documentation.
- Integrity: preventing unauthorised alteration of code, build scripts, release tags, and history.
- Availability: ensuring that authorised users and automation can access the repository when required.
- Authenticity and accountability: establishing who or what created an object or performed an action.
- Traceability: retaining sufficient records to investigate changes and incidents.
Git itself is distributed. Every clone may contain a substantial copy of the repository, including branches, tags, and historical objects. Removing a file from the current branch does not necessarily remove it from existing clones or from Git history. This makes repository security different from security of a conventional central database. The software supply chain extends beyond the repository. It includes package registries, dependencies, build runners, container images, action or pipeline components, signing systems, artifact repositories, and deployment environments. A vulnerable or malicious dependency can undermine a secure application; conversely, a compromised build runner can alter an otherwise trustworthy source tree. A useful trust model identifies four questions for every operation: - Who is requesting the operation? This is authentication.
- What may that identity do? This is authorisation.
- Was the object altered after it was created? This is integrity verification.
- Can the action be reconstructed later? This is auditability.
Authentication without authorisation is insufficient: a valid account may still possess excessive rights. Authorisation without auditability makes misuse difficult to investigate. Signed data without secure key management can provide false confidence. 2. Identity and Access Mechanisms2.1 SSH authenticationSSH is commonly used for Git transport. A key pair consists of a private key, which must remain secret, and a public key, which may be registered with a hosting service. During authentication, the client proves possession of the private key without transmitting it to the server. Good practice includes: - Generate a separate key for each significant device or automation purpose.
- Protect the private key with a strong passphrase and an agent or secure hardware-backed store where available.
- Prefer modern algorithms supported by the organisation’s policy, such as Ed25519 where compatible.
- Never place private keys in a repository, issue, ticket, container image, or shell script.
- Remove keys from lost devices and review registered keys periodically.
- Use host-key verification so that a client can detect an unexpected server identity.
An SSH key authenticates the key holder, not necessarily a human being. If several people share one private key, attribution is weakened and revocation becomes disruptive. Automation should therefore use narrowly scoped deploy keys or dedicated machine identities rather than a developer’s personal key. 2.2 HTTPS and access tokensWhen Git uses HTTPS, a password should generally not be used for Git operations. A personal access token (PAT) or equivalent access token acts as a credential. Tokens should have: - the smallest possible scope;
- an expiration date;
- a named owner or service purpose;
- secure storage in an operating-system credential manager or secrets manager; and
- a documented revocation procedure.
A token with repository-write permission is more dangerous than a read-only token. A token that can administer an organisation is substantially more dangerous than one limited to a single project. Fine-grained tokens are preferable where supported because they reduce both scope and blast radius. Tokens must not be placed in remote URLs, command history, CI logs, source files, or environment dumps. If a token appears in a log, assume it is compromised and revoke it immediately, even if the log is later deleted. 2.3 Deploy keys, applications, and CI identitiesA deploy key is often associated with one repository and is useful for a server or deployment process. A CI job may instead use a platform-issued job token, an application identity, or a short-lived cloud identity. These approaches are safer than a permanent administrator token because they can be restricted by repository, environment, branch, or job context. Service identities should be individually identifiable. Names such as build-production or dependency-bot-project-x are preferable to a generic automation identity. Ownership, purpose, permissions, expiry, and emergency contact should be recorded. 2.4 Access review and least privilegeLeast privilege means granting each identity only the permissions required for its current task and for no longer than necessary. Access should be reviewed when a person changes role, leaves the organisation, or no longer contributes to a project. A practical access review asks: - Is the account still active and necessary?
- Is its role appropriate?
- Does it have write, administrative, or secret-reading rights unnecessarily?
- Are repository permissions inherited from an organisation or group?
- Can a CI job modify protected branches or create releases?
- Are dormant tokens, keys, and deploy credentials still valid?
Least privilege reduces the blast radius of compromise; it does not eliminate the need for monitoring and response. 3. Signed Commits and TagsA Git commit contains author and committer identity fields, but these fields are not proof of identity. Anyone can configure Git with another person’s name and email address. Signing adds cryptographic evidence that a private signing key approved the object. A signed commit can help answer: “Did the holder of this signing key approve this exact commit?” A signed tag can similarly authenticate a release reference. Verification depends on the platform’s trust configuration, the integrity of the public key, and protection of the private key. Signing does not prove that: - the code is safe;
- the dependencies are safe;
- the signer reviewed every line;
- the signer’s account was not compromised; or
- the build artifact was produced from that commit.
The signing key must be protected as carefully as an SSH key. Hardware-backed keys, passphrases, key rotation, revocation, and documented recovery procedures are important. Organisations should also define which identities are trusted to sign release tags and how verified keys are associated with people or bots. For high-assurance releases, commit signing should be combined with protected tags, two-person approval, reproducible or attestable builds, and artifact signing. A verified commit is one link in a chain of evidence, not the entire chain. 4. Secrets in RepositoriesSecrets include passwords, API keys, private keys, database connection strings, cloud credentials, signing keys, tokens, and certificates. A secret accidentally committed to Git should be treated as exposed. Deleting the file in a later commit does not reliably remove it from history, forks, clones, caches, pull requests, or logs. PreventionEffective prevention combines technology and behaviour: - Store secrets in a secrets manager or protected CI/CD variable store.
- Inject secrets at runtime rather than hard-coding them.
- Add appropriate patterns to
.gitignore, while recognising that .gitignore is not a security control for already tracked files. - Use pre-commit hooks and server-side secret scanning.
- Prefer short-lived credentials and workload identity federation.
- Separate development, testing, staging, and production secrets.
- Use test values that cannot access real systems.
- Avoid printing environment variables or command lines in CI logs.
Secret-scanning tools use known signatures, entropy heuristics, and provider-specific verification. They can produce false positives and may miss novel or encoded secrets, so scanning is an additional control rather than a guarantee. Response to an exposed secretThe correct response is rotation first, investigation second, and history cleanup as a separate activity: - Identify the secret and its owner.
- Revoke or rotate it immediately through the issuing system.
- Determine what resources it could access.
- Examine provider, repository, CI, and system logs for use.
- Remove the secret from active files and prevent recurrence.
- Rewrite history only when necessary and with coordination.
- Notify affected stakeholders and document the incident.
History rewriting can disrupt clones and invalidate commit references. It does not replace revocation. A secret removed by force-pushing history remains usable if it was not revoked. 5. Protected Branches, Reviews, and Policy EnforcementA protected branch is a branch subject to controls such as pull or merge requests, required approvals, status checks, signed commits, linear history, restricted push access, or restricted force-push and deletion operations. The default branch and release branches normally deserve the strongest controls. A sound branch policy commonly requires: - no direct pushes to the production branch;
- at least one qualified reviewer, and two for high-risk changes;
- successful tests, linting, security checks, and build validation;
- resolution of review conversations;
- approval by code owners for sensitive paths;
- restricted creation, update, and deletion of release tags;
- explicit emergency procedures with enhanced audit logging.
Branch protection is not a substitute for secure CI. A malicious change can pass weak tests, and a compromised automation identity may bypass a poorly designed rule. Rules should therefore be enforced server-side, tested periodically, and applied consistently to all paths that can reach production. Code ownership is especially valuable for files such as workflow definitions, infrastructure code, dependency manifests, authentication components, and deployment configuration. Changes to CI workflows deserve particular attention because they may execute with repository secrets. 6. Dependency and Supply-Chain SecurityModern applications depend on direct and transitive packages. A dependency may introduce known vulnerabilities, licensing constraints, malicious code, abandoned maintenance, or unexpected network and filesystem behaviour. Important controls include: - dependency manifests and lockfiles committed to version control;
- automated vulnerability scanning for direct and transitive dependencies;
- review of dependency update pull requests;
- pinned versions or controlled version ranges;
- verification of package checksums or signatures where supported;
- software bills of materials (SBOMs);
- provenance or build attestations;
- private registries and approved package sources;
- removal of unused dependencies; and
- rapid patching based on risk rather than alert volume alone.
A lockfile improves reproducibility by recording selected versions, but it does not prove that a package is safe. Pinning a malicious version merely makes the malicious choice repeatable. Dependency scanning also has limitations: a database may lack a newly disclosed vulnerability, severity may depend on application context, and a vulnerable library may not be reachable in the deployed program. A useful risk-prioritisation model considers exploitability, exposure, business impact, availability of a fix, and whether the vulnerable component is actually used. Teams should distinguish between an alert, a validated risk, and a completed remediation. CI/CD as a supply-chain targetPipeline definitions are executable code. A change to a workflow can exfiltrate secrets, alter artifacts, or deploy unauthorised software. Therefore: - review workflow changes as security-sensitive changes;
- minimise permissions granted to job tokens;
- avoid executing untrusted pull-request code with write tokens or production secrets;
- pin third-party actions or reusable components to reviewed immutable references where practical;
- isolate runners and destroy them after use;
- protect release environments with approvals;
- separate build, signing, and deployment privileges; and
- retain build logs and artifact provenance.
7. Alerts, Audit Logs, and DetectionSecurity alerts may concern leaked secrets, vulnerable dependencies, suspicious authentication, malware, unusual repository access, or policy violations. An alert is an input to investigation, not automatically proof of compromise. Audit logs should record events such as login, token creation and revocation, permission changes, repository visibility changes, branch protection changes, force-pushes, releases, workflow executions, and administrative actions. Logs should be protected from alteration and retained according to legal, contractual, and organisational requirements. Detection becomes stronger when events are correlated. For example, a new personal access token, followed by a repository clone from an unusual location and a force-push to a release branch, is more significant than any one event alone. Useful operational practices include: - centralising logs where feasible;
- synchronising timestamps;
- defining alert thresholds and escalation paths;
- monitoring privileged actions;
- testing that logs are actually generated; and
- periodically conducting access and incident exercises.
Privacy must also be considered. Audit systems should collect necessary security evidence without retaining irrelevant personal information indefinitely. 8. Incident Response for Compromised Credentials or HistoryAn incident response process should be prepared before an incident. A practical lifecycle is preparation, identification, containment, eradication, recovery, and lessons learned. PreparationMaintain an asset and identity inventory, emergency contacts, backup procedures, token-revocation knowledge, logging access, and documented decision authority. Define which incidents require legal, privacy, customer, or regulator notification. Identification and analysisDetermine what happened, when it began, which identity was involved, which repositories and environments were accessible, and whether code, secrets, artifacts, or deployments were modified. Preserve relevant evidence before destructive cleanup where possible. ContainmentShort-term containment may include disabling an account, revoking tokens and keys, blocking suspicious sessions, freezing releases, protecting branches, isolating runners, and restricting repository visibility. Containment should avoid destroying evidence unnecessarily. Eradication and recoveryRotate affected credentials, remove persistence, correct malicious changes, rebuild from a trusted commit, regenerate artifacts, and redeploy through a controlled pipeline. Review downstream systems because repository compromise may have affected package registries, cloud accounts, or production deployments. History compromiseIf an attacker rewrites history or inserts malicious commits, do not assume that restoring the visible branch is sufficient. Identify trusted commit points, compare refs and tags, inspect reflogs and audit records where available, invalidate compromised signing keys, and communicate new clone or rebase instructions. Force-pushing is a coordination activity, not an incident-response strategy by itself. Lessons learnedRecord the timeline, root causes, controls that failed, impact, and corrective actions. Improve technical controls and organisational practice. Blaming an individual for an unsafe process can prevent learning and conceal systemic weaknesses. 9. Illustrative Case Study: A Compromised Deployment TokenBackgroundA fictional online retailer, Northstar Retail, stores application code in a hosted Git platform. Its production deployment workflow uses a long-lived token with repository write permission and cloud deployment permission. ProblemA developer accidentally commits the token in a debugging script. Secret scanning raises an alert, but the alert is not monitored outside business hours. Twelve hours later, an attacker uses the token to clone private repositories and modifies a deployment workflow. The attacker also force-pushes a branch containing a backdoor. AnalysisThe token provides more authority than the deployment task requires. The workflow has write permission, production secrets, and access to an unisolated runner. Branch protection applies to the default branch but not to a release branch. Audit logs show token use from an unfamiliar location and a workflow change shortly afterward. Approach and solutionThe incident team first revokes the token and disables the affected service identity. It rotates cloud credentials, freezes releases, preserves logs, and identifies all repositories accessible to the token. It compares current refs with trusted backups and reviews workflow history. The compromised runner is destroyed and replaced. Production is rebuilt from a verified commit, and affected artifacts are regenerated. Long-term changes include a short-lived job identity restricted to one repository and environment, read-only permissions by default, protected release branches, required code-owner approval for workflow changes, mandatory secret-alert escalation, isolated ephemeral runners, and signed release tags. A regular access review is added to the operational calendar. OutcomeNo customer data is confirmed as accessed, but the organisation treats the incident as serious because repository confidentiality and deployment integrity were affected. The response demonstrates that credential rotation, audit analysis, trusted rebuilds, and policy improvements are all necessary; deleting the exposed line alone would not have solved the problem. Learning points- A secret is compromised when exposed, not only when misuse is proven.
- Excessive permissions magnify the consequences of a single mistake.
- Workflow files and runners are part of the software supply chain.
- Protected branches must include all paths to production.
- Recovery requires trusted source, trusted credentials, and trusted build infrastructure.
10. Governance, Ethics, and Contemporary PracticeRepository security involves governance as well as tooling. Organisations should define acceptable use, ownership of repositories, retention of logs, separation of duties, disclosure procedures, and responsibilities for open-source components. Compliance obligations may require evidence of access control, change approval, vulnerability management, and incident handling. Ethically, security teams should balance monitoring with privacy, disclose vulnerabilities responsibly, and avoid surveillance beyond legitimate security purposes. Open-source maintainers should communicate security fixes clearly without unnecessarily exposing exploit details before users can patch. Current practice is moving toward short-lived identities, workload identity federation, signed artifacts, provenance attestations, SBOMs, policy-as-code, and automated risk-based remediation. Artificial intelligence can assist with anomaly detection, dependency triage, and code review, but generated recommendations require human validation. AI systems may also expose proprietary code or produce insecure changes if supplied with sensitive repository content. They must therefore be governed by access controls, data-handling rules, and review requirements. Best-Practice Checklist- Use MFA for human accounts and strong protection for private keys.
- Prefer short-lived, narrowly scoped tokens and service identities.
- Review and revoke unused access regularly.
- Protect default, release, and deployment branches.
- Require review and automated checks for workflow and infrastructure changes.
- Sign important commits, tags, and release artifacts where operationally justified.
- Keep secrets outside Git and rotate exposed credentials immediately.
- Scan dependencies, secrets, containers, and source code continuously.
- Maintain lockfiles, SBOMs, provenance, and trusted build records.
- Centralise audit logs and practise incident response.
- Separate build, signing, and deployment privileges.
- Treat history rewriting as a coordinated operation after credential revocation.
Chapter SummaryRepository security protects confidentiality, integrity, availability, authenticity, and accountability across source code and the wider software supply chain. SSH keys, access tokens, deploy keys, and service identities must be scoped, protected, reviewed, and revoked when necessary. Signed commits and tags strengthen attribution and integrity evidence but do not prove that code is safe or that a build is trustworthy. Secrets should never be stored in repositories; exposure requires immediate revocation or rotation, investigation, and controlled cleanup. Protected branches, code owners, reviews, status checks, and restricted force-pushes reduce unauthorised changes. Dependency scanning, lockfiles, SBOMs, provenance, and secure CI runners address supply-chain risk, while audit logs and correlated alerts support detection. When credentials or history are compromised, organisations should follow a prepared response process: identify scope, contain access, preserve evidence, rotate credentials, rebuild from trusted material, recover safely, and improve controls. Effective security is therefore a combination of technical mechanisms, least-privilege design, governance, monitoring, and disciplined human practice. Key TermsAccess token: A credential used to authenticate an account or service to a platform. Audit log: A record of security-relevant actions and events. Branch protection: Rules that restrict changes to selected branches. Code owner: A person or team responsible for reviewing specified repository paths. Deploy key: An SSH key associated with a repository for automated access. Least privilege: Granting only the permissions necessary for a task. Lockfile: A file recording selected dependency versions and related integrity data. Personal access token: A user-associated token used instead of a password for API or Git access. Provenance: Evidence describing how and from what sources software was produced. Protected tag: A tag whose creation or modification is restricted. Reflog: Local Git records of reference movements, useful for some recovery investigations. Secret: Sensitive authentication or cryptographic material requiring protection. Secret scanning: Automated detection of likely credentials in code, commits, or related content. Software bill of materials: An inventory of components included in software. Software supply chain: The people, tools, code, dependencies, infrastructure, and processes used to produce and deliver software. SSH key pair: A private and public key used for cryptographic authentication. Token rotation: Replacing a credential with a new one and invalidating the old credential. Trusted commit: A commit accepted as an authoritative basis for recovery or release. Workflow: An automated sequence of repository or delivery actions. Review QuestionsShort Answer Questions- Why is deleting a secret from the latest commit insufficient to secure it?
- What is the difference between authentication and authorisation?
- State two limitations of signed commits.
- Why should CI jobs use narrowly scoped identities?
- What is the purpose of a lockfile?
Long Answer Questions- Explain how SSH keys, access tokens, deploy keys, and CI identities should be managed under least privilege.
- Discuss the role of protected branches, code owners, reviews, and status checks in repository integrity.
- Explain a complete response process for an exposed production credential.
- Evaluate the contribution and limitations of dependency scanning, SBOMs, and provenance evidence.
- Describe how audit logs support detection and investigation of repository compromise.
Analytical / Application Questions- A developer commits a cloud access key, deletes it in the next commit, and reports that no suspicious activity is visible. What actions should the security team take, and why?
- A release branch is protected, but a workflow can push directly to it using a broad write token. Analyse the risk and propose layered controls.
- An attacker force-pushes a repository after obtaining a maintainer token. Design an incident-response plan that distinguishes credential recovery, trusted-history recovery, and communication with developers.
Multiple Choice Questions with AnswersQuestion 1Which action is the most appropriate first response when a production token is committed to a public repository? A. Delete the file and wait for the next security scan B. Revoke or rotate the token immediately C. Rename the repository D. Rewrite Git history before taking any other action Correct Answer: B. Revoke or rotate the token immediately Question 2What does a signed Git commit primarily provide? A. Proof that the code has no vulnerabilities B. Proof that every line was reviewed by the signer C. Cryptographic evidence that a signing-key holder approved the commit D. Proof that the resulting binary was safely deployed Correct Answer: C. Cryptographic evidence that a signing-key holder approved the commit Question 3Which principle requires a CI job to receive only the permissions needed for its task? A. Availability B. Least privilege C. Eventual consistency D. Open allocation Correct Answer: B. Least privilege Question 4Why is a lockfile useful? A. It guarantees that every dependency is secure B. It records selected dependency versions for reproducibility C. It encrypts source code before publication D. It prevents all transitive dependencies Correct Answer: B. It records selected dependency versions for reproducibility Question 5Which repository control most directly prevents unauthorised direct pushes to a production branch? A. A protected-branch rule B. A larger repository C. A local Git alias D. A package lockfile Correct Answer: A. A protected-branch rule Question 6A personal access token should generally have which properties? A. No expiry and organisation-wide administrator scope B. A shared owner and unrestricted write access C. Narrow scope, secure storage, and an expiry or rotation plan D. Storage in a remote Git URL for convenience Correct Answer: C. Narrow scope, secure storage, and an expiry or rotation plan Question 7Which statement about secret scanning is correct? A. It guarantees that no secret can ever enter a repository B. It can identify likely exposed credentials but may produce false positives or miss novel secrets C. It makes credential rotation unnecessary D. It removes secrets from all existing clones Correct Answer: B. It can identify likely exposed credentials but may produce false positives or miss novel secrets Question 8Why are workflow files treated as supply-chain-sensitive code? A. They are always larger than application files B. They can execute commands, access credentials, and alter builds or deployments C. They cannot be reviewed by code owners D. They contain only documentation Correct Answer: B. They can execute commands, access credentials, and alter builds or deployments Question 9After a credential is exposed, why is history rewriting not sufficient by itself? A. Git cannot store text files B. The exposed credential may remain usable in clones, caches, or logs unless revoked C. History rewriting automatically grants more access D. Protected branches prevent all credential use Correct Answer: B. The exposed credential may remain usable in clones, caches, or logs unless revoked Question 10Which combination best supports investigation of suspicious repository activity? A. A deleted local clone and an unsigned release B. Centralised audit logs, identity records, and correlated event analysis C. A longer commit message and a larger repository D. A new branch with no access controls Correct Answer: B. Centralised audit logs, identity records, and correlated event analysis
|