# Application Security and IAM

> Chapter 12 of the Courseiva GOOGLE-PCD curriculum — https://courseiva.com/learn/google-pcd/application-security-and-iam

**Official objective:** 3.3 — Implement authentication, authorization, and secure access using IAM and service accounts.

## Introduction

How do you stop a stranger from wandering into your cloud application and reading your database? That’s the core problem of application security: keeping the wrong people out while letting the right people do their jobs. For the Google Professional Cloud Developer exam, you must understand how IAM (Identity and Access Management) and service accounts act as the bouncers and key-makers of your cloud system.

## The Property Lease and Key System Analogy

When you move into a rented office space, the property manager first checks your ID and verifies that your company’s name is on the lease (authentication). Once you’re proven who you say you are, they give you a key card that only opens your specific office door and the shared meeting rooms you’re allowed to use (authorisation). 

 Now zoom out to a whole office building with dozens of companies. Each company needs its own set of keys for its own offices, and no company should accidentally wander into another’s storage closet. The building manager (the IAM system) keeps a master list: who is employed by which company, which keys each employee gets, and what times of day those keys work. Every time an employee enters a door, the system logs it (audit trail). If an employee leaves the company, the building manager instantly deactivates their key card (revoking access). This is exactly how Google Cloud’s IAM works: it manages identities (leases), assigns permissions (keys), and enforces boundaries (walls between offices) so that no one can access resources they don’t own.

## Core explanation

Application security is the practice of protecting your software and its data from unauthorised access, attacks, and breaches. In the cloud, this starts with IAM — Identity and Access Management. IAM is a framework that lets you control who (identity) can do what (access) on which resources (your cloud services). It is the single central place you manage all permissions in Google Cloud. 

 Before IAM, system administrators would manually configure individual servers to allow or deny users. That was slow and error-prone, especially as companies grew. IAM replaces that chaos with a rule-based system managed through a dashboard or API. It is foundational because if your IAM is misconfigured, everything else — your storage, your compute instances, your databases — is exposed. 

 Let us define the key pieces. An identity is a person, group, or application that needs access. In Google Cloud, identities are represented by accounts. Two main types exist: user accounts (for humans) and service accounts (for applications or virtual machines). A service account is a special kind of account that belongs to your application, not a person. It is like a robot worker that has its own badge to access things. 

 A permission is a specific action that can be taken on a resource, like "read a storage bucket" or "write to a database". Permissions are not assigned directly to identities. Instead, an IAM role is a collection of permissions. You attach roles to identities. For example, the role "Storage Object Viewer" includes permissions like storage.objects.get (to read an object) and storage.objects.list (to list objects in a bucket). You can assign that role to a user or a service account. 

 IAM policies are the documents that bind one or more members (identities) to one or more roles. A policy specifies: who (the member), what (the role), and where (the resource). You can attach policies at different levels of the resource hierarchy: the organisation level, the folder level, the project level, or even on a specific resource called a resource itself. Policies are inherited unless overridden. 

 Remember these distinctions: 

 - Authentication: Verifying that an identity is who they claim to be. (Example: logging in with a password and multi-factor authentication.) 
 - Authorisation: Determining what an authenticated identity is allowed to do. (Example: after logging in, you may or may not have permission to delete a database.) 
 - Audit: Logging who did what and when, so you can detect misuse. 

 Service accounts are vital for application security because they remove the need to store human passwords in application code. Instead, you use secure keys or workload identity federation. Another important concept is least privilege, meaning you only grant the minimum permissions needed for a task. Google Cloud’s IAM makes this easier by offering predefined roles (like roles/storage.objectViewer) which are collections of permissions designed for specific job functions, and custom roles where you select exactly the permissions you need. 

 The exam also tests your understanding of how IAM integrates with other security services like Cloud KMS (Key Management Service) for encryption keys, and VPC Service Controls to restrict data movement outside your virtual network boundaries. IAM is the entry point to all security policies in Google Cloud.

## Real-world context

