Lesson 04 — Security Testing & Secret Management
Learning Path
☁️ Phase 02 – AWS Cloud Security
📘 Module 11 – DevSecOps & Infrastructure as Code (IaC) Security
🎯 Lesson Objective
Section titled “🎯 Lesson Objective”By the end of this lesson, you will be able to:
- Explain the major types of application security testing.
- Differentiate SAST, DAST, SCA, secret scanning and container scanning.
- Integrate security testing into a CI/CD pipeline.
- Define risk-based security gates.
- Detect exposed credentials before deployment.
- Store application secrets using AWS Secrets Manager.
- Manage configuration values using AWS Systems Manager Parameter Store.
- Retrieve secrets securely from applications and pipelines.
- Apply least-privilege access to secrets.
- Plan secret rotation and incident response.
- Scan Amazon ECR container images.
- Design an enterprise security-testing and secret-management architecture.
📚 Lesson Information
Estimated Time: 5–6 Hours
Difficulty: Advanced
Prerequisites: Lesson 03 – CI/CD Pipeline Security
Hands-on Labs: Yes
💼 Business Scenario
Section titled “💼 Business Scenario”CloudNova Technologies has implemented a secure CI/CD pipeline for its cloud-native applications.
The environment includes:
- GitHub repositories
- AWS CodeBuild
- AWS CodePipeline
- Terraform
- AWS CloudFormation
- Docker
- Amazon ECR
- Amazon ECS and Amazon EKS
- AWS Lambda
- Amazon RDS
- Development, staging and production accounts
During a recent security review, the Cloud Security team discovers:
- Database passwords stored in application configuration files
- API keys committed to source repositories
- Vulnerable open-source libraries
- Containers running outdated operating-system packages
- Terraform templates creating publicly accessible resources
- Security tests running only before major releases
- Developers manually sharing production credentials
- Secrets remaining unchanged for several years
- Sensitive values appearing in CodeBuild logs
- No consistent process for handling failed security scans
The CISO asks:
“How can we detect security weaknesses automatically and ensure applications access secrets without storing credentials in code?”
As the Cloud Security Engineer, you must implement an enterprise security-testing and secret-management programme.
Why Security Testing Must Be Continuous
Section titled “Why Security Testing Must Be Continuous”Traditional security testing is often performed near the end of a project.
Requirements
↓
Development
↓
Testing
↓
Deployment Preparation
↓
Security Assessment
↓
ProductionThis approach creates several problems:
- Vulnerabilities are discovered late.
- Remediation becomes expensive.
- Release dates are delayed.
- Developers receive feedback after moving to other work.
- Critical weaknesses may reach production.
- Security teams become release bottlenecks.
DevSecOps moves security testing into every stage of delivery.
Plan
↓
Code
↓
Build
↓
Security Test
↓
Deploy
↓
Monitor
↓
ImproveEnterprise Security Testing Strategy
Section titled “Enterprise Security Testing Strategy”CloudNova uses multiple testing techniques because no single scanner can identify every type of security weakness.
Source Code
├── Secret Scanning├── Static Application Security Testing├── Software Composition Analysis└── Infrastructure as Code Scanning
Build Artefacts
├── Malware Scanning├── Package Validation└── Container Image Scanning
Running Application
├── Dynamic Application Security Testing├── API Security Testing└── Penetration Testing
Production Environment
├── Vulnerability Monitoring├── Configuration Monitoring└── Threat DetectionMajor Security Testing Types
Section titled “Major Security Testing Types”| Testing Type | Primary Target | Typical Findings |
|---|---|---|
| SAST | Source code | Injection risks, insecure functions and unsafe coding patterns |
| DAST | Running application | Authentication, input-validation and runtime vulnerabilities |
| SCA | Open-source dependencies | Known vulnerable libraries and licence risks |
| Secret Scanning | Repositories and files | API keys, passwords, tokens and private keys |
| IaC Scanning | Terraform and CloudFormation | Public resources, missing encryption and excessive permissions |
| Container Scanning | Container images | Vulnerable operating-system and application packages |
| API Security Testing | Application APIs | Broken authorisation, weak validation and exposed endpoints |
| Penetration Testing | Complete system | Exploitable weaknesses and attack paths |
Static Application Security Testing
Section titled “Static Application Security Testing”Static Application Security Testing, or SAST, analyses source code without executing the application.
Source Code
↓
Static Analysis Engine
↓
Security Rules
↓
Findings
↓
Developer RemediationSAST may identify:
- Injection vulnerabilities
- Unsafe input handling
- Insecure cryptographic usage
- Hardcoded credentials
- Path traversal risks
- Insecure deserialisation
- Weak error handling
- Dangerous functions
- Missing security controls
Benefits of SAST
Section titled “Benefits of SAST”SAST provides:
- Early developer feedback
- Testing before deployment
- Repeatable automated analysis
- File and line-level findings
- Integration with Pull Requests
- Support for security gates
Limitations of SAST
Section titled “Limitations of SAST”SAST may not fully understand:
- Runtime configuration
- Authentication flows
- Deployed infrastructure
- Application-business logic
- External service behaviour
- Runtime permissions
SAST should therefore be combined with other testing methods.
Dynamic Application Security Testing
Section titled “Dynamic Application Security Testing”Dynamic Application Security Testing, or DAST, tests a running application from an external perspective.
Running Application
↓
Automated Security Scanner
↓
HTTP Requests
↓
Application Responses
↓
Security FindingsDAST may identify:
- Injection vulnerabilities
- Cross-site scripting
- Security-header weaknesses
- Authentication problems
- Session-management issues
- Exposed files
- Server misconfiguration
- Input-validation weaknesses
SAST vs DAST
Section titled “SAST vs DAST”| Area | SAST | DAST |
|---|---|---|
| Target | Source code | Running application |
| Execution Required | No | Yes |
| Pipeline Stage | Code and build | Test and staging |
| Code Visibility | Usually required | Not necessarily required |
| Finding Detail | Often points to source lines | Usually identifies affected endpoint |
| Main Strength | Early detection | Runtime validation |
| Main Limitation | Cannot observe full runtime behaviour | May not identify the exact code location |
CloudNova uses both techniques.
Software Composition Analysis
Section titled “Software Composition Analysis”Modern applications may contain hundreds of third-party packages.
Software Composition Analysis, or SCA, evaluates open-source components.
Application
↓
Dependency Manifest
↓
Package Inventory
↓
Vulnerability Database
↓
Risk FindingsSCA may identify:
- Known vulnerable packages
- Unsupported libraries
- Outdated components
- Malicious packages
- Dependency confusion risks
- Licence-policy violations
- Transitive dependency vulnerabilities
Direct and Transitive Dependencies
Section titled “Direct and Transitive Dependencies”A direct dependency is intentionally added by the development team.
A transitive dependency is installed because another package requires it.
CloudNova Application
↓
Direct Dependency
↓
Transitive Dependency
↓
Additional Transitive DependencySecurity teams must evaluate the complete dependency tree rather than only the packages listed by developers.
Dependency Security Controls
Section titled “Dependency Security Controls”CloudNova applies the following controls:
- Use dependency lock files.
- Pin approved dependency versions.
- Use trusted package repositories.
- Remove unused packages.
- Scan every Pull Request.
- Block critical vulnerabilities.
- Monitor newly disclosed vulnerabilities.
- Review abandoned packages.
- Generate a Software Bill of Materials where required.
- Document approved exceptions.
Software Bill of Materials
Section titled “Software Bill of Materials”A Software Bill of Materials, or SBOM, is an inventory of components included in an application or software artefact.
An SBOM can contain:
- Package name
- Package version
- Supplier
- Dependency relationship
- Package identifier
- Licence information
- Integrity information
Application Release
↓
SBOM
↓
Component Inventory
↓
Vulnerability Correlation
↓
Risk ManagementAn SBOM helps security teams identify which applications are affected when a new vulnerability is disclosed.
Secret Scanning
Section titled “Secret Scanning”Secret scanning searches source code and related files for sensitive credentials.
Examples include:
- AWS access keys
- Database passwords
- API keys
- OAuth tokens
- Private keys
- Signing keys
- Webhook secrets
- Service-account credentials
- Connection strings
Developer Commit
↓
Secret Scanner
├── No Secret → Continue│└── Secret Detected → Block Commit and InvestigateLocations Where Secrets May Appear
Section titled “Locations Where Secrets May Appear”Secrets can accidentally appear in:
- Application source code
- Terraform files
- CloudFormation templates
.envfiles- Configuration files
- Test data
- Dockerfiles
- Container image layers
- CI/CD workflow files
- Build logs
- Git commit history
- Documentation
- Screenshots
- Collaboration messages
Deleting a secret from the latest file does not remove it from Git history.
Secret Exposure Response
Section titled “Secret Exposure Response”When a real credential is committed to a repository, CloudNova follows this process:
Secret Detected
↓
Treat Secret as Compromised
↓
Disable or Rotate Credential
↓
Identify Usage
↓
Review Logs
↓
Remove Secret from Code
↓
Clean Repository History if Required
↓
Store Replacement Securely
↓
Validate Applications
↓
Document IncidentThe credential should be rotated before repository clean-up because an attacker may already possess it.
Infrastructure as Code Security Testing
Section titled “Infrastructure as Code Security Testing”IaC scanning analyses templates before cloud resources are created.
Typical targets include:
- Terraform
- AWS CloudFormation
- Kubernetes manifests
- Dockerfiles
- Helm charts
- CI/CD workflow files
IaC scanning may identify:
- Public S3 buckets
- Open Security Groups
- Unencrypted storage
- Public databases
- Missing logging
- Excessive IAM permissions
- Disabled backups
- Missing tags
- Unrestricted network access
- Containers running as root
Infrastructure Code
↓
Syntax Validation
↓
Security Scan
↓
Policy Validation
↓
Approved DeploymentContainer Image Scanning
Section titled “Container Image Scanning”Container images contain:
- Operating-system packages
- Runtime libraries
- Application dependencies
- Application code
- Configuration files
A vulnerability in any layer can affect the deployed workload.
Dockerfile
↓
Container Build
↓
Image Scan
↓
Security Decision
├── Approved → Push and Deploy│└── Rejected → Remediate and RebuildContainer Security Controls
Section titled “Container Security Controls”CloudNova requires:
- Trusted base images
- Minimal operating-system packages
- Fixed image versions or digests
- Non-root execution
- No embedded credentials
- Image scanning
- Image tag immutability
- Encrypted repositories
- Restricted push permissions
- Removal of unnecessary tools
- Regular image rebuilding
- Deployment using approved image digests
Amazon ECR Image Scanning
Section titled “Amazon ECR Image Scanning”Amazon Elastic Container Registry can identify software vulnerabilities in container images.
CloudNova uses image scanning to:
- Scan newly pushed images.
- Identify vulnerable packages.
- Review severity levels.
- Prevent vulnerable releases.
- Track findings through security workflows.
- Reassess images when vulnerability information changes.
Risk-Based Security Gates
Section titled “Risk-Based Security Gates”Not every finding represents the same level of risk.
CloudNova defines security gates based on:
- Severity
- Exploitability
- Asset criticality
- Internet exposure
- Data sensitivity
- Availability of a fix
- Existing compensating controls
- Regulatory requirements
Example gate:
| Finding Severity | Pipeline Action |
|---|---|
| Critical | Block deployment |
| High | Block unless approved exception exists |
| Medium | Create remediation ticket |
| Low | Track and review |
| Informational | Record for awareness |
Security Exceptions
Section titled “Security Exceptions”There may be situations where an immediate fix is unavailable.
A security exception should include:
- Finding identifier
- Affected system
- Business justification
- Risk description
- Compensating controls
- System owner
- Security approval
- Expiration date
- Remediation owner
- Planned resolution date
Exceptions must not be permanent or undocumented.
False Positives
Section titled “False Positives”Security scanners can produce findings that are not exploitable in the specific application context.
CloudNova’s false-positive process includes:
Finding Generated
↓
Technical Review
↓
Evidence Collected
↓
Security Validation
↓
Approved Suppression
↓
Expiration and ReassessmentDevelopers must not suppress findings without independent review.
Enterprise Security Testing Pipeline
Section titled “Enterprise Security Testing Pipeline” Developer │ Git Commit │ Pull Request │ ┌─────────────────────┼─────────────────────┐ │ │ │ Secret Scanning SAST IaC Scan │ │ │ └─────────────────────┼─────────────────────┘ │ Dependency Scan │ Build │ Container Image Scan │ Staging Deployment │ DAST │ Security Gate Decision │ Production Approval │ Production Deployment │ Continuous Vulnerability MonitoringWhat Is Secret Management?
Section titled “What Is Secret Management?”Secret management is the controlled process of:
- Creating secrets
- Storing secrets
- Granting access
- Retrieving secrets
- Rotating secrets
- Monitoring usage
- Revoking secrets
- Deleting secrets securely
Secret management replaces hardcoded credentials with controlled runtime retrieval.
Hardcoded Secret Problem
Section titled “Hardcoded Secret Problem”Insecure design:
Application Code
↓
Username and Password Embedded in File
↓
Git Repository
↓
Build Artefact
↓
ProductionThe same secret may be copied into:
- Developer laptops
- Git history
- Build environments
- Container images
- Backups
- Logs
Secure Secret Retrieval
Section titled “Secure Secret Retrieval”Secure design:
Application
↓
IAM Role
↓
Secrets Management Service
↓
Authorised Runtime Retrieval
↓
Temporary Use in MemoryThe application code stores only the secret identifier, not the secret value.
AWS Secrets Manager
Section titled “AWS Secrets Manager”AWS Secrets Manager is designed to manage sensitive values such as:
- Database credentials
- API keys
- Application credentials
- OAuth tokens
- Third-party service credentials
Key capabilities include:
- Encrypted secret storage
- IAM-based access control
- Secret versioning
- Rotation workflows
- Audit logging through AWS CloudTrail
- Cross-Region replication options
- Integration with AWS services
Systems Manager Parameter Store
Section titled “Systems Manager Parameter Store”AWS Systems Manager Parameter Store manages configuration data and secrets.
Supported parameter types include:
| Parameter Type | Use |
|---|---|
| String | Plain configuration value |
| StringList | Comma-separated configuration values |
| SecureString | Encrypted sensitive value |
Examples include:
- Application environment name
- Feature flags
- Service endpoint
- Database hostname
- Encrypted application token
- Runtime configuration
Secrets Manager vs Parameter Store
Section titled “Secrets Manager vs Parameter Store”| Requirement | Secrets Manager | Parameter Store |
|---|---|---|
| Store sensitive values | Yes | Yes, using SecureString |
| Store general configuration | Possible, but not primary purpose | Yes |
| Built-in secret lifecycle focus | Yes | Limited |
| Secret rotation workflows | Yes | Requires separate implementation |
| Version support | Yes | Yes |
| Hierarchical paths | Secret naming can be structured | Strong hierarchical path model |
| Typical use | Credentials and rotating secrets | Configuration and selected encrypted parameters |
CloudNova generally uses:
- Secrets Manager for credentials requiring lifecycle and rotation management.
- Parameter Store for hierarchical application configuration and selected encrypted values.
Secret Naming Standard
Section titled “Secret Naming Standard”CloudNova uses predictable paths.
/cloudnova/development/customer-portal/database/cloudnova/staging/customer-portal/database/cloudnova/production/customer-portal/databaseParameter Store example:
/cloudnova/production/customer-portal/database/host/cloudnova/production/customer-portal/database/port/cloudnova/production/customer-portal/api/endpointNames should identify:
- Organisation
- Environment
- Application
- Component
- Secret or parameter purpose
Do not include the secret value in the name, tag or description.
Secret Encryption
Section titled “Secret Encryption”Secrets should be encrypted using AWS Key Management Service.
Secret Value
↓
AWS KMS Encryption
↓
Secrets Manager or Parameter Store
↓
Authorised DecryptionAccess may require permission to:
- Retrieve the secret or parameter
- Use the relevant KMS key for decryption
The KMS key policy and IAM permissions must both be reviewed.
Least-Privilege Secret Access
Section titled “Least-Privilege Secret Access”An application should access only the secrets it requires.
Example:
Customer Portal Role
├── Allowed: Customer Portal Database Secret├── Allowed: Customer Portal API Secret└── Denied: Finance, HR and Admin SecretsExample IAM policy:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "ReadCustomerPortalDatabaseSecret", "Effect": "Allow", "Action": [ "secretsmanager:GetSecretValue" ], "Resource": [ "arn:aws:secretsmanager:ap-south-1:123456789012:secret:cloudnova/production/customer-portal/database-*" ] } ]}Replace the account ID and secret ARN with your environment values.
Secret Resource Policies
Section titled “Secret Resource Policies”Secrets Manager resource-based policies can help control which identities or accounts may access a secret.
CloudNova reviews:
- IAM identity policies
- Secret resource policies
- KMS key policies
- AWS Organizations Service Control Policies
- Permission boundaries
- Session policies
Effective access is determined by the combined policy evaluation.
Secret Rotation
Section titled “Secret Rotation”Secret rotation replaces an existing secret with a new value.
Current Secret
↓
Generate New Secret
↓
Update Target Service
↓
Test New Secret
↓
Promote New Version
↓
Retire Old SecretRotation reduces the time a compromised credential remains useful.
Rotation Considerations
Section titled “Rotation Considerations”Before enabling rotation, verify:
- The target service supports credential updates.
- The application retrieves secrets dynamically.
- Connections can recover after rotation.
- Rotation permissions follow least privilege.
- Failed rotations generate alerts.
- Rollback procedures are documented.
- Rotation does not interrupt production.
Secret Caching
Section titled “Secret Caching”Applications may cache secrets to reduce latency and API requests.
Caching must be designed carefully.
The application should:
- Use a supported caching approach.
- Set an appropriate cache lifetime.
- Refresh after rotation.
- Protect cached values in memory.
- Avoid writing secrets to local files.
- Handle service failures securely.
Secrets in CI/CD Pipelines
Section titled “Secrets in CI/CD Pipelines”A pipeline may need temporary access to:
- Package registry credentials
- Deployment tokens
- Signing keys
- Test database credentials
Secure pipeline flow:
CodeBuild Role
↓
Authorised Secret Request
↓
Secrets Manager
↓
Secret Used During Build
↓
Secret Not Printed or Stored in ArtefactThe build role should receive access only to the exact secret required.
Preventing Secrets in Logs
Section titled “Preventing Secrets in Logs”Applications and pipelines must not:
- Echo secret values.
- Print all environment variables.
- Enable unsafe debug output.
- Include tokens in URLs.
- Log full request headers.
- Log database connection strings.
- Include secrets in error messages.
Review build scripts for commands such as:
envprintenvset -xThese commands may expose sensitive values when used without care.
Enterprise Secret-Management Architecture
Section titled “Enterprise Secret-Management Architecture” Developers and Applications │ Authenticated Identity │ ┌───────────────┴────────────────┐ │ │ IAM Role or STS Pipeline Service Role │ │ └───────────────┬────────────────┘ │ AWS Secrets Manager │ AWS KMS Encryption │ ┌──────────────────┼──────────────────┐ │ │ │ Database Secret API Credentials Signing Material │ │ │ └──────────────────┼──────────────────┘ │ AWS CloudTrail Logs │ Monitoring and AlertingMonitoring Secret Activity
Section titled “Monitoring Secret Activity”CloudNova monitors:
GetSecretValueactivity- Secret creation
- Secret deletion
- Secret policy changes
- Rotation failures
- KMS key-policy changes
- Unusual retrieval patterns
- Cross-account access
- Access-denied events
- Retrieval from unexpected Regions
CloudTrail events should be delivered to a protected central logging account.
Secret Incident Response
Section titled “Secret Incident Response”A suspected secret compromise requires immediate action.
Compromise Suspected
↓
Identify Secret and Consumers
↓
Disable or Rotate Secret
↓
Restrict Access
↓
Review CloudTrail
↓
Search Source Code and Logs
↓
Validate Applications
↓
Remove Exposed Copies
↓
Document and Improve ControlsSecurity Testing Metrics
Section titled “Security Testing Metrics”CloudNova tracks:
| Metric | Purpose |
|---|---|
| Critical Findings per Build | Measures release risk |
| Security Gate Failure Rate | Shows how often releases are blocked |
| Mean Time to Remediate | Measures remediation speed |
| Exposed Secret Events | Tracks credential-handling failures |
| Vulnerable Dependencies | Measures software supply-chain risk |
| Container Images Above Threshold | Tracks container risk |
| Exception Age | Identifies overdue risk acceptances |
| Secret Rotation Success Rate | Measures lifecycle reliability |
| Secrets Without Recent Rotation | Identifies credential risk |
| False-Positive Rate | Measures scanner quality |
🛠 Lab 01 — Create a Secret in AWS Secrets Manager
Section titled “🛠 Lab 01 — Create a Secret in AWS Secrets Manager”Objective
Section titled “Objective”Create, retrieve and update a database credential securely.
Prerequisites
Section titled “Prerequisites”Verify your AWS identity:
aws sts get-caller-identitySet the Region:
aws configure set region ap-south-1Step 1 — Create a Test Secret
Section titled “Step 1 — Create a Test Secret”Run in Git Bash:
aws secretsmanager create-secret \ --name cloudnova/development/customer-portal/database \ --description "Development database credential for the CloudNova customer portal" \ --secret-string '{"username":"cloudnova_app","password":"Replace-With-A-Strong-Lab-Password"}'PowerShell:
aws secretsmanager create-secret ` --name cloudnova/development/customer-portal/database ` --description "Development database credential for the CloudNova customer portal" ` --secret-string '{\"username\":\"cloudnova_app\",\"password\":\"Replace-With-A-Strong-Lab-Password\"}'Use only a temporary lab credential. Do not enter an existing production password into your command history.
Step 2 — Describe the Secret
Section titled “Step 2 — Describe the Secret”aws secretsmanager describe-secret \ --secret-id cloudnova/development/customer-portal/databaseThe command returns metadata but does not display the secret value.
Step 3 — Retrieve the Secret
Section titled “Step 3 — Retrieve the Secret”aws secretsmanager get-secret-value \ --secret-id cloudnova/development/customer-portal/databaseFor a more focused response:
aws secretsmanager get-secret-value \ --secret-id cloudnova/development/customer-portal/database \ --query SecretString \ --output textStep 4 — Update the Secret
Section titled “Step 4 — Update the Secret”aws secretsmanager put-secret-value \ --secret-id cloudnova/development/customer-portal/database \ --secret-string '{"username":"cloudnova_app","password":"Replace-With-A-New-Lab-Password"}'Step 5 — Review Secret Versions
Section titled “Step 5 — Review Secret Versions”aws secretsmanager list-secret-version-ids \ --secret-id cloudnova/development/customer-portal/databaseVerification
Section titled “Verification”Confirm that:
- The secret exists.
- The secret contains the new lab value.
- Multiple versions appear after the update.
- The secret value does not exist in your application source code.
🛠 Lab 02 — Create Parameter Store Configuration
Section titled “🛠 Lab 02 — Create Parameter Store Configuration”Objective
Section titled “Objective”Store plain configuration and encrypted sensitive data using Parameter Store.
Step 1 — Create a String Parameter
Section titled “Step 1 — Create a String Parameter”aws ssm put-parameter \ --name "/cloudnova/development/customer-portal/database/host" \ --description "Development database endpoint" \ --type String \ --value "development-database.internal" \ --overwriteStep 2 — Create a SecureString Parameter
Section titled “Step 2 — Create a SecureString Parameter”aws ssm put-parameter \ --name "/cloudnova/development/customer-portal/api/token" \ --description "Temporary development API token" \ --type SecureString \ --value "Replace-With-A-Temporary-Lab-Token" \ --overwriteStep 3 — Retrieve the Plain Parameter
Section titled “Step 3 — Retrieve the Plain Parameter”aws ssm get-parameter \ --name "/cloudnova/development/customer-portal/database/host"Step 4 — Retrieve the Encrypted Parameter Without Decryption
Section titled “Step 4 — Retrieve the Encrypted Parameter Without Decryption”aws ssm get-parameter \ --name "/cloudnova/development/customer-portal/api/token"Step 5 — Retrieve the Parameter with Decryption
Section titled “Step 5 — Retrieve the Parameter with Decryption”aws ssm get-parameter \ --name "/cloudnova/development/customer-portal/api/token" \ --with-decryptionStep 6 — Retrieve Parameters by Path
Section titled “Step 6 — Retrieve Parameters by Path”aws ssm get-parameters-by-path \ --path "/cloudnova/development/customer-portal" \ --recursive \ --with-decryptionVerification
Section titled “Verification”Confirm that:
- The database host is stored as a
String. - The API token is stored as a
SecureString. - The encrypted value is returned only when decryption is requested and authorised.
- The hierarchical parameter path is easy to identify.
🛠 Lab 03 — Create a Least-Privilege Secret Access Policy
Section titled “🛠 Lab 03 — Create a Least-Privilege Secret Access Policy”Objective
Section titled “Objective”Allow an application role to retrieve only one specific secret.
Step 1 — Retrieve the Secret ARN
Section titled “Step 1 — Retrieve the Secret ARN”aws secretsmanager describe-secret \ --secret-id cloudnova/development/customer-portal/database \ --query ARN \ --output textStep 2 — Create the IAM Policy Document
Section titled “Step 2 — Create the IAM Policy Document”Create customer-portal-secret-policy.json.
Replace the example ARN.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "RetrieveDevelopmentDatabaseSecret", "Effect": "Allow", "Action": [ "secretsmanager:DescribeSecret", "secretsmanager:GetSecretValue" ], "Resource": [ "arn:aws:secretsmanager:ap-south-1:123456789012:secret:cloudnova/development/customer-portal/database-*" ] } ]}Step 3 — Review the Policy
Section titled “Step 3 — Review the Policy”Confirm that the policy does not allow:
secretsmanager:*Confirm that the resource is not:
*Step 4 — Validate with IAM Policy Simulation
Section titled “Step 4 — Validate with IAM Policy Simulation”Replace the policy source ARN and secret ARN.
aws iam simulate-principal-policy \ --policy-source-arn arn:aws:iam::123456789012:role/CloudNovaCustomerPortalRole \ --action-names secretsmanager:GetSecretValue \ --resource-arns arn:aws:secretsmanager:ap-south-1:123456789012:secret:cloudnova/development/customer-portal/database-EXAMPLEExpected Result
Section titled “Expected Result”The application role should:
- Retrieve the authorised database secret.
- Be unable to retrieve unrelated secrets.
- Be unable to create, modify or delete secrets.
🛠 Lab 04 — Detect a Secret Before Commit
Section titled “🛠 Lab 04 — Detect a Secret Before Commit”Objective
Section titled “Objective”Understand how secret scanning prevents credential exposure.
Scenario
Section titled “Scenario”A developer creates the following unsafe file:
database_username=cloudnova_admindatabase_password=Example-Do-Not-Use- Create a temporary local practice repository.
- Add a test configuration file containing fake credentials.
- Run an approved secret-scanning tool.
- Confirm that the pattern is detected.
- Remove the value.
- Replace it with a secret reference.
- Run the scanner again.
- Confirm that the repository passes.
Secure Replacement Example
Section titled “Secure Replacement Example”Insecure:
database_password = "Example-Do-Not-Use"Secure design:
secret_id = "cloudnova/development/customer-portal/database"The application should retrieve the value at runtime using its IAM role.
Evidence
Section titled “Evidence”Document:
- File containing the test secret
- Scanner finding
- Remediation
- Successful rescanning result
- Recommended repository control
Use fake lab values only. Never intentionally commit real credentials.
🛠 Lab 05 — Enable Amazon Inspector ECR Scanning
Section titled “🛠 Lab 05 — Enable Amazon Inspector ECR Scanning”Objective
Section titled “Objective”Enable vulnerability monitoring for Amazon ECR container images.
Step 1 — Confirm Current Identity
Section titled “Step 1 — Confirm Current Identity”aws sts get-caller-identityStep 2 — Enable Amazon Inspector for ECR
Section titled “Step 2 — Enable Amazon Inspector for ECR”aws inspector2 enable \ --resource-types ECRStep 3 — Check Inspector Status
Section titled “Step 3 — Check Inspector Status”aws inspector2 batch-get-account-statusStep 4 — Create an ECR Repository
Section titled “Step 4 — Create an ECR Repository”aws ecr create-repository \ --repository-name cloudnova/customer-portal \ --image-scanning-configuration scanOnPush=true \ --image-tag-mutability IMMUTABLEStep 5 — Describe the Repository
Section titled “Step 5 — Describe the Repository”aws ecr describe-repositories \ --repository-names cloudnova/customer-portalStep 6 — Review Inspector Findings
Section titled “Step 6 — Review Inspector Findings”After pushing an authorised lab image and allowing the scan to complete:
aws inspector2 list-findings \ --filter-criteria '{ "resourceType": [ { "comparison": "EQUALS", "value": "AWS_ECR_CONTAINER_IMAGE" } ] }'Verification
Section titled “Verification”Confirm that:
- Inspector is enabled for ECR.
- The repository exists.
- Image tags are immutable.
- Scan-on-push is configured.
- Findings can be queried after an image is scanned.
Amazon Inspector availability, supported Regions and charges should be reviewed before enabling it in a non-lab account.
🛠 Lab 06 — Build a Security Testing Gate
Section titled “🛠 Lab 06 — Build a Security Testing Gate”Objective
Section titled “Objective”Create a pipeline decision process based on finding severity.
Security Gate Logic
Section titled “Security Gate Logic”Secret Detected?
├── Yes → Stop Pipeline└── No → Continue
Critical Vulnerability Detected?
├── Yes → Stop Pipeline└── No → Continue
High Vulnerability Detected?
├── Approved Exception → Continue with Tracking└── No Exception → Stop Pipeline
Required Security Tests Passed?
├── Yes → Permit Staging Deployment└── No → Stop PipelineStudent Tasks
Section titled “Student Tasks”Create a pipeline policy containing:
- Required scanners
- Severity thresholds
- Blocking conditions
- Exception process
- Finding ownership
- Remediation timelines
- Evidence-retention requirements
- Escalation process
Deliverable
Section titled “Deliverable”| Test | Blocking Threshold | Owner | Required Evidence |
|---|---|---|---|
| Secret Scan | Any confirmed secret | Development | Clean rescanning result |
| SAST | Critical | Application Security | Remediation report |
| SCA | Critical or unapproved High | Development | Updated dependency report |
| IaC Scan | Critical misconfiguration | Cloud Engineering | Corrected plan |
| Container Scan | Critical or unapproved High | Platform Team | New image digest |
| DAST | Critical exploitable finding | Application Team | Retest result |
🛠 Lab 07 — Design Secret Rotation
Section titled “🛠 Lab 07 — Design Secret Rotation”Objective
Section titled “Objective”Create a rotation plan for CloudNova’s production database credential.
Document
Section titled “Document”- Secret owner
- Application owner
- Rotation frequency
- Rotation trigger
- Target database
- Application retrieval process
- Rotation permissions
- Validation process
- Failure notification
- Rollback procedure
- Emergency rotation procedure
- Audit evidence
Rotation Workflow
Section titled “Rotation Workflow”Rotation Triggered
↓
New Credential Generated
↓
Database Updated
↓
Application Retrieves New Version
↓
Connectivity Tested
├── Successful → Complete Rotation│└── Failed → Roll Back and Alert💻 AWS CLI Reference
Section titled “💻 AWS CLI Reference”List Secrets
Section titled “List Secrets”aws secretsmanager list-secretsDescribe a Secret
Section titled “Describe a Secret”aws secretsmanager describe-secret \ --secret-id cloudnova/development/customer-portal/databaseRetrieve a Secret
Section titled “Retrieve a Secret”aws secretsmanager get-secret-value \ --secret-id cloudnova/development/customer-portal/databaseReview Secret Versions
Section titled “Review Secret Versions”aws secretsmanager list-secret-version-ids \ --secret-id cloudnova/development/customer-portal/databaseReview Rotation Configuration
Section titled “Review Rotation Configuration”aws secretsmanager describe-secret \ --secret-id cloudnova/development/customer-portal/database \ --query '{RotationEnabled:RotationEnabled,RotationLambdaARN:RotationLambdaARN,RotationRules:RotationRules}'List Parameters
Section titled “List Parameters”aws ssm describe-parametersRetrieve Parameter Metadata
Section titled “Retrieve Parameter Metadata”aws ssm describe-parameters \ --parameter-filters \ "Key=Name,Option=BeginsWith,Values=/cloudnova/development/customer-portal"Retrieve a SecureString
Section titled “Retrieve a SecureString”aws ssm get-parameter \ --name "/cloudnova/development/customer-portal/api/token" \ --with-decryptionList ECR Repositories
Section titled “List ECR Repositories”aws ecr describe-repositoriesList ECR Images
Section titled “List ECR Images”aws ecr list-images \ --repository-name cloudnova/customer-portalList Amazon Inspector Findings
Section titled “List Amazon Inspector Findings”aws inspector2 list-findings✅ Verification Checklist
Section titled “✅ Verification Checklist”Verify that you can:
- Explain why continuous security testing is required.
- Differentiate SAST, DAST and SCA.
- Explain secret scanning.
- Identify risks in open-source dependencies.
- Explain the purpose of an SBOM.
- Scan Infrastructure as Code before deployment.
- Explain container image scanning.
- Define risk-based security gates.
- Create a secret using Secrets Manager.
- Create a
SecureStringparameter. - Retrieve secrets securely.
- Design least-privilege secret access.
- Explain secret rotation.
- Prevent secret exposure in logs.
- Enable Amazon Inspector ECR scanning.
- Respond to a compromised credential.
🔍 Troubleshooting
Section titled “🔍 Troubleshooting”Problem — Access Denied When Retrieving a Secret
Section titled “Problem — Access Denied When Retrieving a Secret”Review:
secretsmanager:GetSecretValuepermission- Secret ARN
- Secret resource policy
- KMS key policy
kms:Decryptpermission- Permission boundary
- Service Control Policy
- AWS Region
- Current AWS identity
Run:
aws sts get-caller-identityaws secretsmanager describe-secret \ --secret-id YOUR_SECRET_IDProblem — SecureString Cannot Be Decrypted
Section titled “Problem — SecureString Cannot Be Decrypted”Review:
ssm:GetParameterpermissionkms:Decryptpermission- KMS key policy
- Correct parameter name
--with-decryptionoption- Correct AWS Region
Problem — Secret Appears in Build Logs
Section titled “Problem — Secret Appears in Build Logs”Immediately:
- Stop the build if it is still running.
- Rotate the exposed secret.
- Restrict access to the logs.
- Review who accessed the logs.
- Remove unsafe logging commands.
- Run the build again using a temporary lab credential.
- Document the incident.
Problem — Application Stops Working After Rotation
Section titled “Problem — Application Stops Working After Rotation”Verify:
- Application secret caching
- Database credential update
- Secret version stage
- Application IAM role
- Network connectivity
- Connection-pool refresh
- Rotation Lambda logs
- Rollback process
Problem — Inspector Does Not Show ECR Findings
Section titled “Problem — Inspector Does Not Show ECR Findings”Verify:
- Inspector is enabled.
- ECR scanning is configured.
- An image has been pushed.
- The scan has completed.
- The image is within the configured monitoring scope.
- You are viewing the correct AWS Region.
- Your identity can list Inspector findings.
Problem — Security Scanner Blocks Every Build
Section titled “Problem — Security Scanner Blocks Every Build”Review:
- Severity threshold
- Scanner rule configuration
- Duplicate findings
- Unsupported files
- Baseline configuration
- False-positive process
- Approved exception expiration
- Scanner version
Do not disable the security gate simply to make the pipeline pass.
🏢 Enterprise Best Practices
Section titled “🏢 Enterprise Best Practices”CloudNova standards include:
- Run security testing on every Pull Request.
- Combine SAST, DAST, SCA, IaC and container scanning.
- Block confirmed secrets immediately.
- Rotate exposed credentials before repository clean-up.
- Use risk-based security thresholds.
- Require independent approval for suppressions.
- Store credentials in Secrets Manager.
- Use Parameter Store for structured configuration.
- Encrypt sensitive parameters using
SecureString. - Apply least-privilege secret access.
- Use IAM roles and temporary credentials.
- Never print secrets in logs.
- Plan and test credential rotation.
- Monitor secret retrieval and policy changes.
- Scan all production container images.
- Rebuild images when critical vulnerabilities are identified.
- Maintain evidence for audits and security reviews.
- Track findings until verified closure.
🚫 Common Mistakes
Section titled “🚫 Common Mistakes”❌ Depending on only one security scanner.
❌ Running scans only before production releases.
❌ Ignoring transitive dependencies.
❌ Allowing critical findings to proceed without review.
❌ Suppressing findings without evidence or expiration.
❌ Committing .env files containing credentials.
❌ Assuming deleting a secret from the latest commit removes it from Git history.
❌ Storing production passwords as plaintext pipeline variables.
❌ Giving every application access to every secret.
❌ Using wildcard secret permissions.
❌ Printing environment variables in build logs.
❌ Rotating credentials without testing application behaviour.
❌ Deploying container images without scanning them.
❌ Continuing to use old vulnerable container images.
❌ Treating scanner output as a replacement for human security analysis.
🧪 DIY Enterprise Challenge
Section titled “🧪 DIY Enterprise Challenge”CloudNova is launching a new online banking application.
Design an enterprise security-testing and secret-management solution containing:
- Pull Request secret scanning.
- Static application security testing.
- Software composition analysis.
- Infrastructure as Code scanning.
- Container image scanning.
- Staging DAST.
- Risk-based security gates.
- Security exception management.
- AWS Secrets Manager.
- Systems Manager Parameter Store.
- Customer-managed KMS keys.
- Least-privilege application roles.
- Database secret rotation.
- CloudTrail monitoring.
- Security alerts.
- Credential-compromise response.
Prepare the following deliverables:
- Security Testing Architecture
- Pipeline Security Gate Matrix
- Secret Naming Standard
- Secrets Manager Access Policy
- Parameter Store Structure
- Rotation Workflow
- Container Scanning Standard
- Security Exception Template
- Secret Exposure Response Runbook
- Security Metrics Dashboard
- Executive Risk Summary
📊 Knowledge Check
Section titled “📊 Knowledge Check”- What is the difference between SAST and DAST?
- What is Software Composition Analysis?
- Why must transitive dependencies be scanned?
- What is an SBOM?
- What types of information can secret scanners detect?
- Why must exposed credentials be rotated immediately?
- What is Infrastructure as Code scanning?
- Why should container images be scanned before deployment?
- How should a pipeline respond to a critical vulnerability?
- What is a security exception?
- What is the difference between Secrets Manager and Parameter Store?
- What is a
SecureStringparameter? - Why should applications use IAM roles to retrieve secrets?
- What permissions may be required to decrypt a customer-managed secret?
- Why should secrets never appear in logs?
- What is secret rotation?
- How can caching affect secret rotation?
- Which AWS service can scan Amazon ECR images?
- Which events should be monitored for secret-management security?
- What actions should be taken after a secret compromise?
💡 Key Takeaways
Section titled “💡 Key Takeaways”After completing this lesson, you should understand:
- Enterprise application security requires multiple testing methods because each scanner evaluates a different part of the software-delivery process.
- SAST analyses source code, DAST evaluates running applications and SCA identifies risks in third-party components.
- Secret scanning prevents passwords, tokens, access keys and private keys from entering source repositories and build artefacts.
- IaC and container scanning identify security weaknesses before infrastructure and workloads are deployed.
- Security gates should block unacceptable risks while using documented, time-limited exception processes.
- AWS Secrets Manager provides controlled storage and lifecycle management for application credentials and other secrets.
- Systems Manager Parameter Store supports hierarchical configuration management and encrypted
SecureStringvalues. - Applications and pipelines should retrieve secrets using dedicated least-privilege IAM roles and temporary credentials.
- Secret rotation, monitoring and incident-response processes are essential parts of credential lifecycle management.
- Confirmed secret exposure must be treated as a security incident, with immediate credential rotation and investigation.
🚀 Next Lesson
Section titled “🚀 Next Lesson”➡️ Lesson 05 — Enterprise DevSecOps & Infrastructure as Code Security Project and Module Review