Skip to main content
Systems Engineering

Immutable CI/CD Backups via S3 Object Lock

A technical guide to building an immutable backup architecture for CI/CD artifact registries using S3 Object Lock, Compliance mode, and cross-account replication.

KBY Technologies16 min read
Immutable CI/CD Backups via S3 Object Lock

Artifact registries are easy to leave out of a CI/CD threat model. When a Nexus, Artifactory or Docker Registry instance is compromised, the attacker can be one credential away from the backup store next to it, and if those backups can be deleted or overwritten, the recovery point is exactly as compromised as production. The fix is not “more backups.” The fix is an immutable backup architecture where the retention guarantee is enforced at the storage layer, independent of any credential the CI/CD platform itself holds.

This article walks through building that architecture on Amazon S3 using Object Lock, cross-account replication and service control policies, with the artifact registry (Sonatype Nexus, in this case, though the pattern generalises to Artifactory and OCI registries) as the protected workload.

#The Blast Radius Problem: When Backups Share a Trust Domain

The default failure mode in many self-hosted CI/CD estates looks like this: a backup job runs on a cron schedule, dumps the registry’s blob store and metadata database, and pushes the archive to an S3 bucket using the same IAM role, or a role in the same account, that the CI runner uses for everything else. If that runner’s credentials are exfiltrated (a compromised build script, a leaked OIDC token, a malicious dependency executing at build time), the attacker inherits s3:DeleteObject and s3:PutObject on the backup bucket as a side effect. Versioning alone does not save you here: a delete marker does not remove existing versions, but an attacker who also holds s3:DeleteObjectVersion can permanently delete versions by version ID, or add a lifecycle rule whose NoncurrentVersionExpiration action permanently deletes noncurrent versions.

An immutable backup architecture removes this dependency. The retention guarantee has to hold even when the account that produced the backup is compromised. That requirement pushes the design towards WORM (Write Once Read Many) storage semantics enforced by the storage provider, not by application logic. Be precise about the scope: Compliance mode protects locked object versions, but it does not protect the account that holds them. The backup account itself must be protected against closure and billing lapse, and the Organizations management account (which SCPs do not constrain) must be tightly controlled.

#Architectural Breakdown: Building an Immutable Backup Architecture

S3 Object Lock is the primitive that makes this practical without operating a dedicated tape library or hardware WORM appliance. It attaches a retention date to individual object versions, and while that retention is active in Compliance mode, no user, including the root user, can overwrite or delete that version or shorten its retention. AWS documents one way to delete a Compliance-mode version early: deleting the AWS account that holds it. Account-level actions such as closing the account must therefore be controlled separately.

#
WORM Semantics and Retention Modes

Object Lock ships with two retention modes, and the distinction is the crux of the entire immutable backup architecture:

  • In Governance mode, a principal can override retention if it holds s3:BypassGovernanceRetention and also sends the x-amz-bypass-governance-retention:true header with the request (--bypass-governance-retention in the AWS CLI). AWS suggests it for testing retention settings before committing to Compliance, but it reintroduces the exact trust dependency you’re trying to eliminate if that permission leaks.
  • In Compliance mode, a protected version can’t be overwritten or deleted by any user, including the root user; its retention mode can’t be changed and its retention period can’t be shortened, only extended. This is the mode the vault needs.

Compliance mode is irreversible for the duration of the retention window. That is precisely the property you want for ransomware resilience, and precisely the property that will burn you if you set the retention length wrongly on a bucket carrying multi-terabyte nightly dumps (see Failure Modes below).

#
How the Vault Copies End Up in Compliance Mode

Retention belongs to each object version, and S3 Replication carries it across. AWS documents that when it replicates an object that has retention information applied, it applies the same retention controls to the replica, overriding the default retention configured on the destination bucket. Only when the source object has no retention controls is the destination bucket’s default retention applied to the replica.

That rule decides the design. If the backup job wrote each object with Governance retention, the replica in the vault would be in Governance mode too, whatever the vault bucket’s default says, and anyone who obtained the bypass permission in the vault account could remove it. So the source objects carry no retention at all: the source bucket has versioning but no Object Lock, the backup job sends no lock settings, and the vault bucket’s default Compliance retention is what locks each replica as it arrives.

The cost is that the copy in the CI/CD account has only versioning to protect it, so until a backup has replicated it is exposed. Once the replica exists, deleting the source version by version ID does not touch it: S3 does not replicate version-specific deletes.

