💻
Software Development
Technical Knowledges
Technical Knowledges
  • Everything anyone should know
    • Fundamental
      • Life cycle of Dependency Injection
        • When to use?
          • Transient
          • Scoped
          • Singleton
      • OOP
        • Inheritance
          • More with override in C#
            • Why need to use "virtual" keyword when we can use "new" keyword
          • How to achieve multiple inheritance in C#
          • Note
        • Polymophism
        • Encapsulation
        • Abtraction
          • Not use "override" keyword in abstract method
          • Notes
      • Data representing
        • JSON
        • XML
        • Comparation
      • Middleware
      • Status Code
      • API Styles
        • SOAP
        • REST
          • Question
        • GraphQL
        • gRPC
        • WebSocket
        • Webhook
        • Comparation
          • SOAP vs REST
          • REST vs GraphQL
          • gRPC vs REST
          • HTTP vs WebSocket
      • SDK
    • Advanced
      • Memoize
      • N+1 issues
      • Concurrency
        • Thread
          • Race Condition
          • Thread Safety
          • Critical Sections
        • Deadlock
        • Semaphore
    • Comparison
      • Architecture
        • SOA vs Microservices
        • Strong Consistency vs Eventual Consistency
      • Data structures
        • Instance vs Object
        • Field vs Property
        • Properties vs Method
        • Class vs Struct
        • const vs readoly vs static
        • Value types and Reference types
        • i++ vs ++i
        • Prototypal Inheritance vs Class Inheritance
        • Abstraction vs Interface
        • Run-time vs Compile-time
        • Overloading vs Overriding
      • Front-end
        • SSR vs SPA
        • Axios vs Fetch
      • Databases
        • Different between Function() and Store Procedure()
      • Security
        • Encoding vs Encryption vs Tokenization
      • Message Broker
        • RabbitMQ vs Kafka
      • Devops
        • Kubernetes vs Docker Swarm
        • Docker Repository vs Docker Registry
      • Cloud
      • Computer Science
        • Recursion and Iteration
      • Technology
        • .NET Core vs .NET Framework
        • Cache vs Local Storage vs Session Storage vs Cookies
      • SDLC
        • TDD vs BDD
  • Design Pattern
    • Overview
    • Creational Design Patterns
      • Abstract Factory
        • Code Example
          • C#
          • Java
          • Python
      • Builder
        • Code Example
          • C#
          • Java
          • Python
      • Factory Method
        • Code Example
          • C#
          • Java
          • Python
      • Prototype
        • Code example
          • C#
          • Java
          • Python
      • Singleton
        • Code example
          • C#
            • Naïve Singleton
            • Thread-safe Singleton
          • Java
            • Naïve Singleton (single-threaded)
            • Naïve Singleton (multithreaded)
            • Thread-safe Singleton with lazy loading
          • Python
            • Naïve Singleton
            • Thread-safe Singleton
    • Structural Design Patterns
      • Adapter
        • Code example
          • C#
          • Java
          • Python
            • Conceptual Example (via inheritance)
            • Conceptual Example (via object composition)
      • Bridge
        • Code example
          • C#
          • Java
          • Python
      • Composite
        • Code example
          • C#
          • Java
          • Python
      • Decorator
        • Code example
          • C#
          • Java
          • Python
      • Facade
        • Code example
          • C#
          • Java
          • Python
      • Flyweight
        • Code example
          • C#
          • Java
          • Python
      • Proxy
        • Code example
          • C#
          • Java
          • Python
    • Behavior Design Patterns
      • Chain of Responsibility
        • Code example
          • C#
          • Java
          • Python
      • Command
        • C#
        • Java
        • Python
      • Interpreter
        • Code example
          • C#
      • Iterator
        • Code example
          • C#
          • Java
          • Python
      • Mediator
        • Code example
          • C#
          • Java
          • Python
      • Memento
        • Code example
          • C#
          • Java
          • Python
      • Observer
        • Code example
          • C#
          • Java
          • Python
      • State
        • Code example
          • C#
          • Java
          • Python
      • Strategy
        • Code example
          • C#
          • Java
          • Python
        • Different with using abstract class
      • Template Method
        • Code example
          • C#
          • Java
          • Python
      • Visitor
        • Code example
          • C#
          • Java
          • Python
    • Use cases
      • Real-life example
    • More
      • Circuit Breaker Pattern
      • Repository Pattern
      • Unit Of Work Pattern
    • Some design patterns contradictory
  • Architect
    • Clean Architecture
    • Layered (n-tier) Architecture
    • Microservices Architecture
    • Monolithic Architecture
    • Service-Oriented Architecture (SOA)
    • Domain-Driven Design (DDD)
    • Blackboard Architecture
    • Object-Oriented Architecture
  • Microservices Design Pattern
    • Saga Pattern
      • Example
    • Strangler Fig Pattern
    • API Gateway Pattern
    • Backends For Frontends (BFF) Pattern
    • Service Discovery Pattern
    • Circuit Breaker Pattern
    • Bulk Head Pattern
    • Retry Pattern
    • Sidecar Pattern
    • Event Driven Architecture Pattern
    • CQRS (Command and Query Responsibility Segregation)
      • Event Sourcing
      • Code example
        • Basic
        • CQRS + MediatR + EDA + RabbitMQ
      • The Good, the Bad, and the Ugly
    • Configuration Externalization Pattern
  • Design and development principles
    • SOLID aka Design Principles
    • Cohesion Principles
    • Coupling principle
    • Some fundamental principles
      • Separation of Concerns
      • Persistence Ignorance
      • DRY
      • KISS
  • Authentication and Authorization Standards
    • SAML
    • OAuth
    • OIDC
    • SCIM
    • SSO
    • Tools
      • Keycloak
    • More
      • JWT
      • Access Token & Refresh Token
  • .NET TECHNOLOGY
    • .NET MVC
      • HTML Helpers
        • Extension method for HTML Helpers
      • Filters
        • Order of Filters
    • Fundamental
      • Startup file
      • Query Data
        • Linq
          • Filtering
          • Sorting
          • Projecting
          • Quantifying
          • Flattening
          • Grouping
          • Joining
          • Aggregating
          • Deferred execution vs Immediate execution
        • OData
          • Filter Expression
      • ORM
        • Entity Framework
          • Eager Loading vs Lazy Loading vs Explicit Loading
          • How to improve our entity framework core query performance
        • Dapper
        • Why Dapper faster than Entity Framework
      • Identity Server
      • Fluent Validation
      • Minimal API
      • Generic
      • IoC
        • Castle Windsor
        • Autofac
        • Ninject
      • CLR
      • Refit
      • Task Schedule
        • Hangfire
        • Quartz
      • Some notice
    • Advanced
      • Multi Thread
        • Thread pool
        • Parallel
        • Comparation
        • Code comparation
      • Caching
        • IMemoryCache
      • MediatR
      • SignalR
      • API Gateway
        • Ocelot
      • gRPC
      • Multitenancy
      • Special C# technique
        • Generic
        • Extension Method
        • Delegate
        • Lambda Expression
        • Yield
      • Jetbrain tools
        • dotTrace
        • dotMemory
        • dotPeek
      • ABP Framework
        • Multi Layered
          • Domain Layer
            • Entities
            • Repository
            • Domain Services
          • Application Layer
            • Application Services
            • Data Transfer Objects
          • Data Access
            • Entity Framework Core Integration
            • MongoDB Integration
        • Microservice Architecture
        • DDD
          • Domain Layer
            • Entities & Aggregate Roots
            • Value Objects
            • Repositories
            • Domain Services
            • Specifications
          • Application Layer
            • Application Services
            • Data Transfer Objects
            • Unit of Work
    • Tutorial Coding
      • Custom and Using Middleware in .NET CORE
      • Connect Elastic Search and MongoDB
      • Implementing the Unit of Work Pattern in Clean Architecture with .NET Core
    • ServiceStack
    • POCO
  • System Design
    • Blueprint
    • Fundamental
      • Scale from zero to millions of users
        • Single server setup
        • Database
        • Load balancer
        • Database replication
        • Cache
        • Content delivery network (CDN)
        • Stateless web tier
        • Data centers
        • Message queue
        • Logging, metrics, automation
        • Database scaling
        • Millions of users and beyond
      • A framework for system design interviews
        • Step 1 - Understand the problem and establish design scope
        • Step 2 - Propose high-level design and get buy-in
        • Step 3 - Design deep dive
        • Step 4 - Wrap up
        • Summarize
      • Back-of-the-envelope estimation
      • Design a rate limiter
        • Step 1 - Understand the problem and establish design scope
        • Step 2 - Propose high-level design and get buy-in
          • Algorithms for rate limiting
            • Token bucket algorithm
            • Leaking bucket algorithm
            • Fixed window counter algorithm
            • Sliding window log algorithm
            • Sliding window counter algorithm
          • High-level architecture
        • Step 3 - Design deep dive
          • Rate limiting rules
          • Exceeding the rate limit
          • Detailed design
          • Rate limiter in a distributed environment
          • Performance optimization
          • Monitoring
        • Step 4 - Wrap up
      • Design consistent hashing
        • Consitent hashing
        • Two issues in the basic approach
        • Wrap up
      • Design key-value store
        • Understand the problem and establish the design scope
        • CAP theorem
        • System components
          • Data partition
          • Data replication
          • Consistency
          • Inconsistency resolution
          • Handling failures
          • System architecture diagram
          • Write path
          • Read path
      • Design a unique id generator in distributed systems
        • Step 1 - Understand the problem and establish design scope
        • Step 2 - Propose high-level design and get buy-in
          • Multi-master replication
          • UUID
          • Ticket Server
          • Twitter snowflake approach
        • Step 3 - Design deep dive
        • Step 4 - Wrap up
      • Design a url shortener
        • Step 1 - Understand the problem and establish design scope
        • Step 2 - Propose high-level design and get buy-in
        • Step 3 - Design deep dive
          • Data model
          • Hash function
          • URL shortening deep dive
          • URL redirecting deep dive
        • Step 4 - Wrap up
      • Design a web crawler
        • Step 1 - Understand the problem and establish design scope
        • Step 2 - Propose high-level design and get buy-in
        • Step 3 - Design deep dive
          • DFS vs BFS
          • URL frontier
          • HTML Downloader
          • Robustness
          • Extensibility
          • Detect and avoid problematic content
        • Step 4 - Wrap up
    • Use cases
      • Design Youtube
      • Design Social Media App
      • Design Typehead Suggestion
      • Design Taxi Booking System
      • Design Messaging App
  • DBMS
    • Fundamental
      • ACID
      • Order Of Execution of the SQL query
      • Transaction – Concurrency Control Techniques
        • Isolation level
      • Index
        • Clustered Index vs Non-clustered index
        • Index vs Unique index
      • Built-in functions
        • String Functions
          • ASCII
          • CHAR
          • CHARINDEX
          • CONCAT
          • CONCAT_WS
          • DATALENGTH
          • DIFFERENCE
          • FORMAT
          • LEFT
          • LEN
          • LOWER
          • LTRIM
          • NCHAR
          • PATINDEX
          • QUOTENAME
          • REPLACE
          • REPLICATE
          • REVERSE
          • RIGHT
          • RTRIM
          • SOUNDEX
          • SPACE
          • STR
          • STUFF
          • SUBSTRING
          • TRANSLATE
          • TRIM
          • UNICODE
          • UPPER
        • Numeric Functions
          • ABS
          • ACOS
          • ASIN
          • ATAN
          • ATN2
          • AVG
          • CEILING
          • COUNT
          • COS
          • DEGREES
          • EXP
          • FLOOR
          • LOG
          • LOG10
          • MAX
          • MIN
          • PI
          • POWER
          • RADIANS
          • ROUND
          • SIGN
          • SIN
          • SQRT
          • SQUARE
          • SUM
          • TAN
        • Date Functions
          • CURRENT_TIMESTAMP
          • DATEADD
          • DATEDIFF
          • DATEFROMPARTS
          • DATENAME
          • DATEPART
          • DAY
          • GETDATE
          • GETUTCDATE
          • ISDATE
          • MONTH
          • SYSDATETIME
          • YEAR
        • Advance Functions
          • CASE
          • CAST
          • COALESCE
          • CONVERT
          • CURRENT_USER
          • LEAD
          • LAG
          • IIF
          • ISNULL
          • ISNUMERIC
          • NULLIF
          • SESSION_USER
          • SESSIONPROPERTY
          • SYSTEM_USER
          • USER_NAME
      • SQL Best Practice
      • Execution Plan
      • Optimize query execution
    • Advanced
      • CTE
      • Window function
      • Performance Tuning
        • Query tuning
        • Interview ques
      • DB Sharding
      • Concurrency Control
        • Optimistic lock
        • Pessimistic lock
      • Compare DELETE VS TRUNCATE
    • Comparation
      • Oracle vs SQL Server vs Postgre vs Mysql
  • Javascript
    • ES6 Techniques
      • Hoisting
      • Destructing
      • Spread Operator
      • Rest Operator
    • Basic
      • Const vs Let vs Var
      • Debounce & Throttle
      • Callback()
    • 5 ways to define a function
  • Clean code
    • Page 2
  • Search Engine
    • Elastic Search
      • Interview question
      • Code Example
    • Solr
    • IBM Watson Discovery
    • Google Cloud Search
    • Coveo Relevance Cloud
  • Cloud Service
    • Overview
    • Azure
      • Certificate
        • AZ-900
          • Describe cloud concepts
            • What is Cloud Computing?
            • Benefits of using cloud services
              • High Availability and Scalability
              • High Elasticity
              • High Reliability and Predictability
              • High Security and Governance
              • High manageability
            • IaaS vs PaaS vs SaaS
            • Cloud Deployment Models
            • CAPEX vs OPEX
          • Describe Azure architecture and services
            • Describe the core architectural components of Azure
              • Learn sandbox
              • Azure physical infrastructure
              • Azure management infrastructure
              • Create an Azure resource
            • Describe Azure compute and networking services
              • Azure Virtual Machines
              • Create an Azure Virtual Machine
              • Azure Virtual Desktop
              • Azure Containers
              • Azure Function
              • Describe application hosting options
              • Configure network access
              • Describe Azure Virtual Networking
              • Azure Virtual Private Networks
              • Azure ExpressRoute
              • Azure DNS
            • Describe Azure storage services
              • Azure storage accounts
              • Azure storage redundancy
              • Azure storage services
              • Create a storage blob
              • Identify Azure data migration options
              • Identify Azure file movement options
            • Describe Azure identity, access, and security
              • Azure directory services
              • Azure authentication methods
              • Azure external identities
              • Azure conditional access
              • Azure role-based access control
              • Zero trust model
              • Defense-in-depth
              • Microsoft Defender for Cloud
          • Describe Azure management and governance
            • Describe cost management in Azure
              • Factors that can affect costs in Azure
              • Compare the Pricing and Total Cost of Ownership calculators
              • Estimate workload costs by using the Pricing calculator
              • Compare workload costs using the TCO calculator
              • Azure Cost Management tool
            • Describe features and tools in Azure for governance and compliance
              • Azure Blueprints
              • Azure Policy
              • Purpose of resource locks
              • Configure a resource lock
              • Service Trust portal
            • Describe features and tools for managing and deploying Azure resources
              • Tools for interacting with Azure
              • Azure Arc
              • Azure Resource Manager and Azure ARM templates
            • Describe monitoring tools in Azure
              • Azure Advisor
              • Azure Service Health
              • Azure Monitor
        • SC-900
          • Describe the concepts of security, compliance, and identity
            • Describe security and compliance concepts
              • Shared responsibility model
              • Defense in depth
              • Zero Trust model
              • Encryption and hashing
              • Compliance concepts
            • Describe identity concepts
              • Authentication and authorization
              • Identity as the primary security perimeter
              • Role of the identity provider
              • Directory services and Active Directory
              • Federation
          • Describe the capabilities of Microsoft Azure Active Directory, part of Microsoft Entra
            • Describe the services and identity types of Azure AD
              • Azure Active Directory
              • Available Azure AD editions
              • Azure AD identity types
              • Types of external identities
              • Concept of hybrid identity
            • Describe the authentication capabilities of Azure AD
              • Authentication methods available in Azure AD
              • Multi-factor authentication (MFA) in Azure AD
              • Self-service password reset (SSPR) in Azure AD
              • Password protection and management capabilities of Azure AD
            • Describe the access management capabilities of Azure AD
              • Conditional Access in Azure AD
              • Benefits of Azure AD roles and role-based access control
            • Describe the identity protection and governance capabilities of Azure AD
              • Identity governance in Azure AD
              • Entitlement management and access reviews
              • Privileged identity Management
              • Azure Identity Protection
          • Describe the capabilities of Microsoft security solutions
            • Describe basic security capabilities in Azure
              • Azure DDoS protection
              • Azure Firewall
              • Web Application Firewall
              • Network segmentation in Azure
              • Azure Network Security groups
              • Azure Bastion and JIT Access
              • Describe ways Azure encrypts data
            • Describe security management capabilities of Azure
              • Cloud security posture management
              • Microsoft Defender for Cloud
              • Enhanced security of Microsoft Defender for Cloud
              • Microsoft cloud security benchmark and security baselines for Azure
            • Describe security capabilities of Microsoft Sentinel
              • SIEM and SOAR
              • How Microsoft Sentinel provides integrated threat management
              • Understand Sentinel costs
            • Describe threat protection with Microsoft 365 Defender
              • Microsoft 365 Defender services
              • Microsoft Defender for Office 365
              • Microsoft Defender for Endpoint
              • Microsoft Defender for Cloud Apps
              • Microsoft Defender for Identity
              • Microsoft 365 Defender portal
          • Describe the capabilities of Microsoft compliance solutions
            • Describe the Service Trust Portal and privacy at Microsoft
              • Service Trust Portal
              • Microsoft's privacy principles
              • Microsoft Priva
            • Describe the compliance management capabilities in Microsoft Purview
              • Microsoft Purview compliance portal
              • Compliance Manager
              • Describe use and benefits of compliance score
            • Describe information protection and data lifecycle management in Microsoft Purview
              • Know your data, protect your data, and govern your data
              • Data classification capabilities of the compliance portal
              • Sensitivity labels and policies
              • Data loss prevention
              • Retention policies and Retention labels
              • Records management
            • Describe insider risk capabilities in Microsoft Purview
              • Risk management
              • Communication compliance
              • Information barriers
            • Describe the eDiscovery and audit capabilities of Microsoft Purview
              • eDiscovery solutions in Microsoft Purview
              • Audit solutions in Microsoft Purview
            • Describe resource governance capabilities in Azure
              • Azure Policy
              • Azure Blueprints
              • Capabilities in the Microsoft Purview governance portal
        • DP-900
          • Core Concept
            • Explore core data concepts
              • Data formats
              • File storage
              • Databases
              • Transactional data processing
              • Analytical data processing
            • Explore data roles and services
              • Job roles in the world of data
              • Identify data services
          • Relational Data in Azure
            • Explore fundamental relational data concepts
              • Relational data
              • Normalization
              • SQL
              • Database objects
            • Explore relational database services in Azure
              • Azure SQL services and capabilities
              • Azure services for open-source databases
              • Exercise: Explore Azure relational database services
          • Non-relational data in Azure
            • Explore Azure Storage for non-relational data
              • Azure blob storage
              • Azure DataLake Storage Gen2
              • Azure Files
              • Azure Tables
              • Exercise: Explore Azure Storage
            • Explore fundamentals of Azure Cosmos DB
              • Azure Cosmos DB
              • Identify Azure Cosmos DB APIs
              • Exercise: Explore Azure Cosmos DB
          • Data analytics in Azure
            • Explore fundamentals of large-scale data warehousing
              • Data warehousing architecture
              • Data ingestion pipelines
              • Analytical data stores
              • Exercise: Explore data analytics in Azure with Azure Synapse Analytics
            • Explore fundamentals of real-time analytics
              • Understand batch and stream processing
              • Explore common elements of stream processing architecture
              • Azure Stream Analytics
              • Exercise: Explore Azure Stream Analytics Completed
              • Apache Spark on Microsoft Azure
              • Exercise: Explore Spark Streaming in Azure Synapse Analytics Completed
            • Explore fundamentals of data visualization
              • Power BI tools and workflow
              • Core concepts of data modeling
              • Considerations for data visualization
              • Exercise – Explore fundamentals of data visualization with Power BI Completed
        • AI-900
      • Azure Subscription
      • Azure App Service
      • Azure Dictionary B2C
      • Azure Front Door
      • Azure Traffic Manager
      • Azure Load Balancer
      • Azure KeyVault
      • API Management
      • Azure Logic Apps
      • Azure Metric and Logs
      • Azure Workbooks
      • Azure Messaging Services
      • Azure Service Fabric
      • Comparison
        • Durable Function vs Logic App
        • Storage queues vs Service Bus queues
        • Event Grid vs Service Bus
    • AWS
      • Certificate
        • CLF-C02
          • Cloud Concepts
            • Cloud Computing
            • The Deployment Models of the Cloud
            • The Five Characteristics of Cloud Computing
            • Six Advantages of Cloud Computing
            • Problems solved by the Cloud
            • Types of Cloud Computing
            • Pricing of the Cloud
            • AWS Global Infrastructure
              • AWS Regions
              • AWS Availability Zones
              • AWS Points of Presence (Edge Locations)
            • Tour of the AWS Console
            • Shared Responsibility Model diagram
          • Security & Compliance
            • AWS Shared Responsibility Model
            • DDOS
            • Network Firewall
            • Penetration Testing on AWS Cloud
            • Encryption
            • AWS Certificate Manager (ACM)
            • AWS Secrets Manager
            • AWS Artifact (not really a service)
            • Amazon GuardDuty
            • Amazon Inspector
            • AWS Config
            • AWS Macie
            • AWS Security Hub
            • Amazon Detective
            • AWS Abuse
            • Root user privileges
            • IAM Access Analyzer
            • Summary
            • Advanced Identity
              • STS
              • Cognito
              • Directory Services
              • IAM Identity Center
              • Summary
          • Cloud Technology & Services
            • IAM
              • IAM: Users & Groups
              • IAM: Permissions
              • IAM Policies inheritance
              • IAM Policies Structure
              • IAM – Password Policy
              • Multi-Factor Authentication - MFA
              • How can users access AWS?
                • AWS CLI
                • AWS SDK
              • IAM Roles for Services
              • IAM Security Tools
              • IAM Guidelines & Best Practices
              • Shared Responsibility Model for IAM
              • Summary
            • EC2
              • Overview
              • EC2 Instance Types
                • Overview
                • General Purpose
                • Compute Optimized
                • Memory Optimized
                • Storage Optimized
                • Example
              • Security Groups
              • SSH in EC2
              • EC2 Instance Purchasing Options
                • On-Demand Instances
                • Reserved Instances
                • Savings Plans
                • Spot Instances
                • Dedicated Hosts
                • Dedicated Instances
                • Capacity Reservations
                • Summary
              • EC2 Instance Storage
                • EBS
                • EBS Snapshot
                • AMI
                • EC2 Image Builder
                • EC2 Instance Store
                • EFS
                • Shared Responsibility Model for EC2 Storage
                • Amazon FSx
                • Summary
            • ELB & ASG
              • High Availability, Scalability, Elasticity
              • ELB
              • ASG
              • Summary
            • Amazon S3
              • Overview
              • Security
              • Techniques
              • Shared Responsibility Model for S3
              • AWS Snow Family
              • Summary
            • Database & Analytics
              • Overview
              • RDS & Aurora
              • Amazon ElastiCache
              • DynamoDB
              • Redshift
              • EMR
              • Amazon Athena
              • Amazon QuickSight
              • DocumentDB
              • Amazon Neptune
              • Amazon QLDB
              • Amazon Managed Blockchain
              • AWS Glue
              • DMS – Database Migration Service
              • Summary
            • Other Compute Service
              • Docker
              • ECS
              • Fargate
              • ECR
              • AWS Lamda
              • Amazon API Gateway
              • AWS Batch
              • Amazon Lightsail
              • Summary
                • Other Compute - Summary
                • Lambda Summary
            • Deploying and Managing Infrastructure
              • CloudFormation
              • CDK
              • Elastic Beanstalk
              • AWS CodeDeploy
              • AWS CodeCommit
              • AWS CodePipeline
              • AWS CodeArtifact
              • AWS CodeStar
              • AWS Cloud9
              • SSM
              • AWS OpsWorks
              • Summary
            • Global Infrastructure
              • Overview
              • Route 53
              • CloudFront
              • AWS Global Accelerator
              • AWS Outposts
              • AWS WaveLength
              • AWS Local Zones
              • Global Applications Architecture
              • Summary
            • Cloud Integration
              • Overview
              • SQS
              • Kinesis
              • SNS
              • MQ
              • Summary
            • Cloud Monitoring
              • CloudWatch
              • EventBridge
              • CloudTrail
              • X-Ray
              • CodeGuru
              • Health Dashboard
              • Summary
            • VPC
              • Overview
              • IP Addresses in AWS
              • VPC Diagram
              • Core networking
              • VPC Flow Logs
              • VPC Peering
              • VPC Endpoints
              • AWS PrivateLink (VPC Endpoint Services)
              • Site to Site VPN & Direct Connect
              • AWS Client VPN
              • Transit Gateway
              • Summary
            • Machine Learning
              • Rekognition
              • Transcribe
              • Polly
              • Translate
              • Lex & Connect
              • Comprehend
              • SageMaker
              • Forecast
              • Kendra
              • Personalize
              • Textract
              • Summary
            • Other Services
              • WorkSpaces
              • AppStream 2.0
              • IoT Core
              • Elastic Transcoder
              • AppSync
              • Amplify
              • Device Farm
              • Backup
              • Disaster Recovery Strategies
              • AWS Elastic Disaster Recovery (DRS)
              • DataSync
              • Application Discovery Service
              • Application Migration Service (MGN)
              • Migration Evaluator
              • Migration Hub
              • FIS
              • Step Functions
              • Ground Station
              • Pinpoint
          • Account Management, Billing & Support
            • Organizations
            • SCP
            • Control Tower
            • RAM
            • Service Catalog
            • Savings Plan
            • AWS Compute Optimizer
            • Billing and Costing Tools
            • Pricing Calculator
            • Tracking costs in cloud
              • Cost Explorer
            • Monitoring costs in the could
            • AWS Cost Anomaly Detection
            • AWS Service Quotas
            • Trusted Advisor
            • Support Plans
            • Summary
              • Account Best Practices
              • Billing and CostingTools
          • AWS Architecting & Ecosystem
            • General Guiding Principles
            • Well Architected Framework
              • Operational Excellence
              • Security
              • Reliability
              • Performance Efficiency
              • Cost Optimization
              • Sustainability
            • AWS CAF
            • AWS Right Sizing
            • AWS Ecosystem
      • Comparison
        • Region, Availability Zone and Edge Location in AWS
        • EBS vs EFS
    • GCP
    • OCI
    • Object Storage Server
      • MinIO
    • Comparison
      • Azure Active Directory B2C vs AWS Cognito
  • Front End
    • Basic
      • HTML
        • <ul> vs <ol>
        • <table>
      • CSS
        • Padding
        • Box Model
        • Outline
        • Text
        • Display
        • Position
        • z-index
        • Overflow
        • Float
        • Inline vs Inline-block
        • CSS Combinators
        • CSS [attribute] Selector
        • Website Layout
        • Unit
        • CSS The !important Rule
        • Flexbox
        • Comparation
          • div.classname vs div .classname
          • .classname vs .clasname #id vs .classname#id
      • JQuery
        • Syntax
        • Document
      • AJAX
    • Modern Framework
      • React
        • HOC
        • State Management
          • Redux
            • Selector
            • Middleware
              • Saga
              • Thunk
          • MobX
        • Hooks
        • Life Cycle
          • React Lifecycle Methods
          • React Lifecycle Hooks
          • Comparation
        • Signals
      • Angular
        • Directives
          • Component Directives
          • Attribute Directives
            • Built-in
            • Building an Attribute Directive
          • Structural Directives
            • Built-in
            • Custom
        • Binding
        • Components
        • Routing
      • Vue
    • Compile & Module
      • Webpack
      • Babel
    • TypeScript
      • Cheat sheet
    • Blazor
      • WebAssembly
    • UI Library
      • Formik
      • Material UI
      • Tailwind CSS
    • Security
      • Top 7 Common Frontend Security Attacks
    • Some notices
  • Microservices
    • Service Mesh
    • Service Registry
    • Service Discovery
    • Composition
    • Orchestration
    • Transformation
    • Dapr
  • Network
    • Protocols
      • Overview
      • HTTP
      • MQTT
      • AMQP
      • FTP
      • TCP
      • UDP
      • ICMP
    • OSI Model
  • Cache
    • Redis
      • What data should and should not be cached
      • Use cache in
      • Demo in .NET
    • Hazelcast
    • Memcached
  • Message Broker
    • RabbitMQ
      • Demo in .NET
      • Interview Ques
      • Use case
    • Kafka
      • Top 5 Kafka Use Case
    • ActiveMQ
    • Masstransit
  • Bash Script
    • Linux file system
    • Cheat sheet
    • 18 Most-used Linux Commands
    • Interview Question
  • Devops
    • Overview
      • What is ?
      • IaC
      • SAFe
      • Progressive Delivery
        • Blue Green Deployments
        • Canary Deployments
        • A/B Test
      • Platform Engineering
    • Azure Pipeline
    • Docker
      • What is ?
      • Docker Engine
        • Image
        • Docker file
          • Some commands
        • Container
        • Network
        • Volume
          • Additional infomation
      • Docker CLI
      • Docker Compose
        • Additional
      • Docker Security
        • Best Practice
        • Additional Information
      • Docker Swarm
      • Storing
        • Docker Registry
        • Docker Hub
      • Summarize
    • Kubernetes
      • What is ?
        • Additional
      • Kubernetes Pod
      • Replication Controllers
      • ReplicaSets and DaemonSets
        • Additional
      • Kubernetes Services
      • Deployment
        • Additional
      • Volume
      • PersistentVolumes
        • Additional
      • Configuration
        • Additional
      • StatefulSets
        • Additional
      • Downward API
      • Kubernetes internals architecture
      • Pod internal
      • ServiceAccount and Role Based Access Control
      • Network
        • Additional
      • Managing and calculating resources used for Pods
      • Automatic scaling Pods and clusters
      • Advanced scheduling
        • Taints and tolerations
        • Node affinity and Pod affinity
        • Additional
      • Adding custom resource to Kubernetes
    • Openshift
    • IaC
      • Terraform
        • Definition
        • Why chose Terraform?
        • IAC with Terraform
          • Terraform Workflow
            • Terraform Init
            • Terraform Plan
            • Terraform Apply
            • Terraform Destroy
          • Terraform Syntax
        • Terraform Architecture
          • Variable in terraform
          • Variable Type Contraint
          • Terraform Output
          • Terraform Provisioners
        • Terraform State
          • The concept
          • Local and Remote State Storage
          • Persisting Terraform State in AWS S3
          • Hand on
        • Terraform Modules
          • Accessing and Using Terraform Modules
          • Interating with Terraform Module Inputs and Outputs
          • Hand on
        • Built-in Functions and Dynamic Blocks
          • Built-in Function
          • Terraform Type Constraints (Collection & Structural)
          • Terraform Dynamic Block
          • Hand on
        • Terraform CLI
          • Terraform CLI: fmt, taint & import
          • Hand on
            • Practicing Terraform CLI commands(fmt, taint, import)
            • Using Terraform CLI Commands (workspace and state) to Manipulate a Terraform deployment
      • Ansible
    • Jenkin
    • GitOps
      • What is ?
      • Argo CD
    • Monitoring
      • Prometheus and Grafana
      • New Relic
  • Web Server
    • Apache
    • Nginx
    • IIS
  • Security
    • How to prevent crawl data
    • SQL Injection
    • OWASP
      • Web Application Security Risks
        • Broken Access Control
        • Cryptographic Failures
        • Injection
        • Insecure Design
        • Security Misconfiguration
        • Vulnerable and Outdated Components
        • Identification and Authentication Failures
        • Software and Data Integrity Failures
        • Security Logging and Monitoring Failures
        • Server-Side Request Forgery
      • API Security Risks
        • Broken Object Level Authorization
        • Broken Authentication
        • Broken Object Property Level Authorization
        • Unrestricted Resource Consumption
        • Broken Function Level Authorization
        • Unrestricted Access to Sensitive Business Flows
        • Server Side Request Forgery
        • Security Misconfiguration
        • Improper Inventory Management
        • Unsafe Consumption of APIs
    • Security headers
      • HTTP Strict Transport Security (HSTS)
      • Content Security Policy (CSP)
      • Cross Site Scripting Protection (X-XSS-Protection)
      • X-Frame-Options
      • X-Content-Type-Options
      • X-Permitted-Cross-Domain-Policies
      • Public Key Pinning (PKP)
        • What is HTTP Public Key Pinning and Why It’s Not Good to Practice
      • Expect-CT
        • The end of Expect-CT
      • Referer-Policy
      • Pragma
      • Cache-Control
        • Difference between Pragma and Cache-Control headers
      • Same-origin policy
      • Cross-origin resource sharing (CORS)
  • Data Change Capture (CDC)
    • Debezium
  • Software Development Life Cycle (SDLF)
    • Waterfall
    • V Model
    • Agile
      • Methods
        • Xtreme Programming
          • TDD
          • BDD
        • Scrum
        • Kanban
      • Question
  • Secure Software Development Framework (SSDF)
    • Page 1
  • Source Control
    • Git
    • SVN
    • TFS
  • Integration Systems
    • Stripe
    • Salesforce
    • TaxJar
    • Zendesk
  • Enterprise Service Bus (ESB)
    • Mulesoft
  • Data
    • 5 type of analytics
  • SOFTWARE QUALITY STANDARDS – ISO 5055
    • Standard
    • All about ISO 5055
  • Interview Question
    • Overview
      • Roadmap To Clearing Technical Interview
    • Technical
      • DSA
      • System Design
      • C#
      • React
    • Behavior
    • Question back to the interviewer
  • Roadmap
    • .NET
    • Java
  • English
    • Phát âm ed
    • Many vs much
    • Most vs most of vs almost vs the most
    • Quy tắc thêm s,es vào danh từ và cách phát âm s,es chuẩn xác nhất
  • Those will be seen later
    • Note
    • Interview
  • Programming Language
    • Python
      • Data structure
        • Set
    • Javascript
      • Data Structure
        • Map
    • C#
      • Data Structure
        • Value type & Reference type
        • Using statement
        • HashSet
        • Dictionary
        • Priority Queue
      • Fact
        • Understand about IEnumerable vs. IQueryable vs. ICollection vs. IList
        • 5 things you should know about enums in C#
    • Java