You work as a developer at a retail company that runs an e-commerce application on Google Cloud. Your application processes customer orders, stores product images in Cloud Storage, and runs on Compute Engine virtual machines. Here is how you apply application security and IAM in your daily work. 

 Step 1: You create a service account for your application backend. Instead of hardcoding a password into your code, you create a service account named ecommerce-backend-sa. You generate a JSON key file (a token) and securely store it in Cloud Secret Manager. You then assign that service account a role of "roles/cloudsql.client" so it can connect to your Cloud SQL database (authentication as a machine, not a person). 

 Step 2: You set up IAM policies at the project level. You add your team members: a junior developer gets "roles/storage.objectViewer" so they can look at product images but not modify them; a senior developer gets "roles/storage.objectAdmin" to upload and delete images for product updates. You also create a custom role with only the permission "compute.instances.start" and "compute.instances.stop" for a DevOps engineer who manages nightly instance shutdowns. 

 Step 3: You configure Cloud Audit Logs to record all IAM policy changes. When a security incident happens (e.g., a storage bucket was accidentally made public), you examine the logs to see who changed the policy. The logs show an Admin user assigned "roles/storage.objectAdmin" at the bucket level instead of the project level — that was the mistake. You revoke the incorrect policy and review the least-privilege principle with the team. 

 Step 4: You use VPC Service Controls to create a perimeter around your project. This ensures that even if an IAM role is too permissive, the data cannot egress (leave) your virtual network, adding a second layer of security. You test this by trying to upload a file from a personal laptop outside the office — it fails because the perimeter blocks it. 

 In practice, you also manage service account keys. You rotate keys every 90 days using Cloud Key Management Service. You monitor the IAM Recommender to get suggestions: if a role has not been used in 30 days, IAM Recommender flags it as potentially over-privileged. You then modify the role to remove unused permissions. This continuous cycle of granting, auditing, and refining permissions is the daily reality of application security with IAM.

## Exam focus

The PCD exam tests your ability to design and implement IAM for application security in Google Cloud. Expect multiple-choice questions that present a scenario and ask which IAM role, policy, or service account configuration best meets security and business requirements. Here are the specific concepts and traps to know. 

 - Role types: Predefined roles (like roles/bigquery.dataViewer), basic roles (Owner/Editor/Viewer), and custom roles. The exam loves to test when you should use a predefined role vs. a custom role for least privilege. Basic roles are broadly permissive and should be avoided in production. 

 - Service accounts vs. user accounts: Questions often ask where to use each. Service accounts are for applications, not humans. A trap: using a service account key stored in source code (insecure) vs. using Workload Identity Federation (secure for on-premises workloads). 

 - Resource hierarchy: Policies are inherited from organisation to folder to project. A question might give a policy at the organisation level and ask what permissions a user has at the project level. Traps: remember that deny policies override allow policies but explicit deny at a lower level blocks inheritance. 

 - IAM conditions: Added in Google Cloud, these are boolean expressions that grant access only under specific conditions (e.g., only requests from a certain IP range). The exam may ask when to use IAM conditions vs. separate roles. 

 - Common exam traps: 

 - Confusing authentication (verifying identity) with authorisation (granting actions). A scenario about “a user on a mobile app” is typically about authentication, not IAM roles. 
 - Thinking that service accounts can be members of Google Groups — they cannot. Service accounts are standalone identities. 
 - Assuming that deleting a user’s IAM policy immediately revokes all access — session timeouts may keep permissions active for up to 15 minutes. 
 - Misunderstanding that IAM policies are global — they apply to all regions unless you use IAM conditions to restrict. 

 Key definitions you must memorise: 
 
 - “roles/storage.objectAdmin” — full control of objects but not bucket configuration. 
 - “roles/iam.serviceAccountUser” — allows a resource to impersonate a service account (a common exam concept). 
 - “roles/bigquery.dataOwner” — can modify and share datasets. 
 - “Conditional role bindings” — policies with IP, date, or resource restrictions. 

 The exam also tests integration with other services: Cloud KMS for encryption, Cloud Audit Logs for compliance, and VPC Service Controls for data exfiltration prevention. Focus on least privilege and the principle that every over-permissioned role is a security risk.

## Step by step