#
Keeping the Vault in a Separate Account

A locked vault in the same account as the credentials most likely to leak is still one compromise away from both copies. The vault is therefore a bucket in a dedicated backup account with no CI/CD workload identities in it.

immutable backup architecture

The resulting flow looks like this: the CI/CD platform account writes backup archives to a versioned source bucket with no Object Lock retention. An S3 Replication rule copies each new object to the vault bucket in the backup account: Cross-Region Replication (CRR) if the vault is in a different AWS Region, Same-Region Replication (SRR) if it is in the same one. The vault bucket has Object Lock enabled with a default Compliance retention, and its Object Ownership is set to bucket owner enforced, so the backup account owns every replica without needing the s3:ObjectOwnerOverrideToBucketOwner permission. The replication role, which S3 assumes, is limited to the documented replication permissions: s3:GetReplicationConfiguration and s3:ListBucket on the source bucket, s3:GetObjectVersionForReplication, s3:GetObjectVersionAcl and s3:GetObjectVersionTagging on its objects, and s3:ReplicateObject, s3:ReplicateDelete and s3:ReplicateTags on the vault bucket’s objects. AWS also requires s3:GetObjectRetention and s3:GetObjectLegalHold on the source bucket whenever Object Lock is used with replication, which includes replicating into a locked vault, so grant both. Because the buckets are in different accounts, the vault bucket also needs a bucket policy allowing the replication role to replicate into it, and versioning must be enabled on both buckets.

#Implementation Logic: Step-by-Step Rollout

The rollout sequence matters. Object Lock can be enabled on an existing versioned bucket, but once it is enabled it cannot be disabled, and versioning can no longer be suspended on that bucket. Planning it at bucket creation is cleaner, so the vault should be designed before the first backup job runs, not retrofitted after an incident.

  1. Provision a dedicated backup AWS account under your Organization, with SCPs denying any principal from disabling CloudTrail or modifying Object Lock configuration on the vault bucket. Put controls in place against account closure and billing lapse, and restrict access to the management account.
  2. Trial the configuration first with a scratch vault bucket that has a short Compliance default retention (for example 1 day), and confirm that a replicated test object reports Compliance mode (the head-object check below). Only then create the production vault bucket with Object Lock enabled at creation time and a default Compliance retention.
  3. Create the source bucket in the CI/CD account with versioning enabled and Object Lock left off. Set no retention on it or on individual uploads.
  4. Configure the replication rule (CRR or SRR, depending on where the vault bucket lives) with a dedicated replication IAM role holding only the permissions listed above, scoped to the source and vault buckets. Enable replication metrics on the rule so that lag and failures show up in CloudWatch.
  5. Wire the artifact registry’s backup job (a scheduled pipeline stage, not an ad-hoc cron on the registry host) to write via a short-lived STS-assumed role scoped to s3:PutObject on a single prefix of the source bucket.
  6. If you use SSE-KMS, note that S3 does not replicate SSE-KMS objects by default: the rule must enable SseKmsEncryptedObjects in its source selection criteria, and the replication role needs kms:Decrypt on the source key and kms:Encrypt on the vault key. Object Lock does not protect against losing the key, so give the vault key a key policy that denies kms:ScheduleKeyDeletion and kms:DisableKey to everyone except a break-glass admin role (KMS allows a deletion waiting period of 7 to 30 days; use 30 if deletion is ever scheduled) and limits kms:Decrypt to the restore role.
  7. Run a scheduled, automated restore drill against the replicated copy, not the source, at least monthly, including the retention check below. A backup you have not restored is a hypothesis, not a recovery point.

#Code & Configuration Reference

Terraform for the vault bucket in the backup account, applied once and never mutated outside a change-controlled pipeline. Apply it first to a scratch bucket with a short retention (for example days = 1) and raise it to the production value only after validating:

1resource "aws_s3_bucket" "artifact_backup_vault" {
2  bucket = "kby-registry-backups-vault"
3  object_lock_enabled = true
4}
5
6resource "aws_s3_bucket_versioning" "artifact_backup_vault" {
7  bucket = aws_s3_bucket.artifact_backup_vault.id
8  versioning_configuration {
9    status = "Enabled"
10  }
11}
12
13resource "aws_s3_bucket_ownership_controls" "artifact_backup_vault" {
14  bucket = aws_s3_bucket.artifact_backup_vault.id
15  rule {
16    object_ownership = "BucketOwnerEnforced"
17  }
18}
19
20resource "aws_s3_bucket_object_lock_configuration" "artifact_backup_vault" {
21  bucket = aws_s3_bucket.artifact_backup_vault.id
22  rule {
23    default_retention {
24      mode = "COMPLIANCE"
25      days = 90
26    }
27  }
28}