Powered by GitBook
On this page
  • Understand how kubernetes API server performs authentication
  • ServiceAccounts
  • Role Based Access Control
  • Default ClusterRole and ClusterRoleBinding
  • Conclude
  1. Devops
  2. Kubernetes

ServiceAccount and Role Based Access Control

Understand how kubernetes API server performs authentication

As we said in lesson 10, the API server can be configured with one or more authentication plugins. When a request goes to the API server, it will go through all of these authentication plugins. These plugins will separate necessary information such as username, user id, and group to which the client making the request belongs.

Client

There are 2 types of clients clearly distinguished by the API server:

  • Humans (users)

  • Pod (application runs inside a container)

For users, usually use kubectl or make an HTTP request with a token to authenticate to the API server. As for Pod, ServiceAccount will be used to authenticate to the API server. In this article we will talk about Pod authentication to the API server.

Groups

Both users and ServiceAccounts belong to one or more groups. The group is used to grant permissions to all users and ServiceAccounts in it at the same time, instead of having to grant permissions to each individual.

This group is separated by authentication plugin along with username and user id information, there are 4 default groups:

  • system:unauthenticated - assigned to a user that was not authenticated successfully.

  • system:authenticated - assigned to a successfully authenticated user.

  • system:serviceaccounts - group for all ServiceAccounts.

  • system:serviceaccounts: <namespace>- group for all ServiceAccounts in a namespace.

