From 9ab9443a0168a6bf3cae2a6f435c102e4c284200 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 20 Sep 2025 14:20:13 +0000 Subject: [PATCH 1/2] Initial plan From 705e03551bc2013893ac9d241a29527194ff801a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 20 Sep 2025 14:24:41 +0000 Subject: [PATCH 2/2] Add comprehensive authentication and authorization documentation Co-authored-by: paraskuk <5521579+paraskuk@users.noreply.github.com> --- AUTH_README.md | 227 ++++++++ AUTH_TESTING_SCRIPTS.md | 693 ++++++++++++++++++++++++ KUBERNETES_AUTH_GUIDE.md | 1074 ++++++++++++++++++++++++++++++++++++++ QUICK_AUTH_SETUP.md | 208 ++++++++ TERRAFORM_RBAC_CONFIG.md | 832 +++++++++++++++++++++++++++++ 5 files changed, 3034 insertions(+) create mode 100644 AUTH_README.md create mode 100644 AUTH_TESTING_SCRIPTS.md create mode 100644 KUBERNETES_AUTH_GUIDE.md create mode 100644 QUICK_AUTH_SETUP.md create mode 100644 TERRAFORM_RBAC_CONFIG.md diff --git a/AUTH_README.md b/AUTH_README.md new file mode 100644 index 0000000..368dc5d --- /dev/null +++ b/AUTH_README.md @@ -0,0 +1,227 @@ +# Authentication and Authorization Implementation Guide + +This directory contains comprehensive documentation and instructions for implementing authentication and authorization in the Fibonacci Kubernetes cluster. These documents are designed to guide LLM programs through the complete process of securing the cluster with proper RBAC policies, authentication mechanisms, and security best practices. + +## ๐Ÿ“‹ Documentation Overview + +### ๐ŸŽฏ Primary Implementation Guide +- **[KUBERNETES_AUTH_GUIDE.md](./KUBERNETES_AUTH_GUIDE.md)** - Complete, comprehensive guide covering all aspects of authentication and authorization implementation + +### โšก Quick Start Guides +- **[QUICK_AUTH_SETUP.md](./QUICK_AUTH_SETUP.md)** - Streamlined setup for basic authentication and authorization +- **[TERRAFORM_RBAC_CONFIG.md](./TERRAFORM_RBAC_CONFIG.md)** - Production-ready Terraform configurations for RBAC + +### ๐Ÿงช Testing and Validation +- **[AUTH_TESTING_SCRIPTS.md](./AUTH_TESTING_SCRIPTS.md)** - Comprehensive testing scripts and validation procedures + +## ๐ŸŽฏ Implementation Goals + +This implementation will provide: + +### Authentication Features +- โœ… **Service Account-based Authentication** - Secure pod-to-pod communication +- โœ… **User Certificate Authentication** - X.509 certificate-based user authentication +- โœ… **JWT Token Authentication** - Application-level authentication with role-based access +- โœ… **OIDC Integration** - Optional OpenID Connect provider integration + +### Authorization Features +- โœ… **Admin Role** - Full cluster access with all permissions +- โœ… **Reader Role** - Read-only access to resources and logs +- โœ… **Namespace Isolation** - Proper separation between application and monitoring +- โœ… **Network Policies** - Traffic control between services +- โœ… **Pod Security Standards** - Enhanced container security + +## ๐Ÿ—๏ธ Current vs Target Architecture + +### Current State +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Default Namespace โ”‚ +โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”‚ +โ”‚ โ”‚ Fibonacci App (port 8080) โ”‚โ”‚ +โ”‚ โ”‚ Prometheus (port 9090) โ”‚โ”‚ +โ”‚ โ”‚ OpenTelemetry (port 8889) โ”‚โ”‚ +โ”‚ โ”‚ Grafana โ”‚โ”‚ +โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ +``` + +### Target Architecture with Authentication +``` +โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” +โ”‚ Kubernetes Cluster โ”‚ +โ”‚ โ”‚ +โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”‚ +โ”‚ โ”‚ fibonacci-app โ”‚ โ”‚ monitoring โ”‚ โ”‚ auth-system โ”‚โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ”‚ +โ”‚ โ”‚ โ€ข Fibonacci App โ”‚ โ”‚ โ€ข Prometheus โ”‚ โ”‚ โ€ข OIDC Config โ”‚โ”‚ +โ”‚ โ”‚ โ€ข JWT Auth โ”‚ โ”‚ โ€ข Grafana โ”‚ โ”‚ โ€ข Certificates โ”‚โ”‚ +โ”‚ โ”‚ โ€ข Service Acc โ”‚ โ”‚ โ€ข OpenTelemetry โ”‚ โ”‚ โ€ข Secrets โ”‚โ”‚ +โ”‚ โ”‚ โ€ข Network Pol โ”‚ โ”‚ โ€ข Service Acc โ”‚ โ”‚ โ”‚โ”‚ +โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚โ”‚ +โ”‚ โ”‚ RBAC Layer โ”‚โ”‚ +โ”‚ โ”‚ โ€ข ClusterRoles: admin, reader, monitoring โ”‚โ”‚ +โ”‚ โ”‚ โ€ข RoleBindings: namespace-specific permissions โ”‚โ”‚ +โ”‚ โ”‚ โ€ข Service Accounts: per-component authentication โ”‚โ”‚ +โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚โ”‚ +โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ +``` + +## ๐Ÿš€ Quick Implementation Path + +For LLM programs looking to implement authentication and authorization quickly: + +### 1. **Start Here** - Basic Setup (15 minutes) +Follow **[QUICK_AUTH_SETUP.md](./QUICK_AUTH_SETUP.md)** for immediate basic protection: +- Create namespaces and service accounts +- Apply basic RBAC roles +- Test permissions + +### 2. **Production Ready** - Terraform Implementation (30 minutes) +Use **[TERRAFORM_RBAC_CONFIG.md](./TERRAFORM_RBAC_CONFIG.md)** for infrastructure-as-code: +- Complete Terraform configuration +- Production-ready security policies +- Automated deployment + +### 3. **Complete Implementation** - Full Security (1-2 hours) +Follow **[KUBERNETES_AUTH_GUIDE.md](./KUBERNETES_AUTH_GUIDE.md)** for comprehensive security: +- Application-level authentication +- Network policies +- Security contexts +- Monitoring and alerting + +### 4. **Validation** - Testing and Verification (30 minutes) +Use **[AUTH_TESTING_SCRIPTS.md](./AUTH_TESTING_SCRIPTS.md)** to validate: +- RBAC permissions +- Authentication mechanisms +- Network policies +- Security compliance + +## ๐ŸŽญ Role Definitions + +### ๐Ÿ‘‘ Admin Role (`fibonacci-cluster-admin`) +**Capabilities:** +- Full cluster access (create, read, update, delete all resources) +- User and RBAC management +- Namespace creation and management +- Security policy modification +- Access to all monitoring and logs + +**Use Cases:** +- Platform administrators +- DevOps engineers +- Security teams + +### ๐Ÿ‘๏ธ Reader Role (`fibonacci-cluster-reader`) +**Capabilities:** +- Read-only access to application resources +- View pods, services, deployments +- Access to application logs +- View monitoring dashboards +- No modification permissions + +**Use Cases:** +- Developers (read-only access) +- Support teams +- Auditors +- Monitoring systems + +### ๐Ÿ”ง Service Accounts +**Per-Component Authentication:** +- `fibonacci-service-account` - Application pods +- `prometheus-service-account` - Monitoring collection +- `otel-collector-service-account` - Telemetry collection +- `grafana-service-account` - Dashboard access + +## ๐Ÿ›ก๏ธ Security Features + +### Network Security +- **Network Policies** - Control traffic between namespaces +- **TLS Encryption** - Secure communication channels +- **Service Mesh Ready** - Compatible with Istio/Linkerd + +### Pod Security +- **Non-root Containers** - All containers run as non-root users +- **Read-only Filesystems** - Prevent runtime modifications +- **Capability Dropping** - Remove unnecessary Linux capabilities +- **Security Contexts** - Enforced security constraints + +### Authentication Security +- **JWT Token Validation** - Secure application access +- **Certificate-based Auth** - X.509 client certificates +- **Service Account Tokens** - Automatic pod authentication +- **OIDC Integration** - Enterprise identity provider support + +## ๐Ÿ“Š Compliance and Auditing + +### Audit Logging +- All API server interactions logged +- Authentication and authorization events tracked +- Network policy violations recorded +- RBAC permission checks audited + +### Compliance Features +- **Pod Security Standards** - CIS Kubernetes Benchmark compliance +- **RBAC Best Practices** - Principle of least privilege +- **Network Segmentation** - Defense in depth +- **Secret Management** - Secure credential handling + +## ๐Ÿ”ง Customization Options + +### Environment-Specific Configuration +- **Development** - Relaxed policies for easier debugging +- **Staging** - Production-like security with test data +- **Production** - Maximum security with all controls enabled + +### Integration Options +- **LDAP/Active Directory** - Enterprise user directories +- **OAuth 2.0 Providers** - Google, GitHub, Azure AD +- **Certificate Authorities** - Custom PKI integration +- **Vault Integration** - HashiCorp Vault secret management + +## ๐Ÿ“š Additional Resources + +### Kubernetes Documentation +- [RBAC Authorization](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) +- [Pod Security Standards](https://kubernetes.io/docs/concepts/security/pod-security-standards/) +- [Network Policies](https://kubernetes.io/docs/concepts/services-networking/network-policies/) + +### Security Best Practices +- [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes) +- [NIST Container Security](https://csrc.nist.gov/publications/detail/sp/800-190/final) +- [OWASP Kubernetes Security](https://owasp.org/www-project-kubernetes-security-cheatsheet/) + +## ๐ŸŽฏ Success Criteria + +After implementing the authentication and authorization system, you should achieve: + +- โœ… **Zero unauthorized access** - All API calls authenticated and authorized +- โœ… **Principle of least privilege** - Users and services have minimal required permissions +- โœ… **Network segmentation** - Traffic controlled between namespaces +- โœ… **Audit trail** - All security events logged and monitored +- โœ… **Security compliance** - Meeting industry security standards + +## ๐Ÿค Support and Troubleshooting + +Each documentation file includes: +- **Troubleshooting sections** - Common issues and solutions +- **Validation scripts** - Automated testing procedures +- **Debugging commands** - Quick diagnostic tools +- **Rollback procedures** - Safe implementation strategies + +## ๐Ÿ“ˆ Implementation Timeline + +| Phase | Duration | Description | +|-------|----------|-------------| +| **Phase 1** | 15 min | Basic RBAC setup with quick start guide | +| **Phase 2** | 30 min | Terraform implementation and automation | +| **Phase 3** | 45 min | Application-level authentication | +| **Phase 4** | 30 min | Network policies and security contexts | +| **Phase 5** | 30 min | Testing and validation | +| **Total** | **2.5 hours** | Complete secure cluster implementation | + +--- + +๐ŸŽฏ **Start your implementation journey with [QUICK_AUTH_SETUP.md](./QUICK_AUTH_SETUP.md) for immediate results, or dive deep with [KUBERNETES_AUTH_GUIDE.md](./KUBERNETES_AUTH_GUIDE.md) for comprehensive security.** \ No newline at end of file diff --git a/AUTH_TESTING_SCRIPTS.md b/AUTH_TESTING_SCRIPTS.md new file mode 100644 index 0000000..1c8900a --- /dev/null +++ b/AUTH_TESTING_SCRIPTS.md @@ -0,0 +1,693 @@ +# Authentication & Authorization Testing Scripts + +This document provides comprehensive testing scripts and validation procedures to verify the authentication and authorization implementation is working correctly. + +## Test Script Collection + +### 1. RBAC Permissions Test Script + +Create `test-rbac.sh`: + +```bash +#!/bin/bash + +echo "=== RBAC Permissions Testing ===" +echo "Testing various user permissions..." + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Function to test permission +test_permission() { + local user=$1 + local verb=$2 + local resource=$3 + local namespace=$4 + + if [ -n "$namespace" ]; then + result=$(kubectl auth can-i $verb $resource --as=$user -n $namespace 2>/dev/null) + echo -n "Testing: $user can $verb $resource in namespace $namespace: " + else + result=$(kubectl auth can-i $verb $resource --as=$user 2>/dev/null) + echo -n "Testing: $user can $verb $resource (cluster-wide): " + fi + + if [ "$result" = "yes" ]; then + echo -e "${GREEN}โœ“ ALLOWED${NC}" + return 0 + else + echo -e "${RED}โœ— DENIED${NC}" + return 1 + fi +} + +echo -e "\n${YELLOW}1. Testing Admin Permissions (should all be ALLOWED)${NC}" +test_permission "admin" "create" "deployments" "fibonacci-app" +test_permission "admin" "delete" "pods" "fibonacci-app" +test_permission "admin" "create" "namespaces" +test_permission "admin" "get" "secrets" "monitoring" +test_permission "admin" "create" "clusterroles" + +echo -e "\n${YELLOW}2. Testing Reader Permissions${NC}" +echo "Should be ALLOWED:" +test_permission "reader" "get" "pods" "fibonacci-app" +test_permission "reader" "list" "deployments" "fibonacci-app" +test_permission "reader" "watch" "services" "monitoring" +test_permission "reader" "get" "pods/log" "fibonacci-app" + +echo "Should be DENIED:" +test_permission "reader" "create" "deployments" "fibonacci-app" +test_permission "reader" "delete" "pods" "fibonacci-app" +test_permission "reader" "create" "secrets" "fibonacci-app" +test_permission "reader" "create" "namespaces" + +echo -e "\n${YELLOW}3. Testing Service Account Permissions${NC}" +test_permission "system:serviceaccount:fibonacci-app:fibonacci-service-account" "get" "pods" "fibonacci-app" +test_permission "system:serviceaccount:fibonacci-app:fibonacci-service-account" "create" "deployments" "fibonacci-app" +test_permission "system:serviceaccount:monitoring:prometheus-service-account" "get" "pods" + +echo -e "\n${YELLOW}4. Testing Cross-Namespace Access${NC}" +test_permission "reader" "get" "pods" "monitoring" +test_permission "system:serviceaccount:fibonacci-app:fibonacci-service-account" "get" "pods" "monitoring" + +echo -e "\n=== RBAC Testing Complete ===" +``` + +### 2. Authentication Test Script + +Create `test-authentication.sh`: + +```bash +#!/bin/bash + +echo "=== Authentication Testing ===" + +# Configuration +FIBONACCI_URL="http://localhost:8080" +ADMIN_TOKEN="" +READER_TOKEN="" + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +# Function to generate test JWT token (for testing purposes only) +generate_test_token() { + local role=$1 + local secret=${JWT_SECRET:-"your-secret-key"} + + # This is a simple JWT generation for testing + # In production, use proper JWT libraries + header='{"alg":"HS256","typ":"JWT"}' + payload="{\"sub\":\"test-user\",\"role\":\"$role\",\"exp\":$(($(date +%s) + 3600))}" + + header_b64=$(echo -n "$header" | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n') + payload_b64=$(echo -n "$payload" | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n') + + signature=$(echo -n "${header_b64}.${payload_b64}" | openssl dgst -sha256 -hmac "$secret" -binary | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n') + + echo "${header_b64}.${payload_b64}.${signature}" +} + +# Test unauthenticated access +test_unauthenticated() { + echo -e "\n${YELLOW}Testing Unauthenticated Access${NC}" + + echo -n "Testing /health endpoint (should be accessible): " + response=$(curl -s -o /dev/null -w "%{http_code}" "$FIBONACCI_URL/health") + if [ "$response" = "200" ]; then + echo -e "${GREEN}โœ“ SUCCESS (200)${NC}" + else + echo -e "${RED}โœ— FAILED ($response)${NC}" + fi + + echo -n "Testing /api/fibonacci/10 without token (should be 401): " + response=$(curl -s -o /dev/null -w "%{http_code}" "$FIBONACCI_URL/api/fibonacci/10") + if [ "$response" = "401" ]; then + echo -e "${GREEN}โœ“ CORRECTLY DENIED (401)${NC}" + else + echo -e "${RED}โœ— UNEXPECTED RESPONSE ($response)${NC}" + fi +} + +# Test authenticated access +test_authenticated() { + echo -e "\n${YELLOW}Testing Authenticated Access${NC}" + + # Generate test tokens + ADMIN_TOKEN=$(generate_test_token "admin") + READER_TOKEN=$(generate_test_token "reader") + + echo -n "Testing admin access to /api/fibonacci/10: " + response=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $ADMIN_TOKEN" "$FIBONACCI_URL/api/fibonacci/10") + if [ "$response" = "200" ]; then + echo -e "${GREEN}โœ“ SUCCESS (200)${NC}" + else + echo -e "${RED}โœ— FAILED ($response)${NC}" + fi + + echo -n "Testing reader access to /api/fibonacci/10: " + response=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $READER_TOKEN" "$FIBONACCI_URL/api/fibonacci/10") + if [ "$response" = "200" ]; then + echo -e "${GREEN}โœ“ SUCCESS (200)${NC}" + else + echo -e "${RED}โœ— FAILED ($response)${NC}" + fi + + echo -n "Testing admin access to /api/admin: " + response=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $ADMIN_TOKEN" "$FIBONACCI_URL/api/admin") + if [ "$response" = "200" ]; then + echo -e "${GREEN}โœ“ SUCCESS (200)${NC}" + else + echo -e "${RED}โœ— FAILED ($response)${NC}" + fi + + echo -n "Testing reader access to /api/admin (should be 403): " + response=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $READER_TOKEN" "$FIBONACCI_URL/api/admin") + if [ "$response" = "403" ]; then + echo -e "${GREEN}โœ“ CORRECTLY DENIED (403)${NC}" + else + echo -e "${RED}โœ— UNEXPECTED RESPONSE ($response)${NC}" + fi +} + +# Test invalid tokens +test_invalid_tokens() { + echo -e "\n${YELLOW}Testing Invalid Tokens${NC}" + + echo -n "Testing with invalid token: " + response=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer invalid.token.here" "$FIBONACCI_URL/api/fibonacci/10") + if [ "$response" = "401" ]; then + echo -e "${GREEN}โœ“ CORRECTLY DENIED (401)${NC}" + else + echo -e "${RED}โœ— UNEXPECTED RESPONSE ($response)${NC}" + fi + + echo -n "Testing with expired token: " + # Generate expired token (exp in the past) + header='{"alg":"HS256","typ":"JWT"}' + payload="{\"sub\":\"test-user\",\"role\":\"admin\",\"exp\":$(($(date +%s) - 3600))}" + header_b64=$(echo -n "$header" | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n') + payload_b64=$(echo -n "$payload" | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n') + signature=$(echo -n "${header_b64}.${payload_b64}" | openssl dgst -sha256 -hmac "your-secret-key" -binary | base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n') + expired_token="${header_b64}.${payload_b64}.${signature}" + + response=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $expired_token" "$FIBONACCI_URL/api/fibonacci/10") + if [ "$response" = "401" ]; then + echo -e "${GREEN}โœ“ CORRECTLY DENIED (401)${NC}" + else + echo -e "${RED}โœ— UNEXPECTED RESPONSE ($response)${NC}" + fi +} + +# Port forward the service for testing +echo "Starting port-forward to fibonacci service..." +kubectl port-forward svc/fibonacci-service 8080:8080 -n fibonacci-app & +PORT_FORWARD_PID=$! +sleep 3 + +# Run tests +test_unauthenticated +test_authenticated +test_invalid_tokens + +# Cleanup +kill $PORT_FORWARD_PID 2>/dev/null + +echo -e "\n=== Authentication Testing Complete ===" +``` + +### 3. Network Policy Test Script + +Create `test-network-policies.sh`: + +```bash +#!/bin/bash + +echo "=== Network Policy Testing ===" + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +# Test network connectivity +test_network_connectivity() { + local from_pod=$1 + local from_namespace=$2 + local to_service=$3 + local to_namespace=$4 + local port=$5 + local expected=$6 + + echo -n "Testing $from_pod -> $to_service:$port (expect $expected): " + + # Run connectivity test + result=$(kubectl exec -n $from_namespace $from_pod -- nc -zv $to_service.$to_namespace.svc.cluster.local $port 2>&1) + + if [[ $result == *"open"* ]] && [ "$expected" = "ALLOWED" ]; then + echo -e "${GREEN}โœ“ ALLOWED${NC}" + return 0 + elif [[ $result != *"open"* ]] && [ "$expected" = "DENIED" ]; then + echo -e "${GREEN}โœ“ CORRECTLY DENIED${NC}" + return 0 + else + echo -e "${RED}โœ— UNEXPECTED RESULT${NC}" + echo " Result: $result" + return 1 + fi +} + +# Create test pods +create_test_pods() { + echo "Creating test pods..." + + # Test pod in fibonacci-app namespace + kubectl run test-pod-app --image=busybox --restart=Never -n fibonacci-app -- sleep 3600 2>/dev/null || true + + # Test pod in monitoring namespace + kubectl run test-pod-monitoring --image=busybox --restart=Never -n monitoring -- sleep 3600 2>/dev/null || true + + # Test pod in default namespace + kubectl run test-pod-default --image=busybox --restart=Never -n default -- sleep 3600 2>/dev/null || true + + # Wait for pods to be ready + echo "Waiting for test pods to be ready..." + kubectl wait --for=condition=Ready pod/test-pod-app -n fibonacci-app --timeout=60s + kubectl wait --for=condition=Ready pod/test-pod-monitoring -n monitoring --timeout=60s + kubectl wait --for=condition=Ready pod/test-pod-default -n default --timeout=60s +} + +# Run network policy tests +run_network_tests() { + echo -e "\n${YELLOW}Testing Network Policies${NC}" + + # Test access to fibonacci service from different namespaces + echo -e "\n${YELLOW}Testing access to Fibonacci service (port 8080)${NC}" + test_network_connectivity "test-pod-app" "fibonacci-app" "fibonacci-service" "fibonacci-app" "8080" "ALLOWED" + test_network_connectivity "test-pod-monitoring" "monitoring" "fibonacci-service" "fibonacci-app" "8080" "ALLOWED" + test_network_connectivity "test-pod-default" "default" "fibonacci-service" "fibonacci-app" "8080" "DENIED" + + # Test access to prometheus service + echo -e "\n${YELLOW}Testing access to Prometheus service (port 9090)${NC}" + test_network_connectivity "test-pod-app" "fibonacci-app" "prometheus" "monitoring" "9090" "DENIED" + test_network_connectivity "test-pod-monitoring" "monitoring" "prometheus" "monitoring" "9090" "ALLOWED" + test_network_connectivity "test-pod-default" "default" "prometheus" "monitoring" "9090" "DENIED" + + # Test access to otel-collector + echo -e "\n${YELLOW}Testing access to OpenTelemetry Collector (port 8889)${NC}" + test_network_connectivity "test-pod-app" "fibonacci-app" "otel-collector" "monitoring" "8889" "ALLOWED" + test_network_connectivity "test-pod-monitoring" "monitoring" "otel-collector" "monitoring" "8889" "ALLOWED" + test_network_connectivity "test-pod-default" "default" "otel-collector" "monitoring" "8889" "DENIED" + + # Test DNS resolution (should work from all pods) + echo -e "\n${YELLOW}Testing DNS resolution${NC}" + echo -n "Testing DNS from fibonacci-app namespace: " + if kubectl exec -n fibonacci-app test-pod-app -- nslookup kubernetes.default.svc.cluster.local >/dev/null 2>&1; then + echo -e "${GREEN}โœ“ SUCCESS${NC}" + else + echo -e "${RED}โœ— FAILED${NC}" + fi + + echo -n "Testing DNS from monitoring namespace: " + if kubectl exec -n monitoring test-pod-monitoring -- nslookup kubernetes.default.svc.cluster.local >/dev/null 2>&1; then + echo -e "${GREEN}โœ“ SUCCESS${NC}" + else + echo -e "${RED}โœ— FAILED${NC}" + fi +} + +# Cleanup test pods +cleanup_test_pods() { + echo -e "\n${YELLOW}Cleaning up test pods...${NC}" + kubectl delete pod test-pod-app -n fibonacci-app --ignore-not-found=true + kubectl delete pod test-pod-monitoring -n monitoring --ignore-not-found=true + kubectl delete pod test-pod-default -n default --ignore-not-found=true +} + +# Main execution +create_test_pods +run_network_tests +cleanup_test_pods + +echo -e "\n=== Network Policy Testing Complete ===" +``` + +### 4. Security Validation Script + +Create `validate-security.sh`: + +```bash +#!/bin/bash + +echo "=== Security Validation ===" + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +# Check for security issues +check_security_contexts() { + echo -e "\n${YELLOW}Checking Pod Security Contexts${NC}" + + echo -n "Checking for pods running as root: " + root_pods=$(kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name}: {.spec.securityContext.runAsUser}{"\n"}{end}' | grep ': 0$' | wc -l) + if [ "$root_pods" -eq 0 ]; then + echo -e "${GREEN}โœ“ No pods running as root${NC}" + else + echo -e "${RED}โœ— Found $root_pods pods running as root${NC}" + fi + + echo -n "Checking for privileged containers: " + privileged_containers=$(kubectl get pods -A -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.securityContext.privileged}{"\n"}{end}{end}' | grep true | wc -l) + if [ "$privileged_containers" -eq 0 ]; then + echo -e "${GREEN}โœ“ No privileged containers found${NC}" + else + echo -e "${RED}โœ— Found $privileged_containers privileged containers${NC}" + fi + + echo -n "Checking for containers with privilege escalation: " + privilege_escalation=$(kubectl get pods -A -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.securityContext.allowPrivilegeEscalation}{"\n"}{end}{end}' | grep true | wc -l) + if [ "$privilege_escalation" -eq 0 ]; then + echo -e "${GREEN}โœ“ No containers with privilege escalation${NC}" + else + echo -e "${RED}โœ— Found $privilege_escalation containers with privilege escalation${NC}" + fi +} + +# Check RBAC configuration +check_rbac_config() { + echo -e "\n${YELLOW}Checking RBAC Configuration${NC}" + + echo -n "Checking for ClusterRoles: " + cluster_roles=$(kubectl get clusterroles | grep fibonacci | wc -l) + if [ "$cluster_roles" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $cluster_roles fibonacci ClusterRoles${NC}" + else + echo -e "${RED}โœ— No fibonacci ClusterRoles found${NC}" + fi + + echo -n "Checking for ClusterRoleBindings: " + cluster_role_bindings=$(kubectl get clusterrolebindings | grep fibonacci | wc -l) + if [ "$cluster_role_bindings" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $cluster_role_bindings fibonacci ClusterRoleBindings${NC}" + else + echo -e "${RED}โœ— No fibonacci ClusterRoleBindings found${NC}" + fi + + echo -n "Checking for namespace-specific Roles: " + roles=$(kubectl get roles -A | grep fibonacci | wc -l) + if [ "$roles" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $roles fibonacci Roles${NC}" + else + echo -e "${YELLOW}โš  No fibonacci Roles found${NC}" + fi + + echo -n "Checking for RoleBindings: " + role_bindings=$(kubectl get rolebindings -A | grep fibonacci | wc -l) + if [ "$role_bindings" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $role_bindings fibonacci RoleBindings${NC}" + else + echo -e "${YELLOW}โš  No fibonacci RoleBindings found${NC}" + fi +} + +# Check network policies +check_network_policies() { + echo -e "\n${YELLOW}Checking Network Policies${NC}" + + echo -n "Checking for NetworkPolicies in fibonacci-app namespace: " + app_netpols=$(kubectl get networkpolicies -n fibonacci-app 2>/dev/null | grep -v NAME | wc -l) + if [ "$app_netpols" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $app_netpols NetworkPolicies${NC}" + else + echo -e "${YELLOW}โš  No NetworkPolicies found in fibonacci-app namespace${NC}" + fi + + echo -n "Checking for NetworkPolicies in monitoring namespace: " + monitoring_netpols=$(kubectl get networkpolicies -n monitoring 2>/dev/null | grep -v NAME | wc -l) + if [ "$monitoring_netpols" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $monitoring_netpols NetworkPolicies${NC}" + else + echo -e "${YELLOW}โš  No NetworkPolicies found in monitoring namespace${NC}" + fi +} + +# Check secrets +check_secrets() { + echo -e "\n${YELLOW}Checking Secrets${NC}" + + echo -n "Checking for JWT secrets: " + jwt_secrets=$(kubectl get secrets -A | grep jwt | wc -l) + if [ "$jwt_secrets" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $jwt_secrets JWT secrets${NC}" + else + echo -e "${YELLOW}โš  No JWT secrets found${NC}" + fi + + echo -n "Checking for service account tokens: " + sa_tokens=$(kubectl get secrets -A | grep token | wc -l) + if [ "$sa_tokens" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $sa_tokens service account tokens${NC}" + else + echo -e "${RED}โœ— No service account tokens found${NC}" + fi +} + +# Check service accounts +check_service_accounts() { + echo -e "\n${YELLOW}Checking Service Accounts${NC}" + + echo -n "Checking for fibonacci service accounts: " + fibonacci_sas=$(kubectl get serviceaccounts -A | grep fibonacci | wc -l) + if [ "$fibonacci_sas" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $fibonacci_sas fibonacci service accounts${NC}" + else + echo -e "${RED}โœ— No fibonacci service accounts found${NC}" + fi + + echo -n "Checking for monitoring service accounts: " + monitoring_sas=$(kubectl get serviceaccounts -n monitoring | grep -E "(prometheus|otel|grafana)" | wc -l) + if [ "$monitoring_sas" -gt 0 ]; then + echo -e "${GREEN}โœ“ Found $monitoring_sas monitoring service accounts${NC}" + else + echo -e "${YELLOW}โš  No monitoring service accounts found${NC}" + fi +} + +# Generate security report +generate_security_report() { + echo -e "\n${YELLOW}Generating Security Report${NC}" + + report_file="security-report-$(date +%Y%m%d-%H%M%S).txt" + + { + echo "Kubernetes Security Report" + echo "Generated: $(date)" + echo "==========================" + echo + + echo "RBAC Resources:" + kubectl get clusterroles,clusterrolebindings,roles,rolebindings -A | grep fibonacci + echo + + echo "Service Accounts:" + kubectl get serviceaccounts -A | grep -E "(fibonacci|prometheus|otel|grafana)" + echo + + echo "Network Policies:" + kubectl get networkpolicies -A + echo + + echo "Secrets:" + kubectl get secrets -A | grep -E "(jwt|token|auth)" + echo + + echo "Pod Security Contexts:" + kubectl get pods -A -o custom-columns="NAMESPACE:.metadata.namespace,NAME:.metadata.name,USER:.spec.securityContext.runAsUser,PRIVILEGED:.spec.containers[*].securityContext.privileged" + + } > "$report_file" + + echo "Security report saved to: $report_file" +} + +# Main execution +check_security_contexts +check_rbac_config +check_network_policies +check_secrets +check_service_accounts +generate_security_report + +echo -e "\n=== Security Validation Complete ===" +``` + +### 5. Complete Test Suite Runner + +Create `run-all-tests.sh`: + +```bash +#!/bin/bash + +echo "=========================================" +echo " Kubernetes Auth/Authz Test Suite" +echo "=========================================" + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# Test results tracking +TOTAL_TESTS=0 +PASSED_TESTS=0 +FAILED_TESTS=0 + +# Function to run a test script +run_test() { + local test_name=$1 + local test_script=$2 + + echo -e "\n${BLUE}๐Ÿงช Running: $test_name${NC}" + echo "=" | perl -lane 'print "=" x 50' + + if [ -f "$test_script" ] && [ -x "$test_script" ]; then + if ./"$test_script"; then + echo -e "${GREEN}โœ… $test_name: PASSED${NC}" + ((PASSED_TESTS++)) + else + echo -e "${RED}โŒ $test_name: FAILED${NC}" + ((FAILED_TESTS++)) + fi + else + echo -e "${YELLOW}โš ๏ธ $test_name: SKIPPED (script not found or not executable)${NC}" + fi + + ((TOTAL_TESTS++)) +} + +# Pre-flight checks +preflight_checks() { + echo -e "${BLUE}๐Ÿ” Running Pre-flight Checks${NC}" + echo "=" | perl -lane 'print "=" x 50' + + # Check kubectl + if ! command -v kubectl &> /dev/null; then + echo -e "${RED}โŒ kubectl not found${NC}" + exit 1 + fi + + # Check cluster connectivity + if ! kubectl cluster-info &> /dev/null; then + echo -e "${RED}โŒ Cannot connect to Kubernetes cluster${NC}" + exit 1 + fi + + # Check namespaces + echo -n "Checking fibonacci-app namespace: " + if kubectl get namespace fibonacci-app &> /dev/null; then + echo -e "${GREEN}โœ“${NC}" + else + echo -e "${YELLOW}โš ๏ธ Not found${NC}" + fi + + echo -n "Checking monitoring namespace: " + if kubectl get namespace monitoring &> /dev/null; then + echo -e "${GREEN}โœ“${NC}" + else + echo -e "${YELLOW}โš ๏ธ Not found${NC}" + fi + + echo -e "${GREEN}โœ… Pre-flight checks completed${NC}" +} + +# Make test scripts executable +chmod +x test-rbac.sh 2>/dev/null +chmod +x test-authentication.sh 2>/dev/null +chmod +x test-network-policies.sh 2>/dev/null +chmod +x validate-security.sh 2>/dev/null + +# Run all tests +preflight_checks + +run_test "RBAC Permissions Test" "test-rbac.sh" +run_test "Authentication Test" "test-authentication.sh" +run_test "Network Policies Test" "test-network-policies.sh" +run_test "Security Validation" "validate-security.sh" + +# Generate summary report +echo -e "\n${BLUE}๐Ÿ“Š Test Summary Report${NC}" +echo "=" | perl -lane 'print "=" x 50' +echo -e "Total Tests: $TOTAL_TESTS" +echo -e "${GREEN}Passed: $PASSED_TESTS${NC}" +echo -e "${RED}Failed: $FAILED_TESTS${NC}" + +if [ $FAILED_TESTS -eq 0 ]; then + echo -e "\n${GREEN}๐ŸŽ‰ All tests passed! Authentication and authorization setup is working correctly.${NC}" + exit 0 +else + echo -e "\n${RED}โš ๏ธ Some tests failed. Please review the output above and fix any issues.${NC}" + exit 1 +fi +``` + +## Usage Instructions + +1. **Make scripts executable:** + ```bash + chmod +x *.sh + ``` + +2. **Run individual tests:** + ```bash + ./test-rbac.sh + ./test-authentication.sh + ./test-network-policies.sh + ./validate-security.sh + ``` + +3. **Run complete test suite:** + ```bash + ./run-all-tests.sh + ``` + +4. **Set environment variables for authentication tests:** + ```bash + export JWT_SECRET="your-jwt-secret-key" + export FIBONACCI_URL="http://your-fibonacci-service" + ``` + +## Expected Results + +### RBAC Tests +- Admin users should have full access to all resources +- Reader users should only have read access to specified resources +- Service accounts should have appropriate namespace-scoped permissions + +### Authentication Tests +- Unauthenticated requests to protected endpoints should return 401 +- Valid tokens should allow access based on role +- Invalid/expired tokens should be rejected + +### Network Policy Tests +- Traffic should be allowed only according to defined policies +- Cross-namespace communication should be restricted appropriately +- DNS resolution should work from all pods + +### Security Validation +- No containers should run as root +- No privileged containers should exist +- All required RBAC resources should be present +- Network policies should be in place + +These test scripts provide comprehensive validation of your authentication and authorization implementation. \ No newline at end of file diff --git a/KUBERNETES_AUTH_GUIDE.md b/KUBERNETES_AUTH_GUIDE.md new file mode 100644 index 0000000..4c2f89c --- /dev/null +++ b/KUBERNETES_AUTH_GUIDE.md @@ -0,0 +1,1074 @@ +# Kubernetes Authentication and Authorization Implementation Guide + +This document provides comprehensive instructions for implementing authentication and authorization in the Fibonacci Kubernetes cluster. This guide is designed for LLM programs to follow step-by-step to secure the cluster with proper RBAC (Role-Based Access Control) policies. + +## Table of Contents + +1. [Overview](#overview) +2. [Prerequisites](#prerequisites) +3. [Authentication Setup](#authentication-setup) +4. [Authorization with RBAC](#authorization-with-rbac) +5. [Role Definitions](#role-definitions) +6. [Implementation Steps](#implementation-steps) +7. [Security Considerations](#security-considerations) +8. [Testing and Verification](#testing-and-verification) +9. [Troubleshooting](#troubleshooting) + +## Overview + +The current Fibonacci application runs in the `default` namespace without proper authentication and authorization controls. This guide will implement: + +- **Authentication**: Verify the identity of users and services +- **Authorization**: Control what authenticated users and services can do +- **RBAC Policies**: Define granular permissions for different roles +- **Service Accounts**: Secure pod-to-pod communication +- **Network Policies**: Control traffic flow between services + +### Current Architecture Analysis + +The existing deployment includes: +- Fibonacci web application (port 8080) +- Prometheus monitoring (port 9090) +- OpenTelemetry Collector (port 8889) +- Grafana dashboard +- All services running in `default` namespace + +## Prerequisites + +Before implementing authentication and authorization, ensure you have: + +- Kubernetes cluster with RBAC enabled (default in most modern clusters) +- `kubectl` configured with cluster-admin privileges +- Understanding of Kubernetes RBAC concepts +- Terraform and Helm installed (for deployment updates) + +## Authentication Setup + +### 1. Create Dedicated Namespaces + +First, segregate services into appropriate namespaces for better security isolation: + +```yaml +# Create namespaces +apiVersion: v1 +kind: Namespace +metadata: + name: fibonacci-app + labels: + security-tier: application +--- +apiVersion: v1 +kind: Namespace +metadata: + name: monitoring + labels: + security-tier: monitoring +--- +apiVersion: v1 +kind: Namespace +metadata: + name: auth-system + labels: + security-tier: authentication +``` + +### 2. Service Account Creation + +Create service accounts for different components with minimal required permissions: + +```yaml +# Fibonacci application service account +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fibonacci-service-account + namespace: fibonacci-app + labels: + app: fibonacci + security.tier: application +--- +# Prometheus service account +apiVersion: v1 +kind: ServiceAccount +metadata: + name: prometheus-service-account + namespace: monitoring + labels: + app: prometheus + security.tier: monitoring +--- +# OpenTelemetry Collector service account +apiVersion: v1 +kind: ServiceAccount +metadata: + name: otel-collector-service-account + namespace: monitoring + labels: + app: otel-collector + security.tier: monitoring +``` + +### 3. User Authentication Setup + +For user authentication, implement one of the following methods: + +#### Option A: Certificate-based Authentication + +```bash +# Generate client certificate for admin user +openssl genrsa -out admin.key 2048 +openssl req -new -key admin.key -out admin.csr -subj "/CN=admin/O=system:masters" +openssl x509 -req -in admin.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out admin.crt -days 365 + +# Generate client certificate for reader user +openssl genrsa -out reader.key 2048 +openssl req -new -key reader.key -out reader.csr -subj "/CN=reader/O=readers" +openssl x509 -req -in reader.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out reader.crt -days 365 +``` + +#### Option B: OIDC Integration (Recommended for Production) + +```yaml +# OIDC configuration for kube-apiserver +apiVersion: v1 +kind: ConfigMap +metadata: + name: oidc-config + namespace: kube-system +data: + oidc-issuer-url: "https://your-oidc-provider.com" + oidc-client-id: "kubernetes" + oidc-username-claim: "email" + oidc-groups-claim: "groups" +``` + +## Authorization with RBAC + +### 1. Cluster-Level Roles + +Define cluster-wide roles for different access levels: + +```yaml +# Cluster Admin Role +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fibonacci-cluster-admin + labels: + security.tier: admin +rules: +- apiGroups: ["*"] + resources: ["*"] + verbs: ["*"] +- nonResourceURLs: ["*"] + verbs: ["*"] +--- +# Cluster Reader Role +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fibonacci-cluster-reader + labels: + security.tier: reader +rules: +- apiGroups: [""] + resources: ["pods", "services", "configmaps", "secrets"] + verbs: ["get", "list", "watch"] +- apiGroups: ["apps"] + resources: ["deployments", "replicasets"] + verbs: ["get", "list", "watch"] +- apiGroups: ["monitoring.coreos.com"] + resources: ["servicemonitors", "prometheusrules"] + verbs: ["get", "list", "watch"] +``` + +### 2. Namespace-Specific Roles + +Create roles with granular permissions for specific namespaces: + +```yaml +# Fibonacci App Management Role +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + namespace: fibonacci-app + name: fibonacci-app-manager +rules: +- apiGroups: [""] + resources: ["pods", "services", "configmaps", "secrets", "persistentvolumeclaims"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +- apiGroups: ["apps"] + resources: ["deployments", "replicasets"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +- apiGroups: ["networking.k8s.io"] + resources: ["networkpolicies"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +--- +# Monitoring Management Role +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + namespace: monitoring + name: monitoring-manager +rules: +- apiGroups: [""] + resources: ["pods", "services", "configmaps", "secrets"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +- apiGroups: ["apps"] + resources: ["deployments", "daemonsets", "statefulsets"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +- apiGroups: ["monitoring.coreos.com"] + resources: ["servicemonitors", "prometheusrules", "prometheuses", "alertmanagers"] + verbs: ["get", "list", "watch", "create", "update", "patch", "delete"] +--- +# Application Reader Role +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + namespace: fibonacci-app + name: fibonacci-app-reader +rules: +- apiGroups: [""] + resources: ["pods", "services", "configmaps"] + verbs: ["get", "list", "watch"] +- apiGroups: ["apps"] + resources: ["deployments", "replicasets"] + verbs: ["get", "list", "watch"] +- apiGroups: [""] + resources: ["pods/log"] + verbs: ["get", "list"] +``` + +### 3. Role Bindings + +Bind roles to users and service accounts: + +```yaml +# Admin User Cluster Role Binding +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: fibonacci-admin-binding + labels: + security.tier: admin +subjects: +- kind: User + name: admin + apiGroup: rbac.authorization.k8s.io +- kind: ServiceAccount + name: fibonacci-service-account + namespace: fibonacci-app +roleRef: + kind: ClusterRole + name: fibonacci-cluster-admin + apiGroup: rbac.authorization.k8s.io +--- +# Reader User Cluster Role Binding +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: fibonacci-reader-binding + labels: + security.tier: reader +subjects: +- kind: User + name: reader + apiGroup: rbac.authorization.k8s.io +- kind: Group + name: readers + apiGroup: rbac.authorization.k8s.io +roleRef: + kind: ClusterRole + name: fibonacci-cluster-reader + apiGroup: rbac.authorization.k8s.io +--- +# Service Account Role Bindings +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fibonacci-app-manager-binding + namespace: fibonacci-app +subjects: +- kind: ServiceAccount + name: fibonacci-service-account + namespace: fibonacci-app +roleRef: + kind: Role + name: fibonacci-app-manager + apiGroup: rbac.authorization.k8s.io +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: monitoring-manager-binding + namespace: monitoring +subjects: +- kind: ServiceAccount + name: prometheus-service-account + namespace: monitoring +- kind: ServiceAccount + name: otel-collector-service-account + namespace: monitoring +roleRef: + kind: Role + name: monitoring-manager + apiGroup: rbac.authorization.k8s.io +``` + +## Role Definitions + +### Admin Role Capabilities +- **Full cluster access**: Can perform any operation on any resource +- **User management**: Can create, modify, and delete user accounts and permissions +- **Resource management**: Can deploy, scale, and delete applications +- **Security management**: Can modify RBAC policies and security configurations +- **Monitoring access**: Full access to all monitoring and logging systems +- **Namespace management**: Can create, modify, and delete namespaces + +### Reader Role Capabilities +- **Read-only access**: Can view resources but cannot modify them +- **Log access**: Can view application and system logs +- **Metrics access**: Can view monitoring dashboards and metrics +- **Limited namespace access**: Can only access designated namespaces +- **No security operations**: Cannot view or modify security configurations +- **No user management**: Cannot create or modify user accounts + +## Implementation Steps + +### Step 1: Update Terraform Configuration + +Modify `main.tf` to include RBAC resources: + +```hcl +# Add to main.tf + +# Create namespaces +resource "kubernetes_namespace" "fibonacci_app" { + metadata { + name = "fibonacci-app" + labels = { + security-tier = "application" + } + } +} + +resource "kubernetes_namespace" "monitoring" { + metadata { + name = "monitoring" + labels = { + security-tier = "monitoring" + } + } +} + +# Service Accounts +resource "kubernetes_service_account" "fibonacci_sa" { + metadata { + name = "fibonacci-service-account" + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + labels = { + app = "fibonacci" + security-tier = "application" + } + } +} + +resource "kubernetes_service_account" "prometheus_sa" { + metadata { + name = "prometheus-service-account" + namespace = kubernetes_namespace.monitoring.metadata[0].name + labels = { + app = "prometheus" + security-tier = "monitoring" + } + } +} + +# Cluster Roles +resource "kubernetes_cluster_role" "fibonacci_admin" { + metadata { + name = "fibonacci-cluster-admin" + labels = { + security-tier = "admin" + } + } + + rule { + api_groups = ["*"] + resources = ["*"] + verbs = ["*"] + } + + rule { + non_resource_urls = ["*"] + verbs = ["*"] + } +} + +resource "kubernetes_cluster_role" "fibonacci_reader" { + metadata { + name = "fibonacci-cluster-reader" + labels = { + security-tier = "reader" + } + } + + rule { + api_groups = [""] + resources = ["pods", "services", "configmaps"] + verbs = ["get", "list", "watch"] + } + + rule { + api_groups = ["apps"] + resources = ["deployments", "replicasets"] + verbs = ["get", "list", "watch"] + } + + rule { + api_groups = [""] + resources = ["pods/log"] + verbs = ["get", "list"] + } +} + +# Role Bindings +resource "kubernetes_cluster_role_binding" "fibonacci_admin_binding" { + metadata { + name = "fibonacci-admin-binding" + labels = { + security-tier = "admin" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "ClusterRole" + name = kubernetes_cluster_role.fibonacci_admin.metadata[0].name + } + + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.fibonacci_sa.metadata[0].name + namespace = kubernetes_service_account.fibonacci_sa.metadata[0].namespace + } +} + +resource "kubernetes_cluster_role_binding" "fibonacci_reader_binding" { + metadata { + name = "fibonacci-reader-binding" + labels = { + security-tier = "reader" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "ClusterRole" + name = kubernetes_cluster_role.fibonacci_reader.metadata[0].name + } + + subject { + kind = "User" + name = "reader" + api_group = "rbac.authorization.k8s.io" + } + + subject { + kind = "Group" + name = "readers" + api_group = "rbac.authorization.k8s.io" + } +} +``` + +### Step 2: Update Deployment Configurations + +Modify the Fibonacci deployment to use the new service account and namespace: + +```hcl +# Update the fibonacci deployment in main.tf +resource "kubernetes_deployment" "fibonacci" { + metadata { + name = "fibonacci-deployment" + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "fibonacci" + } + } + + template { + metadata { + labels = { + app = "fibonacci" + } + } + + spec { + service_account_name = kubernetes_service_account.fibonacci_sa.metadata[0].name + + # Add security context + security_context { + run_as_non_root = true + run_as_user = 1000 + run_as_group = 1000 + fs_group = 1000 + } + + container { + name = "fibonacci" + image = "${var.docker_username}/fibonacci_rust:${var.docker_image_tag}" + + # Add security context for container + security_context { + allow_privilege_escalation = false + read_only_root_filesystem = true + run_as_non_root = true + run_as_user = 1000 + capabilities { + drop = ["ALL"] + } + } + + # ... rest of container configuration + } + } + } + } +} +``` + +### Step 3: Implement Network Policies + +Add network policies to control traffic between services: + +```yaml +# Network policy for Fibonacci app +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: fibonacci-network-policy + namespace: fibonacci-app +spec: + podSelector: + matchLabels: + app: fibonacci + policyTypes: + - Ingress + - Egress + ingress: + - from: + - namespaceSelector: + matchLabels: + security-tier: monitoring + ports: + - protocol: TCP + port: 8080 + - from: [] # Allow ingress from anywhere for the service + ports: + - protocol: TCP + port: 8080 + egress: + - to: + - namespaceSelector: + matchLabels: + security-tier: monitoring + ports: + - protocol: TCP + port: 8889 + - to: [] # Allow DNS resolution + ports: + - protocol: UDP + port: 53 +--- +# Network policy for monitoring namespace +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: monitoring-network-policy + namespace: monitoring +spec: + podSelector: {} + policyTypes: + - Ingress + - Egress + ingress: + - from: + - namespaceSelector: + matchLabels: + security-tier: application + - from: + - namespaceSelector: + matchLabels: + security-tier: monitoring + egress: + - to: [] # Allow all egress for monitoring tools +``` + +### Step 4: Application-Level Authentication + +Implement authentication at the application level by modifying the Rust application: + +#### Add Dependencies to Cargo.toml: + +```toml +[dependencies] +# ... existing dependencies +jsonwebtoken = "8.3" +serde_json = "1.0" +base64 = "0.21" +uuid = { version = "1.0", features = ["v4", "serde"] } +``` + +#### Create Authentication Middleware: + +```rust +// src/auth.rs +use actix_web::{dev::ServiceRequest, Error, HttpMessage}; +use actix_web_httpauth::extractors::bearer::{BearerAuth, Config}; +use actix_web_httpauth::extractors::AuthenticationError; +use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Claims { + pub sub: String, + pub role: String, + pub exp: usize, +} + +pub async fn validator(req: ServiceRequest, credentials: BearerAuth) -> Result { + let token = credentials.token(); + + // In production, use a proper secret key + let secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "your-secret-key".to_string()); + + match decode::( + token, + &DecodingKey::from_secret(secret.as_ref()), + &Validation::new(Algorithm::HS256), + ) { + Ok(token_data) => { + req.extensions_mut().insert(token_data.claims); + Ok(req) + } + Err(_) => { + let config = req.app_data::().map(|data| data.clone()).unwrap_or_else(Default::default); + Err(AuthenticationError::from(config).into()) + } + } +} +``` + +#### Update Main Application: + +```rust +// src/main.rs +mod auth; + +use actix_web::{web, App, HttpServer, HttpResponse, Result, HttpRequest}; +use actix_web_httpauth::middleware::HttpAuthentication; +use auth::{validator, Claims}; + +async fn fibonacci_protected(req: HttpRequest, path: web::Path) -> Result { + let claims = req.extensions().get::().unwrap(); + + // Check if user has appropriate role + match claims.role.as_str() { + "admin" | "reader" => { + // Existing fibonacci logic here + let n = path.into_inner(); + let result = calculate_fibonacci(n); + Ok(HttpResponse::Ok().json(result)) + } + _ => Ok(HttpResponse::Forbidden().json("Insufficient permissions")), + } +} + +async fn admin_only_endpoint(req: HttpRequest) -> Result { + let claims = req.extensions().get::().unwrap(); + + if claims.role != "admin" { + return Ok(HttpResponse::Forbidden().json("Admin access required")); + } + + Ok(HttpResponse::Ok().json("Admin endpoint accessed")) +} + +#[actix_web::main] +async fn main() -> std::io::Result<()> { + HttpServer::new(|| { + let auth = HttpAuthentication::bearer(validator); + + App::new() + .route("/health", web::get().to(health_check)) // Unprotected health check + .service( + web::scope("/api") + .wrap(auth) + .route("/fibonacci/{n}", web::get().to(fibonacci_protected)) + .route("/admin", web::get().to(admin_only_endpoint)) + ) + }) + .bind("0.0.0.0:8080")? + .run() + .await +} +``` + +### Step 5: Update Helm Charts + +Modify the Helm chart to include RBAC configurations: + +```yaml +# fibonacci/templates/rbac.yaml +{{- if .Values.rbac.create -}} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "fibonacci.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "fibonacci.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "fibonacci.fullname" . }}-role + namespace: {{ .Release.Namespace }} +rules: +- apiGroups: [""] + resources: ["pods", "services", "configmaps"] + verbs: ["get", "list", "watch"] +- apiGroups: ["apps"] + resources: ["deployments"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "fibonacci.fullname" . }}-rolebinding + namespace: {{ .Release.Namespace }} +subjects: +- kind: ServiceAccount + name: {{ include "fibonacci.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +roleRef: + kind: Role + name: {{ include "fibonacci.fullname" . }}-role + apiGroup: rbac.authorization.k8s.io +{{- end }} +``` + +Update `fibonacci/values.yaml`: + +```yaml +# Add RBAC configuration +rbac: + create: true + +serviceAccount: + create: true + annotations: {} + name: "" + +# Add security context +securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + +podSecurityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 1000 + capabilities: + drop: + - ALL +``` + +### Step 6: Environment Configuration + +Create environment-specific configuration files: + +```yaml +# config/development.yaml +authentication: + enabled: false + jwt_secret: "dev-secret-key" + +authorization: + default_role: "reader" + admin_users: + - "admin@localhost" + +security: + enforce_https: false + cors_enabled: true +``` + +```yaml +# config/production.yaml +authentication: + enabled: true + jwt_secret: "${JWT_SECRET}" + oidc: + issuer: "${OIDC_ISSUER}" + client_id: "${OIDC_CLIENT_ID}" + +authorization: + default_role: "reader" + admin_users: + - "${ADMIN_USERS}" + +security: + enforce_https: true + cors_enabled: false +``` + +## Security Considerations + +### 1. Secret Management + +- **Never hardcode secrets** in configuration files or code +- Use Kubernetes Secrets for sensitive data +- Consider using a secret management system like HashiCorp Vault +- Rotate secrets regularly + +```yaml +# Example secret for JWT signing +apiVersion: v1 +kind: Secret +metadata: + name: fibonacci-jwt-secret + namespace: fibonacci-app +type: Opaque +stringData: + jwt-secret: "your-base64-encoded-secret-here" +``` + +### 2. Pod Security Standards + +Implement Pod Security Standards to enhance security: + +```yaml +# Pod Security Policy +apiVersion: policy/v1beta1 +kind: PodSecurityPolicy +metadata: + name: fibonacci-psp +spec: + privileged: false + allowPrivilegeEscalation: false + requiredDropCapabilities: + - ALL + volumes: + - 'configMap' + - 'emptyDir' + - 'projected' + - 'secret' + - 'downwardAPI' + - 'persistentVolumeClaim' + runAsUser: + rule: 'MustRunAsNonRoot' + seLinux: + rule: 'RunAsAny' + fsGroup: + rule: 'RunAsAny' +``` + +### 3. Network Security + +- Implement network policies to restrict communication +- Use TLS for all inter-service communication +- Consider service mesh (like Istio) for advanced traffic management + +### 4. Audit Logging + +Enable audit logging to track all API calls: + +```yaml +# Audit policy +apiVersion: audit.k8s.io/v1 +kind: Policy +rules: +- level: Metadata + namespaces: ["fibonacci-app", "monitoring"] + verbs: ["get", "list", "create", "update", "patch", "delete"] +``` + +## Testing and Verification + +### 1. Test RBAC Permissions + +Create test scripts to verify role permissions: + +```bash +#!/bin/bash +# test-rbac.sh + +echo "Testing admin permissions..." +kubectl auth can-i create deployments --as=admin +kubectl auth can-i delete pods --as=admin + +echo "Testing reader permissions..." +kubectl auth can-i get pods --as=reader +kubectl auth can-i create deployments --as=reader # Should be "no" +kubectl auth can-i delete pods --as=reader # Should be "no" + +echo "Testing service account permissions..." +kubectl auth can-i get pods --as=system:serviceaccount:fibonacci-app:fibonacci-service-account +``` + +### 2. Test Authentication + +```bash +#!/bin/bash +# test-auth.sh + +echo "Testing unauthenticated access..." +curl -i http://localhost:8080/api/fibonacci/10 # Should return 401 + +echo "Testing authenticated access..." +# Get token first (implementation depends on your auth method) +TOKEN=$(get_jwt_token_for_user "reader") +curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/fibonacci/10 + +echo "Testing admin endpoint..." +ADMIN_TOKEN=$(get_jwt_token_for_user "admin") +curl -i -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:8080/api/admin +``` + +### 3. Security Validation + +```bash +#!/bin/bash +# security-validation.sh + +echo "Checking for privileged containers..." +kubectl get pods -o jsonpath='{.items[*].spec.containers[*].securityContext.privileged}' | grep -v true + +echo "Checking for containers running as root..." +kubectl get pods -o jsonpath='{.items[*].spec.containers[*].securityContext.runAsUser}' | grep -v 0 + +echo "Validating network policies..." +kubectl get networkpolicies -A + +echo "Checking RBAC bindings..." +kubectl get rolebindings,clusterrolebindings -A +``` + +## Troubleshooting + +### Common Issues and Solutions + +#### 1. Permission Denied Errors + +```bash +# Check current user permissions +kubectl auth can-i --as= + +# Check role bindings +kubectl get rolebindings,clusterrolebindings -A -o wide + +# Verify service account exists +kubectl get serviceaccounts -n +``` + +#### 2. Authentication Failures + +```bash +# Check JWT token validity +echo $TOKEN | base64 -d | jq . + +# Verify certificate configuration +openssl x509 -in -text -noout + +# Check OIDC configuration +kubectl get configmap oidc-config -n kube-system -o yaml +``` + +#### 3. Network Policy Issues + +```bash +# Test connectivity between pods +kubectl exec -it -- nc -zv + +# Check network policy configuration +kubectl describe networkpolicy -n + +# Verify DNS resolution +kubectl exec -it -- nslookup +``` + +#### 4. Service Account Token Issues + +```bash +# Check service account token +kubectl get secret $(kubectl get serviceaccount -o jsonpath='{.secrets[0].name}') -o yaml + +# Verify token mount in pod +kubectl exec -it -- ls -la /var/run/secrets/kubernetes.io/serviceaccount/ +``` + +### Monitoring and Alerting + +Set up monitoring for authentication and authorization events: + +```yaml +# Prometheus alerting rules +groups: +- name: kubernetes.auth + rules: + - alert: AuthenticationFailures + expr: increase(apiserver_audit_total{verb!="get",objectRef_resource!="events"}[5m]) > 10 + for: 2m + labels: + severity: warning + annotations: + summary: "High number of authentication failures" + + - alert: UnauthorizedAccess + expr: increase(apiserver_audit_total{verb="create",code!~"2.."}[5m]) > 5 + for: 1m + labels: + severity: critical + annotations: + summary: "Unauthorized access attempts detected" +``` + +## Deployment Checklist + +Before deploying authentication and authorization: + +- [ ] Backup existing cluster configuration +- [ ] Test RBAC policies in development environment +- [ ] Verify service account permissions +- [ ] Test authentication mechanisms +- [ ] Validate network policies +- [ ] Configure monitoring and alerting +- [ ] Update documentation +- [ ] Train team on new security procedures +- [ ] Plan rollback strategy +- [ ] Schedule deployment during maintenance window + +## Additional Resources + +- [Kubernetes RBAC Documentation](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) +- [Pod Security Standards](https://kubernetes.io/docs/concepts/security/pod-security-standards/) +- [Network Policies](https://kubernetes.io/docs/concepts/services-networking/network-policies/) +- [Audit Logging](https://kubernetes.io/docs/tasks/debug-application-cluster/audit/) +- [Security Best Practices](https://kubernetes.io/docs/concepts/security/) + +This comprehensive guide provides all the necessary instructions for implementing robust authentication and authorization in the Fibonacci Kubernetes cluster. Follow each step carefully and test thoroughly in a development environment before applying to production. \ No newline at end of file diff --git a/QUICK_AUTH_SETUP.md b/QUICK_AUTH_SETUP.md new file mode 100644 index 0000000..add8821 --- /dev/null +++ b/QUICK_AUTH_SETUP.md @@ -0,0 +1,208 @@ +# Quick Start Authentication Setup + +This document provides a streamlined implementation guide for quickly setting up basic authentication and authorization in the Fibonacci Kubernetes cluster. + +## Prerequisites + +- Kubernetes cluster with RBAC enabled +- `kubectl` with cluster-admin access +- Current Fibonacci application deployed + +## 1. Create Namespaces and Service Accounts + +```bash +# Create namespaces +kubectl create namespace fibonacci-app +kubectl create namespace monitoring + +# Create service accounts +kubectl create serviceaccount fibonacci-service-account -n fibonacci-app +kubectl create serviceaccount prometheus-service-account -n monitoring +``` + +## 2. Define Basic Roles + +Create `rbac-basic.yaml`: + +```yaml +# Admin ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fibonacci-admin +rules: +- apiGroups: ["*"] + resources: ["*"] + verbs: ["*"] +--- +# Reader ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fibonacci-reader +rules: +- apiGroups: [""] + resources: ["pods", "services", "configmaps"] + verbs: ["get", "list", "watch"] +- apiGroups: ["apps"] + resources: ["deployments", "replicasets"] + verbs: ["get", "list", "watch"] +- apiGroups: [""] + resources: ["pods/log"] + verbs: ["get"] +--- +# Bind admin role +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: fibonacci-admin-binding +subjects: +- kind: User + name: admin + apiGroup: rbac.authorization.k8s.io +roleRef: + kind: ClusterRole + name: fibonacci-admin + apiGroup: rbac.authorization.k8s.io +--- +# Bind reader role +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: fibonacci-reader-binding +subjects: +- kind: User + name: reader + apiGroup: rbac.authorization.k8s.io +roleRef: + kind: ClusterRole + name: fibonacci-reader + apiGroup: rbac.authorization.k8s.io +``` + +Apply the configuration: +```bash +kubectl apply -f rbac-basic.yaml +``` + +## 3. Update Existing Deployments + +Move existing deployments to new namespaces: + +```bash +# Export current fibonacci deployment +kubectl get deployment fibonacci-deployment -o yaml > fibonacci-deployment.yaml + +# Edit the file to: +# 1. Change namespace to "fibonacci-app" +# 2. Add serviceAccountName: fibonacci-service-account +# 3. Add security context + +# Delete old deployment and create new one +kubectl delete deployment fibonacci-deployment +kubectl apply -f fibonacci-deployment.yaml -n fibonacci-app + +# Do the same for services +kubectl get service fibonacci-service -o yaml > fibonacci-service.yaml +# Edit namespace and apply +kubectl delete service fibonacci-service +kubectl apply -f fibonacci-service.yaml -n fibonacci-app +``` + +## 4. Test Permissions + +```bash +# Test admin permissions (should work) +kubectl auth can-i create deployments --as=admin + +# Test reader permissions (should fail) +kubectl auth can-i create deployments --as=reader + +# Test reader read access (should work) +kubectl auth can-i get pods --as=reader +``` + +## 5. Create User Certificates (Optional) + +```bash +# Generate admin certificate +openssl genrsa -out admin.key 2048 +openssl req -new -key admin.key -out admin.csr -subj "/CN=admin/O=system:masters" + +# Generate reader certificate +openssl genrsa -out reader.key 2048 +openssl req -new -key reader.key -out reader.csr -subj "/CN=reader" + +# Sign certificates (requires cluster CA) +openssl x509 -req -in admin.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out admin.crt -days 365 +openssl x509 -req -in reader.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out reader.crt -days 365 +``` + +## 6. Update kubeconfig + +```bash +# Add admin user +kubectl config set-credentials admin --client-certificate=admin.crt --client-key=admin.key +kubectl config set-context admin-context --cluster=kubernetes --user=admin + +# Add reader user +kubectl config set-credentials reader --client-certificate=reader.crt --client-key=reader.key +kubectl config set-context reader-context --cluster=kubernetes --user=reader + +# Test contexts +kubectl config use-context admin-context +kubectl get pods -A # Should work + +kubectl config use-context reader-context +kubectl get pods -A # Should work (read-only) +kubectl create deployment test --image=nginx # Should fail +``` + +## 7. Basic Network Policy + +Create `network-policy-basic.yaml`: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: fibonacci-netpol + namespace: fibonacci-app +spec: + podSelector: + matchLabels: + app: fibonacci + policyTypes: + - Ingress + - Egress + ingress: + - from: [] # Allow all ingress + ports: + - protocol: TCP + port: 8080 + egress: + - to: [] # Allow all egress +``` + +Apply: +```bash +kubectl apply -f network-policy-basic.yaml +``` + +## 8. Verification + +```bash +# Check RBAC setup +kubectl get clusterroles | grep fibonacci +kubectl get clusterrolebindings | grep fibonacci + +# Check deployments in new namespaces +kubectl get deployments -n fibonacci-app +kubectl get deployments -n monitoring + +# Test application access +kubectl port-forward svc/fibonacci-service 8080:8080 -n fibonacci-app +curl http://localhost:8080/fibonacci?n=10 +``` + +This quick setup provides basic authentication and authorization. For production use, refer to the comprehensive guide in `KUBERNETES_AUTH_GUIDE.md`. \ No newline at end of file diff --git a/TERRAFORM_RBAC_CONFIG.md b/TERRAFORM_RBAC_CONFIG.md new file mode 100644 index 0000000..d52f30d --- /dev/null +++ b/TERRAFORM_RBAC_CONFIG.md @@ -0,0 +1,832 @@ +# Terraform RBAC Configuration Template + +This file provides production-ready Terraform configurations for implementing authentication and authorization in the Fibonacci Kubernetes cluster. + +## Complete Terraform RBAC Implementation + +Add the following to your `main.tf` file: + +### 1. Namespace Resources + +```hcl +# Create dedicated namespaces +resource "kubernetes_namespace" "fibonacci_app" { + metadata { + name = "fibonacci-app" + labels = { + "security-tier" = "application" + "monitoring" = "enabled" + "backup" = "required" + } + annotations = { + "description" = "Namespace for Fibonacci application" + } + } +} + +resource "kubernetes_namespace" "monitoring" { + metadata { + name = "monitoring" + labels = { + "security-tier" = "monitoring" + "monitoring" = "enabled" + "backup" = "required" + } + annotations = { + "description" = "Namespace for monitoring infrastructure" + } + } +} + +resource "kubernetes_namespace" "auth_system" { + metadata { + name = "auth-system" + labels = { + "security-tier" = "authentication" + "monitoring" = "enabled" + "backup" = "critical" + } + annotations = { + "description" = "Namespace for authentication and authorization services" + } + } +} +``` + +### 2. Service Accounts + +```hcl +# Fibonacci application service account +resource "kubernetes_service_account" "fibonacci_sa" { + metadata { + name = "fibonacci-service-account" + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + labels = { + app = "fibonacci" + component = "backend" + security-tier = "application" + } + annotations = { + "description" = "Service account for Fibonacci application pods" + } + } + + automount_service_account_token = true +} + +# Prometheus service account +resource "kubernetes_service_account" "prometheus_sa" { + metadata { + name = "prometheus-service-account" + namespace = kubernetes_namespace.monitoring.metadata[0].name + labels = { + app = "prometheus" + component = "monitoring" + security-tier = "monitoring" + } + annotations = { + "description" = "Service account for Prometheus monitoring" + } + } + + automount_service_account_token = true +} + +# OpenTelemetry Collector service account +resource "kubernetes_service_account" "otel_collector_sa" { + metadata { + name = "otel-collector-service-account" + namespace = kubernetes_namespace.monitoring.metadata[0].name + labels = { + app = "otel-collector" + component = "telemetry" + security-tier = "monitoring" + } + annotations = { + "description" = "Service account for OpenTelemetry Collector" + } + } + + automount_service_account_token = true +} + +# Grafana service account +resource "kubernetes_service_account" "grafana_sa" { + metadata { + name = "grafana-service-account" + namespace = kubernetes_namespace.monitoring.metadata[0].name + labels = { + app = "grafana" + component = "dashboard" + security-tier = "monitoring" + } + annotations = { + "description" = "Service account for Grafana dashboard" + } + } + + automount_service_account_token = true +} +``` + +### 3. Cluster Roles + +```hcl +# Admin cluster role with full permissions +resource "kubernetes_cluster_role" "fibonacci_cluster_admin" { + metadata { + name = "fibonacci-cluster-admin" + labels = { + security-tier = "admin" + rbac-scope = "cluster" + } + annotations = { + "description" = "Full cluster administration role for Fibonacci project" + } + } + + rule { + api_groups = ["*"] + resources = ["*"] + verbs = ["*"] + } + + rule { + non_resource_urls = ["*"] + verbs = ["*"] + } +} + +# Reader cluster role with read-only permissions +resource "kubernetes_cluster_role" "fibonacci_cluster_reader" { + metadata { + name = "fibonacci-cluster-reader" + labels = { + security-tier = "reader" + rbac-scope = "cluster" + } + annotations = { + "description" = "Read-only cluster access for Fibonacci project" + } + } + + # Pod and basic resource read access + rule { + api_groups = [""] + resources = ["pods", "services", "configmaps", "endpoints", "persistentvolumeclaims"] + verbs = ["get", "list", "watch"] + } + + # Application resource read access + rule { + api_groups = ["apps"] + resources = ["deployments", "replicasets", "daemonsets", "statefulsets"] + verbs = ["get", "list", "watch"] + } + + # Networking read access + rule { + api_groups = ["networking.k8s.io"] + resources = ["networkpolicies", "ingresses"] + verbs = ["get", "list", "watch"] + } + + # Monitoring resources read access + rule { + api_groups = ["monitoring.coreos.com"] + resources = ["servicemonitors", "prometheusrules", "prometheuses", "alertmanagers"] + verbs = ["get", "list", "watch"] + } + + # Log access + rule { + api_groups = [""] + resources = ["pods/log"] + verbs = ["get", "list"] + } + + # Metrics access + rule { + api_groups = ["metrics.k8s.io"] + resources = ["pods", "nodes"] + verbs = ["get", "list"] + } +} + +# Monitoring cluster role for monitoring services +resource "kubernetes_cluster_role" "fibonacci_monitoring" { + metadata { + name = "fibonacci-monitoring" + labels = { + security-tier = "monitoring" + rbac-scope = "cluster" + } + annotations = { + "description" = "Monitoring services cluster role" + } + } + + # Access to metrics and monitoring endpoints + rule { + api_groups = [""] + resources = ["nodes", "nodes/proxy", "nodes/metrics", "services", "endpoints", "pods"] + verbs = ["get", "list", "watch"] + } + + rule { + api_groups = ["extensions"] + resources = ["ingresses"] + verbs = ["get", "list", "watch"] + } + + rule { + non_resource_urls = ["/metrics", "/metrics/*"] + verbs = ["get"] + } +} +``` + +### 4. Namespace-Specific Roles + +```hcl +# Application manager role for fibonacci-app namespace +resource "kubernetes_role" "fibonacci_app_manager" { + metadata { + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + name = "fibonacci-app-manager" + labels = { + security-tier = "application" + rbac-scope = "namespace" + } + annotations = { + "description" = "Management role for Fibonacci application namespace" + } + } + + # Full access to application resources + rule { + api_groups = [""] + resources = ["pods", "services", "configmaps", "secrets", "persistentvolumeclaims", "serviceaccounts"] + verbs = ["get", "list", "watch", "create", "update", "patch", "delete"] + } + + rule { + api_groups = ["apps"] + resources = ["deployments", "replicasets", "daemonsets", "statefulsets"] + verbs = ["get", "list", "watch", "create", "update", "patch", "delete"] + } + + rule { + api_groups = ["networking.k8s.io"] + resources = ["networkpolicies"] + verbs = ["get", "list", "watch", "create", "update", "patch", "delete"] + } + + rule { + api_groups = ["rbac.authorization.k8s.io"] + resources = ["roles", "rolebindings"] + verbs = ["get", "list", "watch", "create", "update", "patch", "delete"] + } +} + +# Monitoring manager role for monitoring namespace +resource "kubernetes_role" "monitoring_manager" { + metadata { + namespace = kubernetes_namespace.monitoring.metadata[0].name + name = "monitoring-manager" + labels = { + security-tier = "monitoring" + rbac-scope = "namespace" + } + annotations = { + "description" = "Management role for monitoring namespace" + } + } + + # Full access to monitoring resources + rule { + api_groups = [""] + resources = ["pods", "services", "configmaps", "secrets", "persistentvolumeclaims", "serviceaccounts"] + verbs = ["get", "list", "watch", "create", "update", "patch", "delete"] + } + + rule { + api_groups = ["apps"] + resources = ["deployments", "replicasets", "daemonsets", "statefulsets"] + verbs = ["get", "list", "watch", "create", "update", "patch", "delete"] + } + + rule { + api_groups = ["monitoring.coreos.com"] + resources = ["servicemonitors", "prometheusrules", "prometheuses", "alertmanagers"] + verbs = ["get", "list", "watch", "create", "update", "patch", "delete"] + } +} + +# Application reader role for fibonacci-app namespace +resource "kubernetes_role" "fibonacci_app_reader" { + metadata { + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + name = "fibonacci-app-reader" + labels = { + security-tier = "reader" + rbac-scope = "namespace" + } + annotations = { + "description" = "Read-only role for Fibonacci application namespace" + } + } + + # Read-only access to application resources + rule { + api_groups = [""] + resources = ["pods", "services", "configmaps", "endpoints"] + verbs = ["get", "list", "watch"] + } + + rule { + api_groups = ["apps"] + resources = ["deployments", "replicasets"] + verbs = ["get", "list", "watch"] + } + + rule { + api_groups = [""] + resources = ["pods/log"] + verbs = ["get", "list"] + } +} +``` + +### 5. Role Bindings + +```hcl +# Cluster role bindings +resource "kubernetes_cluster_role_binding" "fibonacci_admin_binding" { + metadata { + name = "fibonacci-admin-binding" + labels = { + security-tier = "admin" + rbac-scope = "cluster" + } + annotations = { + "description" = "Binds admin users to cluster admin role" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "ClusterRole" + name = kubernetes_cluster_role.fibonacci_cluster_admin.metadata[0].name + } + + # Bind to admin users (replace with actual usernames) + subject { + kind = "User" + name = "admin" + api_group = "rbac.authorization.k8s.io" + } + + # Bind to fibonacci service account for admin operations + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.fibonacci_sa.metadata[0].name + namespace = kubernetes_service_account.fibonacci_sa.metadata[0].namespace + } + + # Bind to admin group + subject { + kind = "Group" + name = "system:masters" + api_group = "rbac.authorization.k8s.io" + } +} + +resource "kubernetes_cluster_role_binding" "fibonacci_reader_binding" { + metadata { + name = "fibonacci-reader-binding" + labels = { + security-tier = "reader" + rbac-scope = "cluster" + } + annotations = { + "description" = "Binds reader users to cluster reader role" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "ClusterRole" + name = kubernetes_cluster_role.fibonacci_cluster_reader.metadata[0].name + } + + # Bind to reader users + subject { + kind = "User" + name = "reader" + api_group = "rbac.authorization.k8s.io" + } + + # Bind to readers group + subject { + kind = "Group" + name = "readers" + api_group = "rbac.authorization.k8s.io" + } +} + +resource "kubernetes_cluster_role_binding" "fibonacci_monitoring_binding" { + metadata { + name = "fibonacci-monitoring-binding" + labels = { + security-tier = "monitoring" + rbac-scope = "cluster" + } + annotations = { + "description" = "Binds monitoring services to monitoring cluster role" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "ClusterRole" + name = kubernetes_cluster_role.fibonacci_monitoring.metadata[0].name + } + + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.prometheus_sa.metadata[0].name + namespace = kubernetes_service_account.prometheus_sa.metadata[0].namespace + } + + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.otel_collector_sa.metadata[0].name + namespace = kubernetes_service_account.otel_collector_sa.metadata[0].namespace + } +} + +# Namespace role bindings +resource "kubernetes_role_binding" "fibonacci_app_manager_binding" { + metadata { + name = "fibonacci-app-manager-binding" + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + labels = { + security-tier = "application" + rbac-scope = "namespace" + } + annotations = { + "description" = "Binds application managers to app manager role" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "Role" + name = kubernetes_role.fibonacci_app_manager.metadata[0].name + } + + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.fibonacci_sa.metadata[0].name + namespace = kubernetes_service_account.fibonacci_sa.metadata[0].namespace + } + + # Add app managers group + subject { + kind = "Group" + name = "fibonacci-app-managers" + api_group = "rbac.authorization.k8s.io" + } +} + +resource "kubernetes_role_binding" "monitoring_manager_binding" { + metadata { + name = "monitoring-manager-binding" + namespace = kubernetes_namespace.monitoring.metadata[0].name + labels = { + security-tier = "monitoring" + rbac-scope = "namespace" + } + annotations = { + "description" = "Binds monitoring managers to monitoring manager role" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "Role" + name = kubernetes_role.monitoring_manager.metadata[0].name + } + + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.prometheus_sa.metadata[0].name + namespace = kubernetes_service_account.prometheus_sa.metadata[0].namespace + } + + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.otel_collector_sa.metadata[0].name + namespace = kubernetes_service_account.otel_collector_sa.metadata[0].namespace + } + + subject { + kind = "ServiceAccount" + name = kubernetes_service_account.grafana_sa.metadata[0].name + namespace = kubernetes_service_account.grafana_sa.metadata[0].namespace + } +} + +resource "kubernetes_role_binding" "fibonacci_app_reader_binding" { + metadata { + name = "fibonacci-app-reader-binding" + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + labels = { + security-tier = "reader" + rbac-scope = "namespace" + } + annotations = { + "description" = "Binds app readers to app reader role" + } + } + + role_ref { + api_group = "rbac.authorization.k8s.io" + kind = "Role" + name = kubernetes_role.fibonacci_app_reader.metadata[0].name + } + + # Bind to readers group + subject { + kind = "Group" + name = "fibonacci-app-readers" + api_group = "rbac.authorization.k8s.io" + } +} +``` + +### 6. Secrets for Authentication + +```hcl +# JWT secret for application authentication +resource "kubernetes_secret" "fibonacci_jwt_secret" { + metadata { + name = "fibonacci-jwt-secret" + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + labels = { + app = "fibonacci" + security-tier = "application" + secret-type = "authentication" + } + annotations = { + "description" = "JWT signing secret for Fibonacci application" + } + } + + type = "Opaque" + + data = { + jwt-secret = base64encode(var.jwt_secret_key) + } +} + +# OIDC configuration secret +resource "kubernetes_secret" "oidc_config" { + metadata { + name = "oidc-config" + namespace = kubernetes_namespace.auth_system.metadata[0].name + labels = { + security-tier = "authentication" + secret-type = "oidc" + } + annotations = { + "description" = "OIDC provider configuration" + } + } + + type = "Opaque" + + data = { + oidc-issuer-url = base64encode(var.oidc_issuer_url) + oidc-client-id = base64encode(var.oidc_client_id) + oidc-client-secret = base64encode(var.oidc_client_secret) + } +} +``` + +### 7. Network Policies + +```hcl +# Network policy for Fibonacci application +resource "kubernetes_network_policy" "fibonacci_app_netpol" { + metadata { + name = "fibonacci-app-network-policy" + namespace = kubernetes_namespace.fibonacci_app.metadata[0].name + labels = { + app = "fibonacci" + security-tier = "application" + } + annotations = { + "description" = "Network policy for Fibonacci application" + } + } + + spec { + pod_selector { + match_labels = { + app = "fibonacci" + } + } + + policy_types = ["Ingress", "Egress"] + + # Allow ingress from monitoring namespace and anywhere for service access + ingress { + from { + namespace_selector { + match_labels = { + security-tier = "monitoring" + } + } + } + ports { + port = "8080" + protocol = "TCP" + } + } + + ingress { + from = [] # Allow from anywhere for external access + ports { + port = "8080" + protocol = "TCP" + } + } + + # Allow egress to monitoring namespace and DNS + egress { + to { + namespace_selector { + match_labels = { + security-tier = "monitoring" + } + } + } + ports { + port = "8889" + protocol = "TCP" + } + } + + # Allow DNS resolution + egress { + to = [] + ports { + port = "53" + protocol = "UDP" + } + } + + # Allow HTTPS for external API calls + egress { + to = [] + ports { + port = "443" + protocol = "TCP" + } + } + } +} + +# Network policy for monitoring namespace +resource "kubernetes_network_policy" "monitoring_netpol" { + metadata { + name = "monitoring-network-policy" + namespace = kubernetes_namespace.monitoring.metadata[0].name + labels = { + security-tier = "monitoring" + } + annotations = { + "description" = "Network policy for monitoring namespace" + } + } + + spec { + pod_selector = {} # Apply to all pods in namespace + + policy_types = ["Ingress", "Egress"] + + # Allow ingress from application and monitoring namespaces + ingress { + from { + namespace_selector { + match_labels = { + security-tier = "application" + } + } + } + } + + ingress { + from { + namespace_selector { + match_labels = { + security-tier = "monitoring" + } + } + } + } + + # Allow external access to Grafana and Prometheus + ingress { + from = [] + ports { + port = "3000" # Grafana + protocol = "TCP" + } + } + + ingress { + from = [] + ports { + port = "9090" # Prometheus + protocol = "TCP" + } + } + + # Allow all egress for monitoring tools + egress { + to = [] + } + } +} +``` + +### 8. Variables + +Add these variables to your `variables.tf`: + +```hcl +variable "jwt_secret_key" { + description = "Secret key for JWT token signing" + type = string + sensitive = true + default = "" +} + +variable "oidc_issuer_url" { + description = "OIDC provider issuer URL" + type = string + default = "" +} + +variable "oidc_client_id" { + description = "OIDC client ID" + type = string + default = "" +} + +variable "oidc_client_secret" { + description = "OIDC client secret" + type = string + sensitive = true + default = "" +} + +variable "enable_rbac" { + description = "Enable RBAC configuration" + type = bool + default = true +} + +variable "enable_network_policies" { + description = "Enable network policies" + type = bool + default = true +} +``` + +## Deployment Instructions + +1. **Update your terraform configuration:** + ```bash + terraform plan -var="jwt_secret_key=your-secret-key" -var="enable_rbac=true" + terraform apply -var="jwt_secret_key=your-secret-key" -var="enable_rbac=true" + ``` + +2. **Verify RBAC setup:** + ```bash + kubectl get clusterroles | grep fibonacci + kubectl get clusterrolebindings | grep fibonacci + kubectl get roles -A | grep fibonacci + kubectl get rolebindings -A | grep fibonacci + ``` + +3. **Test permissions:** + ```bash + kubectl auth can-i create deployments --as=admin + kubectl auth can-i create deployments --as=reader # Should be "no" + ``` + +This Terraform configuration provides a complete, production-ready RBAC setup for the Fibonacci Kubernetes cluster with proper separation of concerns and security best practices. \ No newline at end of file