A Service Control Policy applied through AWS Organizations, rolled out first to a test OU and then to the CI/CD and backup accounts (note that SCPs do not apply to the management account), denying the escape hatches an attacker would reach for: bypassing Governance retention, changing Object Lock settings on either bucket, and changing or removing the source bucket’s replication rule (S3 authorises DeleteBucketReplication with s3:PutReplicationConfiguration too). Nothing in this design uses Governance mode, so the bypass is denied as a backstop. A break-glass role is exempted through a condition so that an emergency path remains; replace the role ARN with your own:

1{
2  "Version": "2012-10-17",
3  "Statement": [
4    {
5      "Sid": "DenyGovernanceBypass",
6      "Effect": "Deny",
7      "Action": "s3:BypassGovernanceRetention",
8      "Resource": "arn:aws:s3:::kby-registry-backups-*",
9      "Condition": {
10        "ArnNotLike": {
11          "aws:PrincipalArn": "arn:aws:iam::*:role/backup-break-glass"
12        }
13      }
14    },
15    {
16      "Sid": "DenyObjectLockAndReplicationChange",
17      "Effect": "Deny",
18      "Action": [
19        "s3:PutBucketObjectLockConfiguration",
20        "s3:PutObjectRetention",
21        "s3:PutObjectLegalHold",
22        "s3:PutReplicationConfiguration"
23      ],
24      "Resource": [
25        "arn:aws:s3:::kby-registry-backups-vault",
26        "arn:aws:s3:::kby-registry-backups-vault/*",
27        "arn:aws:s3:::kby-registry-backups-source",
28        "arn:aws:s3:::kby-registry-backups-source/*"
29      ],
30      "Condition": {
31        "ArnNotLike": {
32          "aws:PrincipalArn": "arn:aws:iam::*:role/backup-break-glass"
33        }
34      }
35    }
36  ]
37}

The backup runs as two jobs in a GitLab CI scheduled pipeline rather than a host-level cron, so execution, exit codes and duration are captured alongside every other pipeline job. The first uses the official postgres image for pg_dump; its major version must be at least the database server’s, because pg_dump refuses to dump a newer major version. Connection settings come from libpq environment variables (PGHOST, PGUSER, and PGPASSWORD as a masked variable) set as CI/CD variables, and the custom format is compressed by default. The second job uses amazon/aws-cli, whose entrypoint is the aws binary; entrypoint: [""] clears it so GitLab can run the script in a shell. That image has no jq, so the CLI’s own --query and --output text extract the credentials. This dumps the Nexus metadata database only; the blob store needs its own step:

1stages:
2  - backup
3
4registry-db-dump:
5  stage: backup
6  image: postgres:16
7  rules:
8    - if: '$CI_PIPELINE_SOURCE == "schedule"'
9  script:
10    - pg_dump --format=custom --file=nexus-metadata.dump nexus_metadata
11    - sha256sum nexus-metadata.dump > checksum.sha256
12  artifacts:
13    paths:
14      - nexus-metadata.dump
15      - checksum.sha256
16    expire_in: 1 day
17
18registry-backup-upload:
19  stage: backup
20  image:
21    name: amazon/aws-cli:2.15.30
22    entrypoint: [""]
23  needs: ["registry-db-dump"]
24  rules:
25    - if: '$CI_PIPELINE_SOURCE == "schedule"'
26  script:
27    - CREDS=$(aws sts assume-role --role-arn "$BACKUP_ROLE_ARN" --role-session-name backup-job --duration-seconds 900 --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text)
28    - export AWS_ACCESS_KEY_ID=$(echo "$CREDS" | cut -f1)
29    - export AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | cut -f2)
30    - export AWS_SESSION_TOKEN=$(echo "$CREDS" | cut -f3)
31    - aws s3api put-object --bucket kby-registry-backups-source --key nightly/$(date +%F)/checksum.sha256 --body checksum.sha256 --checksum-algorithm SHA256
32    - aws s3api put-object --bucket kby-registry-backups-source --key nightly/$(date +%F)/nexus-metadata.dump --body nexus-metadata.dump --checksum-algorithm SHA256