ServiceAccounts

As we said, ServiceAccount will be automatically mounted inside the Pod container in folder /var/run/secrets/kubernetes.io/serviceaccount. Consists of 3 files: ca.crt, namespace, token.

This token file is the file that will contain information about the Pod client. When we use it to make requests to the server, the API server will separate the information from this token. And our ServiceAccount username will have the following form system:serviceaccount:<namespace>:<service account name>, with system:serviceaccount:<namespace>the group and <service account name>the name of the ServiceAccount used.

After obtaining the above information, the server will transmit this ServiceAccount username to the authorization plugins, to see if this ServiceAccount has the right to perform the current action on the API server or not.

ServiceAccount is essentially just a resource that the application inside the container can use to authenticate to the API server. We can list ServiceAccount with the command:

$ kubectl get sa
NAME     SECRETS  AGE
default  1        10d

And this ServiceAccount is a namespace resource, meaning it only has scope within a namespace, we cannot use this namespace's ServiceAccount for another namespace. And each namespace will have a ServiceAccount named default that is automatically created when a namespace is created. A ServiceAccount can be used by multiple Pods within the same namespace.

Use ServiceAccount to pull images from private container registry

In this series, we have only used public container images, not private container images. When working on a real project, we will need to use a private container image, not a public container image, because we never want the container of our product to be public on the internet so everyone can download it to run it. So to download images from the private registry, in the Pod's config, we must declare the imagePullSecrets field , as follows:

