.NET File Access Control Development
This skill guides development of .NET Standard 2.0 applications for Windows 10/11 that validate user principal permissions before file system operations, following test-driven development principles.
Objective
Build robust .NET applications that determine and enforce user principal permissions for file creation, reading, updating, and deletion operations with comprehensive logging and test coverage.
Step-by-Step Instructions
1. Project Setup
Create a .NET Standard 2.0 project targeting Windows 10/11Set up a corresponding unit test project using xUnit, NUnit, or MSTestInitialize git repository if not already doneVerify `requirements.md` exists and is properly formatted2. Requirements Management
Review `requirements.md` design sheetEnsure all tasks are marked with status: `[Pending]`, `[In Process]`, or `[Completed]`Work through tasks procedurally in order listedMark each task `[In Process]` before beginning workNever mark a task `[Completed]` until its unit test passes3. Test-Driven Development Workflow
For each feature or task:
**Red Light Phase:**
Write a failing unit test that describes the expected behaviorRun the test to confirm it fails (red light)Commit with message: "test: Add failing test for [feature name]"**Green Light Phase:**
Write minimal code to make the test passRun the test to confirm it passes (green light)Commit with message: "feat: Implement [feature name]"**Refactor Phase (if needed):**
Improve code quality while keeping tests passingCommit with message: "refactor: Improve [aspect] of [feature name]"4. User Confirmation Protocol
After completing each task item and verifying tests pass, present summary to userWait for explicit user confirmation before marking task `[Completed]`Create commit describing actions taken: "docs: Mark [task name] as completed"Proceed to next task only after user approval5. Core Functionality Priority
Implement in this order:
**Priority 1: Directory Access Rights**
Implement method to determine current user access rights on directoriesCheck read, write, modify, and delete permissionsWrite unit tests mocking Windows ACL checksLog permission results**Priority 2: File Access Rights Validation**
Implement pre-operation permission checks for create, read, update, deleteUse `System.Security.AccessControl` namespaceWrite unit tests for each CRUD operation permission checkReturn clear boolean or enum results**Priority 3: Access Denial Logging**
Implement structured logging (consider `Microsoft.Extensions.Logging`)Log events when user lacks permissionsLog file/directory path, operation attempted, user principal, timestampWrite unit tests verifying log entries are created correctly**Priority 4: Execute Authorized Operations**
Implement file CRUD operations that execute only after permission validationWrap operations in try-catch with appropriate loggingWrite unit tests using temporary test filesEnsure proper cleanup in test teardown**Enhancement: User Principal Name Validation**
Add method to check access rights by specific user principal name (not just current user)Use `WindowsIdentity` and impersonation where appropriateWrite unit tests with mock principalsDocument security implications6. Code Quality Standards
Follow C# naming conventions (PascalCase for public members, camelCase for private)Use meaningful variable and method namesAdd XML documentation comments for public APIsKeep methods focused and single-purposeHandle exceptions appropriately with informative messages7. Security Best Practices
Never suppress security exceptionsValidate all file paths to prevent path traversalUse `Path.GetFullPath()` to normalize pathsLog security events without exposing sensitive dataFollow principle of least privilege8. Documentation
Maintain `requirements.md` with current task statusesDocument any deviations from requirements with user approvalAdd inline comments for complex permission logicUpdate README with usage examplesExample Usage
When implementing directory access validation:
```csharp
// Test first (RED)
[Fact]
public void GetDirectoryAccessRights_CurrentUser_ReturnsAccessRights()
{
var service = new FileAccessService();
var rights = service.GetDirectoryAccessRights(@"C:\TestDir");
Assert.NotNull(rights);
Assert.True(rights.CanRead || !rights.CanRead); // Should return a result
}
// Then implement (GREEN)
public AccessRights GetDirectoryAccessRights(string directoryPath)
{
var dirInfo = new DirectoryInfo(directoryPath);
var security = dirInfo.GetAccessControl();
// Implementation details...
}
```
Constraints
Must target .NET Standard 2.0 onlyMust run on Windows 10/11 (no cross-platform requirement)No task is complete without passing unit testMust obtain user approval before proceeding to next taskMust commit after each significant changeMust follow red-light/green-light TDD cycle strictlyNotes
Use `System.Security.Principal.WindowsIdentity.GetCurrent()` for current userLeverage `System.Security.AccessControl` for ACL operationsConsider using `FileSystemAccessRule` for granular permission checksTest coverage should be >80% for production codeIntegration tests may require admin privileges to create test directories