The upload deliberately has no --object-lock-mode or --object-lock-retain-until-date: a lock set here would travel with the replica and replace the vault’s Compliance default. The restore drill reads the lock back from the vault, using a backup-account role that holds s3:GetObjectRetention:

1aws s3api head-object --bucket kby-registry-backups-vault \
2  --key nightly/2026-11-19/nexus-metadata.dump \
3  --query '[ObjectLockMode,ObjectLockRetainUntilDate]'

Anything other than COMPLIANCE in the first field means retention is reaching the vault from the source.

#Failure Modes & Edge Cases

Compliance mode’s irreversibility cuts both ways. Every version that lands in the vault is kept, and billed, for the full default retention, and nothing can prune it early; lowering the default later does not shorten the versions already stored. Take a hypothetical seven-year default and a 3.2 TB nightly dump: by the end of year seven the vault holds about 2,555 dumps, more than 8 PB, none of which can be removed.

Immutable CI/CD Backups via S3 Object Lock architecture diagram 2

Lifecycle rules keep working on locked objects, and the lock is kept through transitions between storage classes, though an expiration rule cannot delete a locked version. The catch is restore time. S3 Glacier Instant Retrieval objects can be read straight away, but S3 Glacier Flexible Retrieval and S3 Glacier Deep Archive objects must be restored before they can be read, and a Standard retrieval from Deep Archive typically finishes within 12 hours (Bulk within 48). If an incident response target assumes the newest dump is readable at once, keep recent dumps in a class that allows it.

The quiet failure in this design is retention reappearing on the source. If someone enables Object Lock on the source bucket with a Governance default, or adds lock flags to the upload, new replicas inherit that Governance retention instead of the vault’s Compliance default. The SCP’s deny on s3:PutBucketObjectLockConfiguration covers the first route; the head-object check in the restore drill catches both.

Replication lag is the final trap. Replication is asynchronous, and AWS notes that large objects can take several hours to replicate, so the newest dump in the vault can trail the newest dump in the source, and your Recovery Point Objective (RPO) is set by what has reached the vault. S3 Replication Time Control replicates 99.9 percent of objects within 15 minutes. Replication metrics, which RTC turns on and which you can also enable on their own, publish ReplicationLatency, BytesPendingReplication, OperationsPendingReplication and OperationsFailedReplication to CloudWatch (see the S3 documentation on replication metrics). Alarm on failed operations: a broken rule leaves new backups unlocked in the CI/CD account.

#Scaling & Security Trade-offs

Rolling this out across a multi-team platform requires weighing retention rigidity against operational flexibility. Teams evaluating this alongside broader architectural patterns for platform resilience should treat the following as a decision matrix rather than a checklist:

  • Governance vs Compliance mode: Governance gives operators an override for legitimate cost or retention mistakes, but anyone who obtains the bypass permission and sends the header can use it; Compliance removes that path entirely at the cost of zero flexibility until expiry.
  • Same-account vs cross-account replication: same-account Object Lock protects locked versions but leaves them beside the credentials most likely to leak; cross-account isolation keeps a copy out of reach of a full account-level or root-credential compromise, at the cost of more IAM and key policy to maintain.
  • Storage class selection: S3 Standard objects can be read straight away for drills and real incidents; S3 Glacier Deep Archive is designed for low-cost long-term storage but needs a restore first, typically within 12 hours for a Standard retrieval, which may break an incident response target for a registry backing production deploys.
  • Retention window length: short windows (7–14 days) cost less but may expire before a slow intrusion is detected; longer windows hold every nightly dump for longer, as the example above shows.
  • Replication load vs backup frequency: more frequent backups shorten the RPO but add replication load and multiply the number of versions held for the full retention period; a single nightly full dump is the simplest point on that axis.

None of these trade-offs are free, and the correct point on each axis depends on what the registry actually protects: a registry serving a single internal team tolerates a looser configuration than one gating production container images for a regulated workload.

Object Lock and cross-account replication are not a substitute for detection and response controls upstream of the registry; they are the last line of defence that guarantees a clean recovery point exists regardless of what happens further up the chain, which is the entire point of treating backup integrity as an architectural concern rather than an operational afterthought.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01S3 documentationdocs.aws.amazon.com

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Withdrawn. Details
  • : Corrected during a review of published articles. Details
Reader Interaction

Comments

Add a thoughtful note on Immutable CI/CD Backups via S3 Object Lock. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Discover more

Lexicon Definitions

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.