apiVersion: apps/v1
kind: Deployment
...
    spec:
      imagePullSecrets:
        - name: <secret-name> # secret use to pull image form private registry
      containers:
        - name: background-consume-queue
          image: registry.kala.ai/web-crm/background-consume-queue
...

The imagePullSecrets name field will contain the Secret name that we use to pull the image from the private registry. This secret name is created using the following command:

$ kubectl create secret docker-registry <secret-name> --docker-server=<your-registry-server> --docker-username=<your-name> --docker-password=<your-pword>

With <secret-name>is the name of the secret, docker-server is the server registry, if you use it, hub.docker.comthe server registry is docker.io, docker-username is the username you use to log into docker hub, docker-password is the password of the username corresponding to the docker hub name. For example, if we want to pull an image from the private registry registry.kala.ai, we create a secret as follows:

$ kubectl create secret docker-registry my-secret --docker-server=registry.kala.ai --docker-username=username --docker-password=12345678
apiVersion: apps/v1
kind: Deployment
...
    spec:
      imagePullSecrets:
        - name: my-secret
      containers:
        - name: background-consume-queue
          image: registry.kala.ai/web-crm/background-consume-queue
...

So if we want to pull images from private registry, every time we write config we have to add the imagePullSecrets field. We can use ServiceAccount to simplify this step. When a Pod is created, a ServiceAccount named default is automatically assigned to each Pod.

