Engineering Solution Architect Security and Observability
Session 04 - Compliance Frameworks 3 min read 8 lessons in this module
Mark complete
Tổng Quan Compliance Landscape
Compliance không chỉ là checkbox - nó định hình cách team thiết kế, build và vận hành software. Với .NET trên Azure, nhiều compliance controls đã có sẵn nhưng cần cấu hình đúng .
Framework Phạm vi Ai cần? SOC 2 Security, availability, processing integrity SaaS companies, B2B GDPR Data protection cho EU citizens Mọi app có EU users HIPAA Healthcare data protection Healthcare apps PCI DSS Payment card data Apps xử lý payment ISO 27001 Information security management Enterprise, government
SOC 2 - Trust Service Criteria
5 Trust Service Criteria
Criteria Focus .NET/Azure Implementation Security Protection against unauthorized access Azure AD, NSG, WAF, encryption Availability System uptime commitments SLOs, health checks, DR plan Processing Integrity Accurate, complete processing Input validation, idempotency Confidentiality Data protection for sensitive info Encryption at rest/transit, Key Vault Privacy PII handling per privacy notice Data classification, consent, retention
SOC 2 Technical Controls Mapping
Audit Logging Requirements
csharp
public class AuditLogEntry
{
public Guid Id { get ; init ; } = Guid.NewGuid();
public DateTimeOffset Timestamp { get ; init ; } = DateTimeOffset.UtcNow;
public required string Action { get ; init ; }
public required string ActorId { get ; init ; }
public required string ActorType { get ; init ; }
public string ? ResourceType { get ; init ; }
public string ? ResourceId { get ; init ; }
public string ? IpAddress { get ; init ; }
public string ? UserAgent { get ; init ; }
public required string Result { get ; init ; }
public string ? Details { get ; init ; }
}
public class AuditService
{
private readonly AppDbContext _ db;
private readonly IHttpContextAccessor _ httpContext;
public AuditService (AppDbContext db, IHttpContextAccessor httpContext )
{
_ db = db;
_ httpContext = httpContext;
}
public async Task LogAsync (string action, string result,
string ? resourceType = null , string ? resourceId = null ,
string ? details = null )
{
var context = _ httpContext.HttpContext;
var entry = new AuditLogEntry
{
Action = action,
ActorId = context?.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "system" ,
ActorType = context?.User.Identity?.IsAuthenticated == true ? "User" : "System" ,
ResourceType = resourceType,
ResourceId = resourceId,
IpAddress = context?.Connection.RemoteIpAddress?.ToString(),
UserAgent = context?.Request.Headers.UserAgent.ToString(),
Result = result,
Details = details
};
_ db.AuditLogs.Add(entry);
await _ db.SaveChangesAsync();
}
}
Quan trọng : Audit log table phải append-only - không cho phép UPDATE hoặc DELETE.
GDPR Requirements cho .NET Apps
Core GDPR Rights
Right Mô tả Implementation Right to Access User xem data của mình Export API endpoint Right to Rectification User sửa data sai Update API endpoint Right to Erasure "Right to be forgotten" Deletion/anonymization pipeline Right to Portability Export data ở format chuẩn JSON/CSV export Right to Object Từ chối processing Consent management Right to Restriction Hạn chế processing Processing flags
Consent Management
csharp
public class UserConsent
{
public Guid UserId { get ; set ; }
public required string Purpose { get ; set ; }
public bool IsGranted { get ; set ; }
public DateTimeOffset GrantedAt { get ; set ; }
public DateTimeOffset? RevokedAt { get ; set ; }
public required string ConsentVersion { get ; set ; }
public required string IpAddress { get ; set ; }
}
public class ConsentCheckFilter : IAsyncActionFilter
{
private readonly ConsentService _ consentService;
public ConsentCheckFilter (ConsentService consentService )
=> _ consentService = consentService;
public async Task OnActionExecutionAsync (
ActionExecutingContext context,
ActionExecutionDelegate next )
{
var userId = context.HttpContext.User
.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId is not null )
{
var hasConsent = await _ consentService
.HasValidConsentAsync(userId, "data-processing" );
if (!hasConsent)
{
context.Result = new StatusCodeResult(451 );
return ;
}
}
await next();
}
}
Right to Erasure Implementation
csharp
public class GdprDeletionService
{
private readonly AppDbContext _ db;
private readonly IBlobStorage _ blobStorage;
private readonly ILogger<GdprDeletionService> _ logger;
public async Task<DeletionResult> DeleteUserDataAsync (string userId )
{
var result = new DeletionResult { UserId = userId };
var orders = await _ db.Orders.Where(o => o.UserId == userId).ToListAsync();
foreach (var order in orders)
{
order.UserId = "DELETED" ;
order.CustomerName = "ANONYMIZED" ;
order.Email = null ;
order.ShippingAddress = "ANONYMIZED" ;
}
result.OrdersAnonymized = orders.Count;
var user = await _ db.Users.FindAsync(userId);
if (user is not null )
{
_ db.Users.Remove(user);
result.ProfileDeleted = true ;
}
var deletedBlobs = await _ blobStorage.DeleteUserFilesAsync(userId);
result.FilesDeleted = deletedBlobs;
_ logger.LogInformation(
"GDPR_DELETION: UserId={UserId} Orders={Orders} Files={Files}" ,
"HASH:" + HashUserId(userId),
result.OrdersAnonymized,
result.FilesDeleted);
await _ db.SaveChangesAsync();
return result;
}
private static string HashUserId (string userId )
=> Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(userId)))[..16 ];
}
Azure Compliance Manager
Sử dụng Compliance Manager
bash
az security assessment list \
--query "[?contains(displayName, 'SOC')]" \
--output table
az security pricing create \
--name VirtualMachines \
--tier Standard
az monitor diagnostic-settings create \
--name audit-logs \
--resource /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{app} \
--workspace /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.OperationalInsights/workspaces/{workspace} \
--logs '[{"category":"AppServiceAuditLogs","enabled":true,"retentionPolicy":{"enabled":true,"days":365}}]'
Compliance Dashboard KQL Queries
kusto
// Audit log analysis - ai đã access sensitive data?
AppServiceAuditLogs
| where TimeGenerated > ago(30d)
| where OperationName contains "sensitive"
| summarize AccessCount = count() by UserDisplayName, bin(TimeGenerated, 1d)
| order by AccessCount desc
// Failed authentication attempts
SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType != 0 // Non-zero = failure
| summarize FailureCount = count() by UserPrincipalName, IPAddress
| where FailureCount > 10
| order by FailureCount desc
Data Classification Strategy
Classification Levels
Level Mô tả Ví dụ Controls Public Có thể công khai Marketing content, docs Basic access control Internal Chỉ nhân viên Internal wiki, processes Authentication required Confidential Business sensitive Financial reports, roadmap Encryption + access control Restricted PII, regulated data SSN, health records, payment Encryption + audit + DLP
Implementation trong .NET
csharp
[AttributeUsage(AttributeTargets.Property) ]
public class DataClassificationAttribute : Attribute
{
public DataClassificationLevel Level { get ; }
public DataClassificationAttribute (DataClassificationLevel level ) => Level = level;
}
public enum DataClassificationLevel
{
Public,
Internal,
Confidential,
Restricted
}
public class Customer
{
public int Id { get ; set ; }
[DataClassification(DataClassificationLevel.Confidential) ]
public required string FullName { get ; set ; }
[DataClassification(DataClassificationLevel.Restricted) ]
public required string Email { get ; set ; }
[DataClassification(DataClassificationLevel.Restricted) ]
[PersonalData ]
public string ? PhoneNumber { get ; set ; }
[DataClassification(DataClassificationLevel.Public) ]
public required string PreferredLanguage { get ; set ; }
}
Data Retention Policies
Data Type Retention Period After Expiry Audit logs 7 years (SOC 2) Archive to cold storage User PII Until deletion request Delete/anonymize Transaction records 7 years (tax) Archive Application logs 90 days Delete Session data 24 hours Auto-expire Backup data 30 days Auto-rotate
Trade-offs
Quyết định Pro Con Strict data classification Clear controls, audit-friendly Process overhead, slower development Automated compliance checks Continuous assurance False positives, tool cost Encryption everywhere Maximum protection Performance impact, complexity Detailed audit logging Full traceability Storage cost, PII in logs risk GDPR hard delete True erasure Data integrity issues, cascading deletes GDPR soft delete (anonymize) Preserves referential integrity Phải ensure k-anonymity