1. **Identify the Workload Identity Type** — Determine whether the resource that needs access is a human user, an application running in Compute Engine, or a service on another cloud. This choice decides whether you use a user account, service account, or workload identity federation.
2. **Create or Select the Right Identity** — For an application, create a service account in the Google Cloud console. For a human, ensure they have a Google account or Cloud Identity profile. For an on-premises app, set up workload identity federation linking to your external identity provider.
3. **Define the Roles and Permissions** — Select the minimal set of permissions needed: start with a predefined role (like storage.objectAdmin), then consider a custom role for rare or combined permissions. Avoid basic roles (Owner, Editor, Viewer) in production as they are too permissive.
4. **Attach the IAM Policy at the Correct Level** — Add the identity as a member to a role in an IAM policy at the appropriate hierarchy level — resource-level for fine-grained control, project-level for general access, or folder/organisation for broad teams. Use IAM conditions if time, IP, or resource restrictions are needed (e.g., allow only from 9am-5pm).
5. **Test and Audit the Policy** — Simulate the access from the identity’s perspective using the IAM Policy Troubleshooter. Enable Cloud Audit Logs to record all permission changes and accesses. Use IAM Recommender periodically to identify unneeded permissions and tighten the policy.

## Comparisons

### Predefined Role vs Custom Role

**Predefined Role:**
- Pre-built by Google Cloud with a set of permissions for common job functions.
- Automatically updated when Google adds new features to the service.
- Cannot remove individual permissions from the set.

**Custom Role:**
- User-defined by selecting specific permissions needed.
- Not automatically updated; must be manually maintained when services change.
- Supports exact least privilege but requires more maintenance.

### IAM Policy (Allow) vs Deny Policy (Organization Policy)

**IAM Policy (Allow):**
- By default, an allow policy grants permissions if a binding exists.
- Permissions are additive: if any allow policy gives access, it is granted.
- Cannot block access that is granted by another allow policy.

**Deny Policy (Organization Policy):**
- Explicitly blocks access regardless of allow policies.
- Overrides all allow policies, even at higher levels.
- Used for mandatory access controls (e.g., prevent all data exports).

### Service Account Key vs Workload Identity Federation

**Service Account Key:**
- A long-lived JSON key that can be downloaded and stored.
- Manual rotation required; key leakage is a major risk.
- Best for applications running in Google Cloud (Compute Engine, GKE).

**Workload Identity Federation:**
- No keys to store; uses an external identity provider (e.g., AWS, on-prem AD).
- Short-lived tokens automatically refreshed; reduces risk.
- Best for applications running outside Google Cloud (hybrid or multi-cloud).

## Diagram

_IAM flow: identities (users/service accounts) authenticate, IAM checks policy bindings to roles, and permissions are applied on resources, with inheritance from organisation down to project level._

```mermaid
flowchart TD
    U[User] -->|Authenticate| G[Google Cloud IAM]
    SA[Service Account] -->|Authenticate with Key| G
    G -->|Check Policy| R[Resource e.g. Cloud Storage, Compute Engine]
    P[IAM Policy] -->|Binds| Role[Role - set of permissions]
    Role -->|Grants| Permission[Permissions like storage.objects.get]
    P -->|Inherits| Org[Organisation]
    Org --> Folder
    Folder --> Project
    Project --> R
    G -->|Log| Audit[Cloud Audit Logs]
```

## Common misconceptions

- **Misconception:** Service accounts are like regular user accounts and can be used by humans to log in. **Reality:** Service accounts are designed for applications or virtual machines, not human users. They should never be used interactively. They authenticate with a private key, not a password, and are best used with workload identity federation or key rotation. (Newcomers often think a service account is just a robot user that people can impersonate. This misunderstanding leads to insecure practices like storing service account keys in source code.)
- **Misconception:** IAM roles are set once and rarely need to be changed. **Reality:** IAM roles should be reviewed and refined regularly using tools like IAM Recommender to remove unused permissions and reduce the attack surface (least privilege). (In initial cloud setups, developers often grant broad roles like Editor or Owner to "get things working" then never revisit them. This creates major security holes as the application evolves.)
- **Misconception:** If I give someone the ‘Viewer’ role, they can see everything but can take no actions at all. **Reality:** The Viewer role includes the permission to list and read most resources, but some resources like Cloud Storage bucket objects might require additional grants (e.g., storage.objectViewer) because they are separate resource types. (It is easy to oversimplify basic roles. Beginners assume Viewer is all-seeing but Google Cloud resource hierarchy makes it possible for some data to still be hidden without explicit permissions.)
- **Misconception:** IAM policies apply only to the project where they are defined and have no effect on other projects. **Reality:** IAM policies defined at the organisation or folder level are inherited by all child projects unless explicitly overridden. They can affect resources across multiple projects. (People think of IAM as per-project because they usually work in one project at a time. Inheritance is a subtle but important concept that catches candidates off guard on the exam.)
- **Misconception:** If two IAM policies grant the same permission, the more restrictive one wins. **Reality:** By default, IAM permissions are additive: if any policy grants the permission, it is granted. A deny policy (using Google Cloud’s Deny Organization Policy) can override and block access, but standard policies are union-based, not intersection-based. (This confusion comes from network Access Control Lists (ACLs) where deny rules often take precedence. Beginners carry that mental model to IAM, but identity-based access control works differently.)