$ kubectl get pod <pod-name> -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2021-10-14T07:42:11Z"
  ...
spec:
  ...
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default # here
  serviceAccountName: default # here
  ...

We will see that the serviceAccount field will be automatically assigned to the Pod with the value ServiceAccount default. Let's try to see the configuration of a ServiceAccount.

$ kubectl describe sa default
Name:                default
Namespace:           default
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   default-token-tnbgw
Tokens:              default-token-tnbgw
Events:              <none>

You will notice that the config of a ServiceAccount shown above has a field named Image pull secrets , this is the field that has the same effect as imagePullSecrets inside the Pod's config, so what we need to do now is update Update the imagePullSecrets field of the default ServiceAccount, and this ServiceAccount will automatically be assigned to the Pod, and we do not need to declare the imagePullSecrets field in each Pod's config, we update the imagePullSecrets field of the ServiceAccount as follows:

$ kubectl patch sa default --type json -p '[{"op":"replace","path":"/imagePullSecrets[0].name", "value": "my-secret"}]'

So all Pods in our default namespace can pull images from the private registry without us needing to declare imagePullSecrets when writing config for the Pod.

Create ServiceAccount

ServiceAccount is a resouce of kubernetes, so we can create and delete it like other resouce normally, even if you delete the default ServiceAccount, when creating a Pod it will give an error saying it cannot find a ServiceAccount to assign to the Pod. , then when we delete the default ServiceAccount, kubernetes will automatically recreate a new ServiceAccount for us, and the Pod will be created normally again.

Or you can also create another ServiceAccount and assign the Pod to use this new ServiceAccount instead of using the default ServiceAccount. To create a ServiceAccount is very simple, we just need to type the command:

$ kubectl create sa bar
serviceaccount/bar created
$ kubectl describe sa bar
Name:                bar
Namespace:           default
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   bar-token-ndvtr
Tokens:              bar-token-ndvtr
Events:              <none>

Above, when we describe an SA, we see that it has a field named Mountable secrets , this is the name of the Secret assigned to the SA. When an SA is created, it will also create a Secret for us.

$ kubectl get secret
NAME                 TYPE                                 DATA
bar-token-ndvtr      kubernetes.io/service-account-token  3
default-token-4fsjr  kubernetes.io/service-account-token  3
$ kubectl describe secret bar-token-ndvtr
Name:         bar-token-ndvtr
Namespace:    default
...
ca.crt:     1066 bytes
namespace:  7 bytes
token:      ...
...

When we describe the secret generated by SA, we will see that it contains 3 files, which will be mounted inside the Pod container in folder /var/run/secrets/kubernetes.io/serviceaccount.

To use a ServiceAccount other than default inside the Pod, we specify it in the spec.serviceAccountName field .

apiVersion: apps/v1
kind: Deployment
...
    spec:
      serviceAccountName: bar
      containers:
        - name: background-consume-queue
          image: registry.kala.ai/web-crm/background-consume-queue