## Key takeaways

- IAM (Identity and Access Management) in Google Cloud centrally controls who can do what on which resources through policies that bind members to roles.
- Service accounts are non-human identities for applications and should never be used by people or stored in source code — always use secure key management.
- Least privilege means granting only the exact permissions required; over-permissioned roles are the most common source of cloud security breaches.
- IAM policies are inherited from the organisation level down to projects, so one organisation-wide policy can impact multiple projects unless overridden.
- Authentication verifies identity (e.g., login), while authorisation determines allowed actions (e.g., roles); the exam tests both separately and together.
- IAM Recommender proactively suggests removing unused permissions, helping you maintain least privilege automatically over time.

## FAQ

**What is the difference between a user account and a service account in Google Cloud IAM?**

A user account is for people and is linked to a Google or Cloud Identity login. A service account is for applications and virtual machines and authenticates using a private key or workload identity federation, not a password.

**Can a service account be a member of a Google Group?**

No, service accounts cannot be added as members of Google Groups. They are standalone identities. You can grant roles directly to a service account or impersonate it using another identity with the roles/iam.serviceAccountUser role.

**What happens when I delete an IAM policy?**

Deleting an IAM policy removes the role bindings for that resource or project. However, existing sessions may still have access for up to 15 minutes due to caching. To immediately revoke access, use a deny policy with the Deny Organization Policy.

**How do I restrict access to only certain IP addresses using IAM?**

Use IAM Conditions. In the IAM policy, add a condition expression like request.ip in ["203.0.113.0/24"] to allow access only from that IP range. This is more precise than editing network rules separately.

**What is a custom role in IAM and when should I use one?**

A custom role lets you collect specific permissions you define, rather than using a predefined role. Use a custom role when no predefined role provides just the permissions you need for least privilege, but avoid over-creating them as they require more management.

**Does IAM work across different Google Cloud regions?**

Yes, IAM policies are global and apply to resources in all regions. To restrict access to specific regions, combine IAM with VPC Service Controls or use IAM Conditions that check the resource location.

## Check your understanding

1. **You need to give a compute instance the ability to read objects from a Cloud Storage bucket. Which IAM role should you assign to the instance’s service account?**

   Answer: The role roles/storage.objectViewer, which includes permissions like storage.objects.get and storage.objects.list for that bucket.

2. **What is the difference between authentication and authorisation in the context of IAM?**

   Answer: Authentication verifies an identity (e.g., logging in with a password), while authorisation determines what actions that identity can perform (e.g., whether they can delete a database).

3. **An engineer wants to store a service account key in a GitHub repository to allow a CI/CD pipeline to deploy to Google Cloud. Is this recommended?**

   Answer: No. Storing keys in source code is insecure. Instead, use Workload Identity Federation for GitHub Actions or Cloud Build’s built-in service account.

4. **If an IAM policy is set at the organisation level granting a user the role ‘roles/storage.objectViewer’, and a project-level policy denies that role, what is the final effective permission?**

   Answer: The project-level deny policy overrides the organisation-level allow policy, so the user will not have object viewer access in that project.

5. **What is the purpose of IAM conditions?**

   Answer: IAM conditions allow you to add extra constraints to a role binding, such as restricting access to a specific IP range, during a certain time window, or only for requests to a specific resource type.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/google-pcd/application-security-and-iam