...

So do we need to create another SA or just use one guy for quick results? To answer this question, by default, if an SA does not enable the Role Based Access Control authorization plugin , it will have the right to perform all actions on the API server, meaning an application in the container can use the SA. to authenticate to the API server and list Pods, delete Pods, and create new Pods normally, because it has enough rights. So to prevent that, we need to enable the Role Based Access Control authorization plugin.

Role Based Access Control

Since version 1.8.0, RBAC will be enabled by default, and we can create Roles and assign them to certain SAs. Only allow an SA to perform actions that we allow, according to the Principle of Least Privilege .

Action

The actions we can perform to the API server are HEAD, GET, POST, PUT, PATCH, DELETE. And these actions will correspond to a verb that we will use when defining the role.

Action

Verb

HEAD, GET

get

POST

create

PUT

update

PATCH

patch

DELETE

delete

RBAC resources

RBAC will have the following resources:

  • Roles: defines which verbs can be implemented on the namespace resource

  • ClusterRoles: defines which verbs can be implemented on the cluster resource

  • RoleBindings: assign Roles to an SA

  • ClusterRoleBindings: assign ClusterRoles to SA

The difference between Roles and ClusterRoles is that Roles is a namespace resource, meaning it will belong to a certain namespace, and only defines roles for SAs in a namespace. ClusterRoles will not belong to any namespace.

Create Role and RoleBinding

Now we will practice creating Roles and Clusterroles to better understand the theory. First we will create 2 namespaces:

$ kubectl create ns foo
namespace/foo created
$ kubectl create ns bar
namespace/bar created
$ kubectl run test --image=luksa/kubectl-proxy -n foo
pod/test created
$ kubectl run test --image=luksa/kubectl-proxy -n bar
pod/test created

Access Pod and make request.

$ kubectl exec -it test-145485760-ttq36 -n foo sh
/# curl localhost:8001/api/v1/namespaces/foo/services
User "system:serviceaccount:foo:default" cannot list services in the
namespace "foo".

We will see that with RBAC enabled, the SA will now have no rights. To allow the default SA in namespace foo to list services in namespace foo, we need to create a Role and use RoleBinding to assign permissions to this default SA. Create a file named service-reader.yaml with the following configuration:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: foo
  name: service-reader
rules:
  - apiGroups: [""]
    verbs: ["get", "list"]
    resources: ["services"]
$ kubectl apply -f service-reader.yaml -n foo

In the config file above, the apiGroups property will specify the group of the api we want to perform actions on, above we specify "" which means core api group /v1 path , if we want to perform actions on deployment then we will specify apiGroups as apps/v1. The verb field specifies the action we can perform on the api group group above, the resources field we specify is Service resources. Once we have created the Role, we need to bind it to SA using the following command:

$ kubectl create rolebinding test --role=service-reader --serviceaccount=foo:default -n foo

Or write the config file as follows:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: test
  namespace: foo
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role # this must be Role or ClusterRole
  name: service-reader # this must match the name of the Role or ClusterRole you wish to bind to
subjects:
  - kind: ServiceAccount # Kind is User or ServiceAccount
    name: default # name of the SA
    namespace: foo

Now we can call the list service API inside the Pod.

/# curl localhost:8001/api/v1/namespaces/foo/services
{
  "kind": "ServiceList",
  "apiVersion": "v1",
  "metadata": {
    "selfLink": "/api/v1/namespaces/foo/services",
    "resourceVersion": "24906"
  },
  "items": []
}

We can also use Rolebinding in this namespace for SA in another namespace. By adding SA to the subjects field of the Rolebinding.

$ kubectl edit rolebinding test -n foo
...
subjects:
...
- kind: ServiceAccount
  name: default
  namespace: bar

When we add the above subject, now the SA in the namespace bar can read the services in the namespace foo.

Create ClusterRole and ClusterRoleBinding

Now we will go through creating a ClusterRole. ClusterRole allows an SA to access Cluster resources such as Node, PersistentVolume, etc. In the current Pod, when we make an API request to list persistentvolumes then we will get an error.

/# curl localhost:8001/api/v1/persistentvolumes
User "system:serviceaccount:foo:default" cannot list persistentvolumes at the
cluster scope.

To perform this action, we must create a ClusterRole, create a file named pv-reader with the following configuration:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: pv-reader
rules:
  - apiGroups: [""]
    verbs: ["get", "list"]
    resources: ["persistentvolumes"]

The configuration of ClusterRole is the same as Role, we just need to change kind from Role to ClusterRole and do not need to specify namespace.

$ kubectl apply -f pv-reader.yaml

Then we create ClusterRoleBinding:

$ kubectl create clusterrolebinding pv-test --clusterrole=pv-reader --serviceaccount=foo:default

Now we can call the API server to list PV.

/# curl localhost:8001/api/v1/persistentvolumes
{
  "kind": "PersistentVolumeList",
  "apiVersion": "v1",
...

Default ClusterRole and ClusterRoleBinding

Kubernetes has a default ClusterRole and ClusterRoleBinding, we can list it with the command:

$ kubectl get clusterroles
NAME
admin
cluster-admin
edit
...
system:discovery
...
view
...
$ kubectl get clusterrolebindings
admin
cluster-admin
edit
...
system:discovery
...
view
...

Access non-resource URLs with system:discovery

The Kubernetes API server will be divided into two main categories: urls related to resources and urls not related to resources (called non-resource URLs). Resource URLs are urls that will list resources and perform operations on resources, while non-resource URLs will not have any direct interactions related to resources, for example, urls are used to list all resources. including urls that the API server supports.

For non-resource URLs, even authenticated or unauthenticated clients with the API server can access these non-resource URLs. This role is defined in system:discovery ClusterRole and ClusterRoleBinding.

Let's take a look at the config of system:discovery:

$ kubectl get clusterrole system:discovery -o yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
    name: system:discovery
...
rules:
- nonResourceURLs:
    - /api
    - /api/*
    - /apis
    - /apis/*
    - /healthz
    - /swaggerapi
    - /swaggerapi/*
    - /version
verbs:
- get

We will see that this role will define that we have the right to get information about non-resource URLs defined in the nonResourceURLs field. Above we talked about groups, which is a way to grant permission to a group of users or to each individual user. Then the system:discovery ClusterRoleBinding will bind the role to all users belonging to the authenticated, unauthenticated group.

$ kubectl get clusterrolebinding system:discovery -o yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
    name: system:discovery
...
roleRef:
    apiGroup: rbac.authorization.k8s.io
    kind: ClusterRole
    name: system:discovery # bind to ClusterRole
subjects:
    - apiGroup: rbac.authorization.k8s.io
      kind: Group
      name: system:authenticated # group authenticated
    - apiGroup: rbac.authorization.k8s.io
      kind: Group
      name: system:unauthenticated # group unauthenticated

List all resources in a namespace with ClusterRole view

View ClusterRole will define all roles allowing us to list all resources within a namespace. Let's take a look at the view 's config :

$ kubectl get clusterrole view -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
    name: view
...
rules:
    - apiGroups:
    - ""
resources:
    - configmaps
    - endpoints
    - persistentvolumeclaims
    - pods
    - replicationcontrollers
    - replicationcontrollers/scale
    - serviceaccounts
    - services
verbs:
    - get
    - list
    - watch
...

To use the ClusterRole view , just create a ClusterRoleBinding for it:

$ kubectl create clusterrolebinding view --clusterrole=view --serviceaccount=foo:default

And because it is a ClusterRole, the SA in foo namespace can also list resources other than its namespace. But we cannot use it to read the cluster resource, because it only has scope for the namespace resource. Inside the pod of foo namespace

/# curl localhost:8001/api/v1/namespaces/foo/pods
{
  "kind": "PodList",
  "apiVersion": "v1",
  ...

/# curl localhost:8001/api/v1/namespaces/bar/pods
{
  "kind": "PodList",
  "apiVersion": "v1",
  ...

Update resource with edit ClusterRole

eidt ClusterRole will inherit all the roles of the view and in addition, it also defines additional roles that allow us to perform the verbs create, update, patch, delete all resources within a namespace, except for Secret, Role, RoleBinding

Full control over namespace with admin ClusterRole

This admin ClusterRole allows us to have full rights on a namespace, including editing Secret, Role, RoleBinding. Except for ResourceQuotas (will be discussed in another article). The difference between edit and admin is that the admin can edit Secret, Role, RoleBinding. And the editor doesn't.

Full control over the cluster with cluster-admin ClusterRole

This guy is the guy who will give us all rights on the API server, cross namepspace, and can access cluster resources.

system:* ClusterRole

When we list the ClusterRole, we will see that there are many default ClusterRoles, including some prefixed with system:, these are the ClusterRoles used by kubernetes components. For example system:kube-scheduler is used by Scheduler.

Conclude

So we have learned about how to secure the API server using ServiceAccount with Role and ClusterRole. In practice, we should apply the Principle of Least Privilege , only allowing a person to do what he needs, not providing him with unnecessary rights. By creating different SAs and assigning a Role or ClusterRole to them, then assign that SA to the Pod. If you have any questions or need further clarification, you can ask in the comment section below. In this article, we will learn about how to secure the API server

PreviousPod internalNextNetwork

Last updated 1 year ago