[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AS0PFJGK5ZPYHPWSQDBS3D":3,"skill-same:01M7AS0PFJGK5ZPYHPWSQDBS3D":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AS0PFJGK5ZPYHPWSQDBS3D","cybersecurity-implementation",null,"Concrete copy-paste security patterns for Azure\u002F.NET 8\u002FReact\u002FBlazor\u002FCosmos\u002FPostgreSQL\u002FDatabricks. Use for Entra ID auth, MSAL.js, Microsoft.Identity.Web, .NET 8 middleware pipeline, rate limiting, BOLA prevention, DOMPurify\u002FCSP, PostgreSQL RLS, Cosmos hierarchical partition keys, Databricks Unity Catalog, Claude Code managed-settings.json, PostToolUse Semgrep hook, Key Vault Bicep, Private Endpoints, AKS Workload Identity, or KQL security queries. Six security domains, three-tier maturity model. Use with security-first-scrum.","the-vibey-project\u002Fvibey","the-vibey-project","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F329298758?v=4","01M7AJHGZ9722CTJ4JNQZVRH0Q","the vibey project","01M7AJHGZVMG2K7TGXQ6XFHVG3",5,"MIT","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fcybersecurity-implementation\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: cybersecurity-implementation\ndescription: \"Concrete copy-paste security patterns for Azure\u002F.NET 8\u002FReact\u002FBlazor\u002FCosmos\u002FPostgreSQL\u002FDatabricks. Use for Entra ID auth, MSAL.js, Microsoft.Identity.Web, .NET 8 middleware pipeline, rate limiting, BOLA prevention, DOMPurify\u002FCSP, PostgreSQL RLS, Cosmos hierarchical partition keys, Databricks Unity Catalog, Claude Code managed-settings.json, PostToolUse Semgrep hook, Key Vault Bicep, Private Endpoints, AKS Workload Identity, or KQL security queries. Six security domains, three-tier maturity model. Use with security-first-scrum.\"\n---\n\n# Enterprise Cybersecurity Implementation Guide\n\nProduction-ready, copy-paste security implementation for: Microsoft Azure, .NET 8 Web API,\nReact, Blazor WASM, CosmosDB, PostgreSQL, Databricks, Claude Code, Cursor IDE.\n\nThree-tier maturity model for each domain:\n- **Foundational** — get secure fast; correct flow selection and baseline controls\n- **Intermediate** — hardened for production; RBAC, rate limiting, resource authorization\n- **Advanced** — defense-in-depth; zero-secrets, network isolation, threat detection\n\n---\n\n## DOMAIN 1: IDENTITY AND AUTHENTICATION (ENTRA ID, JWT, OIDC)\n\n### Foundational — App Registrations and Correct Auth Flows\n\nCreate **separate Entra ID app registrations** for the API and each frontend (React SPA, Blazor\nWASM). Use \"Accounts in this organizational directory only\" for single-tenant internal apps.\n\n```bash\n# Create API app registration\naz ad app create --display-name \"myapp-api\" --sign-in-audience \"AzureADMyOrg\" \\\n  --identifier-uris \"api:\u002F\u002Fmyapp-api\"\n# Create SPA app registration\naz ad app create --display-name \"myapp-spa\" --sign-in-audience \"AzureADMyOrg\"\n# Create service principal (Enterprise Application)\naz ad sp create --id \u003CAPP_ID>\n```\n\n**Authentication flow selection is non-negotiable.** Wrong flows break security.\n\n| Scenario | Required Flow | Never Use |\n|---|---|---|\n| React SPA user login | Authorization Code + PKCE | Implicit Grant (deprecated, disabled) |\n| Blazor WASM user login | Authorization Code + PKCE | Implicit Grant |\n| Service-to-service \u002F daemons | Client Credentials | Shared secrets in config |\n| API calling downstream API for user | On-Behalf-Of (OBO) | Storing user tokens in service |\n| CLI tooling | Device Code | Embedded credentials |\n\n**.NET 8 Web API — Microsoft.Identity.Web** (NuGet: `Microsoft.Identity.Web` v3.x\u002Fv4.x):\n\n```csharp\n\u002F\u002F Program.cs\nusing Microsoft.Identity.Web;\nbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(\"AzureAd\"));\nbuilder.Services.AddAuthorization();\n```\n\n```json\n\u002F\u002F appsettings.json — non-secret values only; ClientSecret must NEVER appear here\n{\n  \"AzureAd\": {\n    \"Instance\": \"https:\u002F\u002Flogin.microsoftonline.com\u002F\",\n    \"TenantId\": \"your-tenant-id\",\n    \"ClientId\": \"your-api-client-id\",\n    \"Audience\": \"api:\u002F\u002Fyour-api-client-id\"\n  }\n}\n```\n\n**React with MSAL.js** (npm: `@azure\u002Fmsal-browser` v3.x, `@azure\u002Fmsal-react` v2.x):\n\n```typescript\n\u002F\u002F authConfig.ts\nexport const msalConfig: Configuration = {\n  auth: {\n    clientId: \"your-spa-client-id\",\n    authority: \"https:\u002F\u002Flogin.microsoftonline.com\u002Fyour-tenant-id\",\n    redirectUri: \"\u002F\",\n  },\n  cache: {\n    cacheLocation: \"sessionStorage\", \u002F\u002F NEVER localStorage — XSS-vulnerable\n    storeAuthStateInCookie: false,\n  },\n};\nexport const apiScopes = { scopes: [\"api:\u002F\u002Fyour-api-client-id\u002FApi.Read\"] };\n```\n\n```tsx\n\u002F\u002F index.tsx — Instantiate OUTSIDE component tree (never inside a component)\nconst msalInstance = new PublicClientApplication(msalConfig);\nawait msalInstance.initialize();\nawait msalInstance.handleRedirectPromise();\nconst accounts = msalInstance.getAllAccounts();\nif (accounts.length > 0) msalInstance.setActiveAccount(accounts[0]);\nroot.render(\u003CMsalProvider instance={msalInstance}>\u003CApp \u002F>\u003C\u002FMsalProvider>);\n```\n\n**Blazor WASM** (NuGet: `Microsoft.Authentication.WebAssembly.Msal` v8.x):\n\n```csharp\n\u002F\u002F Program.cs\nbuilder.Services.AddMsalAuthentication(options =>\n{\n    builder.Configuration.Bind(\"AzureAd\", options.ProviderOptions.Authentication);\n    options.ProviderOptions.DefaultAccessTokenScopes.Add(\n        \"api:\u002F\u002Fyour-api-client-id\u002FApi.Read\");\n    options.ProviderOptions.LoginMode = \"redirect\";\n});\n```\n\n**Critical anti-patterns to avoid:**\n- Storing tokens in `localStorage` (XSS-vulnerable)\n- Enabling implicit grant checkboxes in app registration\n- Sharing a single app registration across environments\n- Hardcoding client secrets in source code\n- Creating `PublicClientApplication` inside React components (re-created on every render)\n\n### Intermediate — JWT Validation, App Roles, Token Lifecycle\n\nJWT validation in .NET must enforce issuer, audience, lifetime, and signing key — all handled\nautomatically by `AddMicrosoftIdentityWebApi`. If configuring manually: `ClockSkew = TimeSpan.Zero`\n(the 5-minute default is too generous). Never hardcode signing keys — Microsoft rotates them via\nthe JWKS endpoint.\n\n**App Roles in manifest:**\n```json\n{\n  \"appRoles\": [\n    {\n      \"allowedMemberTypes\": [\"User\"],\n      \"displayName\": \"Admin\",\n      \"id\": \"unique-guid-here\",\n      \"isEnabled\": true,\n      \"value\": \"Admin\"\n    }\n  ]\n}\n```\n\n**Map App Roles to authorization policies:**\n```csharp\nbuilder.Services.AddAuthorizationBuilder()\n    .AddPolicy(\"AdminOnly\", policy => policy.RequireRole(\"Admin\"))\n    .AddPolicy(\"ReaderOrAdmin\", policy => policy.RequireRole(\"Reader\", \"Admin\"))\n    .AddPolicy(\"DepartmentFinance\", policy =>\n        policy.RequireClaim(\"department\", \"finance\"));\n```\n\n**Use App Roles over Group Claims.** Groups create an overage problem: users with more than 200\ngroups cause Entra ID to emit a `_claim_sources` reference instead of the groups array, requiring\na Graph API call. App Roles are portable and don't have this limitation.\n\n**Token storage in SPAs:** MSAL.js keeps tokens in-memory by default. `sessionStorage` is the\nmost secure persistent option (per-tab isolation, auto-clears on tab close). **Refresh token\nrotation is automatic** — SPAs receive one-time-use refresh tokens that rotate on each use.\nReplaying a used token revokes the entire token family.\n\n### Advanced — Managed Identities, Conditional Access, Zero-Secrets\n\n**Managed Identities eliminate all secrets from your .NET API configuration.** Core NuGet:\n`Azure.Identity` (v1.13.x).\n\n```csharp\n\u002F\u002F Production-optimized credential selection\nvar credential = builder.Environment.IsDevelopment()\n    ? new DefaultAzureCredential()\n    : new ManagedIdentityCredential();  \u002F\u002F Faster startup — skips environment probing\n\n\u002F\u002F CosmosDB with Managed Identity\nvar cosmosClient = new CosmosClient(\"https:\u002F\u002Fyour-account.documents.azure.com:443\u002F\", credential);\n\n\u002F\u002F PostgreSQL with periodic token refresh (tokens expire in 4-24 hours)\nvar dataSourceBuilder = new NpgsqlDataSourceBuilder(connStringWithoutPassword);\ndataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>\n{\n    var token = await credential.GetTokenAsync(new TokenRequestContext(\n        new[] { \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\" }), ct);\n    return token.Token;\n}, TimeSpan.FromHours(4), TimeSpan.FromSeconds(10));\n```\n\n```bash\n# Assign Cosmos DB Built-in Data Contributor role\naz cosmosdb sql role assignment create \\\n  --account-name myCosmosAccount --resource-group myRG \\\n  --role-definition-id \"00000000-0000-0000-0000-000000000002\" \\\n  --principal-id \"\u003Cmanaged-identity-object-id>\" --scope \"\u002F\"\n```\n\n**Conditional Access policies to deploy:**\n1. Require MFA for all users (exclude break-glass accounts)\n2. Block legacy authentication protocols (SMTP, IMAP, POP3 bypass Conditional Access)\n3. Require compliant devices via Intune\n4. Require MFA from non-trusted network locations\n\nAlways test with Report-only mode and the What If tool before enforcement.\n\n---\n\n## DOMAIN 2: API SECURITY (.NET 8 WEB API)\n\n### Foundational — Middleware Pipeline ORDER (Critical), Validation, CORS\n\n**Middleware ordering is the single most common security misconfiguration in .NET APIs.**\n`UseAuthentication` must precede `UseAuthorization` — reversing them causes authentication to\nsilently fail and authorization to pass for all requests.\n\n```csharp\nvar app = builder.Build();\n\nif (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }\nelse { app.UseHsts(); }\n\n\u002F\u002F Security headers — first substantial middleware\napp.Use(async (context, next) => {\n    context.Response.Headers[\"X-Content-Type-Options\"] = \"nosniff\";\n    context.Response.Headers[\"X-Frame-Options\"] = \"DENY\";\n    context.Response.Headers[\"Referrer-Policy\"] = \"strict-origin-when-cross-origin\";\n    context.Response.Headers[\"Permissions-Policy\"] =\n        \"accelerometer=(), camera=(), geolocation=(), microphone=()\";\n    await next();\n});\n\napp.UseHttpsRedirection();\napp.UseSerilogRequestLogging();\napp.UseRouting();\napp.UseRateLimiter();        \u002F\u002F Rate limit BEFORE auth to block brute force\napp.UseCors(\"SpaPolicy\");\napp.UseAuthentication();    \u002F\u002F WHO are you?\napp.UseAuthorization();     \u002F\u002F WHAT can you do?\napp.MapControllers();\n```\n\nRemove Kestrel Server header: `builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);`\n\n**Input validation** with FluentValidation (NuGet: `FluentValidation` v11.x +\n`FluentValidation.DependencyInjectionExtensions`). Note: `FluentValidation.AspNetCore` is\ndeprecated — use the base package:\n\n```csharp\npublic class CreateUserRequestValidator : AbstractValidator\u003CCreateUserRequest>\n{\n    public CreateUserRequestValidator()\n    {\n        RuleFor(x => x.Name).NotEmpty().MaximumLength(100)\n            .Matches(@\"^[a-zA-Z\\s\\-']+$\").WithMessage(\"Name contains invalid characters.\");\n        RuleFor(x => x.Email).NotEmpty().EmailAddress();\n        RuleFor(x => x.Age).InclusiveBetween(18, 120);\n    }\n}\n\u002F\u002F Program.cs\nbuilder.Services.AddValidatorsFromAssemblyContaining\u003CCreateUserRequestValidator>();\n```\n\n**CORS — exact allowed origins only:**\n```csharp\nvar allowedOrigins = builder.Configuration.GetSection(\"Cors:AllowedOrigins\").Get\u003Cstring[]>()!;\nbuilder.Services.AddCors(options =>\n{\n    options.AddPolicy(\"SpaPolicy\", policy => policy\n        .WithOrigins(allowedOrigins)  \u002F\u002F NEVER AllowAnyOrigin() in production\n        .AllowAnyHeader().AllowAnyMethod().AllowCredentials());\n});\n```\n\nTrailing slash in origin URLs (`\"https:\u002F\u002Fapp.example.com\u002F\"`) causes silent comparison failure.\nOmit trailing slashes.\n\n### Intermediate — Rate Limiting, BOLA via IAuthorizationHandler, Logging\n\n**Built-in rate limiting in .NET 8** (no extra NuGet needed):\n\n```csharp\nbuilder.Services.AddRateLimiter(options =>\n{\n    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;\n    options.AddTokenBucketLimiter(\"Api\", opt =>\n    {\n        opt.TokenLimit = 100;\n        opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10);\n        opt.TokensPerPeriod = 20;\n        opt.QueueLimit = 5;\n    });\n    \u002F\u002F Per-user rate limiting (falls back to IP for unauthenticated)\n    options.GlobalLimiter = PartitionedRateLimiter.Create\u003CHttpContext, string>(\n        httpContext => RateLimitPartition.GetFixedWindowLimiter(\n            partitionKey: httpContext.User.Identity?.Name\n                ?? httpContext.Connection.RemoteIpAddress?.ToString() ?? \"anon\",\n            factory: _ => new FixedWindowRateLimiterOptions\n            {\n                PermitLimit = 60, Window = TimeSpan.FromMinutes(1)\n            }));\n});\n```\n\nApply with `[EnableRateLimiting(\"Api\")]` on controllers or `.RequireRateLimiting(\"Api\")` on\nminimal API routes.\n\n**BOLA prevention via IAuthorizationHandler** (OWASP API1 — Broken Object Level Authorization):\n\n```csharp\npublic class DocumentAuthorizationHandler\n    : AuthorizationHandler\u003CSameAuthorRequirement, Document>\n{\n    protected override Task HandleRequirementAsync(\n        AuthorizationHandlerContext context,\n        SameAuthorRequirement requirement, Document resource)\n    {\n        if (context.User.Identity?.Name == resource.AuthorId)\n            context.Succeed(requirement);\n        \u002F\u002F Never call context.Succeed for unauthorized access — implicit failure is correct\n        return Task.CompletedTask;\n    }\n}\n```\n\n**Serilog with Application Insights:**\n```csharp\nbuilder.Host.UseSerilog((context, services, config) => config\n    .ReadFrom.Configuration(context.Configuration)\n    .Enrich.FromLogContext()\n    .WriteTo.Console()\n    .WriteTo.ApplicationInsights(\n        services.GetRequiredService\u003CTelemetryConfiguration>(),\n        TelemetryConverter.Traces));\n```\n\nNever log passwords, JWTs, API keys, connection strings, credit card numbers, or PII. Always log\nfailed auth, authorization denials, and suspicious input with structured fields.\n\n### Advanced — Key Vault Config, Swagger Lockdown, Minimal API Security\n\n**Zero-secrets configuration with Azure Key Vault:**\n```csharp\nvar kvUri = new Uri($\"https:\u002F\u002F{builder.Configuration[\"KeyVaultName\"]}.vault.azure.net\u002F\");\nbuilder.Configuration.AddAzureKeyVault(kvUri, new DefaultAzureCredential(),\n    new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(5) });\n```\n\nSecrets auto-refresh without restarts when using `IOptionsMonitor\u003CT>`.\n\n**Swagger must never be exposed in production:**\n```csharp\nif (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }\n\u002F\u002F For Swagger JWT auth in development — use Http type, not ApiKey\noptions.AddSecurityDefinition(\"Bearer\", new OpenApiSecurityScheme\n{\n    Type = SecuritySchemeType.Http,\n    Scheme = \"Bearer\",\n    BearerFormat = \"JWT\"\n});\n```\n\n**Minimal APIs — route group authorization:**\n```csharp\nvar admin = app.MapGroup(\"\u002Fapi\u002Fadmin\").RequireAuthorization(\"AdminOnly\");\nadmin.MapGet(\"\u002Fusers\", () => Results.Ok());\nadmin.MapDelete(\"\u002Fusers\u002F{id}\", (int id) => Results.NoContent());\n\u002F\u002F Explicit anonymous — document why\napp.MapGet(\"\u002Fapi\u002Fhealth\", () => Results.Ok(\"healthy\")).AllowAnonymous();\n```\n\n---\n\n## DOMAIN 3: FRONTEND SECURITY (REACT AND BLAZOR WASM)\n\n### Foundational — Token Management and XSS Prevention\n\n**Never store tokens in `localStorage`** — any XSS vulnerability enables trivial theft via\n`localStorage.getItem('token')`. Use `sessionStorage` (per-tab isolation, auto-clears on close).\n\n**Axios interceptor for automatic token attachment and silent refresh:**\n```typescript\n\u002F\u002F apiClient.ts\nimport axios from 'axios';\nimport { msalInstance } from '.\u002FauthConfig';\nimport { InteractionRequiredAuthError } from '@azure\u002Fmsal-browser';\n\nconst apiClient = axios.create({ baseURL: 'https:\u002F\u002Fapi.example.com' });\n\napiClient.interceptors.request.use(async (config) => {\n  const account = msalInstance.getActiveAccount();\n  if (!account) throw new Error('No active account');\n  try {\n    const response = await msalInstance.acquireTokenSilent({\n      scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'], account,\n    });\n    config.headers.Authorization = `Bearer ${response.accessToken}`;\n  } catch (error) {\n    if (error instanceof InteractionRequiredAuthError) {\n      await msalInstance.acquireTokenRedirect({\n        scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'],\n      });\n    }\n  }\n  return config;\n});\n```\n\n**Four vectors that bypass React's auto-escaping protection:**\n1. `dangerouslySetInnerHTML` without sanitization\n2. `href` with `javascript:` protocol\n3. Direct DOM manipulation via `ref.current.innerHTML`\n4. `eval()` with user input\n\n**DOMPurify SafeHTML wrapper** (npm: `dompurify`, `@types\u002Fdompurify`):\n```tsx\nimport DOMPurify from 'dompurify';\nexport function SafeHTML({ html }: { html: string }) {\n  const sanitized = DOMPurify.sanitize(html, {\n    ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a'],\n    FORBID_TAGS: ['script', 'style', 'iframe'],\n    FORBID_ATTR: ['onerror', 'onload', 'onclick'],\n  });\n  return \u003Cdiv dangerouslySetInnerHTML={{ __html: sanitized }} \u002F>;\n}\n```\n\n### Intermediate — Blazor WASM Constraints and Protected Routes\n\n**Blazor WASM fundamental security constraint:** Everything runs client-side. All .NET assemblies\nare downloadable and decompilable with ILSpy. All `[Authorize]` attributes and `AuthorizeView`\ncomponents are cosmetic — **the server API must re-validate every request**. Never put secrets,\nsensitive business logic, or intellectual property in Blazor WASM code.\n\n**Blazor WASM auth routing:**\n```razor\n\u003C!-- App.razor -->\n\u003CCascadingAuthenticationState>\n    \u003CRouter AppAssembly=\"@typeof(Program).Assembly\">\n        \u003CFound Context=\"routeData\">\n            \u003CAuthorizeRouteView RouteData=\"@routeData\" DefaultLayout=\"@typeof(MainLayout)\">\n                \u003CNotAuthorized>\n                    @if (context.User.Identity?.IsAuthenticated != true)\n                    { \u003CRedirectToLogin \u002F> }\n                    else\n                    { \u003Cp>You are not authorized.\u003C\u002Fp> }\n                \u003C\u002FNotAuthorized>\n            \u003C\u002FAuthorizeRouteView>\n        \u003C\u002FFound>\n    \u003C\u002FRouter>\n\u003C\u002FCascadingAuthenticationState>\n```\n\n**React protected route with role checking:**\n```tsx\nfunction ProtectedRoute({ allowedRoles }: { allowedRoles?: string[] }) {\n  const isAuthenticated = useIsAuthenticated();\n  const { accounts } = useMsal();\n  const location = useLocation();\n\n  if (!isAuthenticated)\n    return \u003CNavigate to=\"\u002Flogin\" state={{ from: location }} replace \u002F>;\n  if (allowedRoles?.length) {\n    const userRoles = (accounts[0]?.idTokenClaims as any)?.roles ?? [];\n    if (!allowedRoles.some(role => userRoles.includes(role)))\n      return \u003CNavigate to=\"\u002Funauthorized\" replace \u002F>;\n  }\n  return \u003COutlet \u002F>;\n}\n```\n\nBoth React and Blazor role-based UI rendering are UX features only. The API `[Authorize]` is the\nreal security boundary.\n\n### Advanced — CSP Headers, Dependency Security, SRI\n\n**Content Security Policy for React\u002FVite:**\n```typescript\n\u002F\u002F vite.config.ts\nexport default defineConfig({\n  build: { assetsInlineLimit: 0 }, \u002F\u002F Prevent inline scripts that bypass CSP\n  server: {\n    headers: {\n      'Content-Security-Policy': [\n        \"default-src 'self'\",\n        \"script-src 'self'\",\n        \"connect-src 'self' https:\u002F\u002Flogin.microsoftonline.com https:\u002F\u002Fapi.example.com\",\n        \"img-src 'self' data: https:\",\n        \"frame-ancestors 'none'\",\n      ].join('; '),\n    },\n  },\n});\n```\n\n**Production CSP (served by .NET backend):**\n```\ndefault-src 'self';\nscript-src 'self' 'nonce-{SERVER_GENERATED}' 'strict-dynamic';\nstyle-src 'self' 'nonce-{SERVER_GENERATED}';\nconnect-src 'self' https:\u002F\u002Flogin.microsoftonline.com https:\u002F\u002Fgraph.microsoft.com;\nframe-ancestors 'none';\nupgrade-insecure-requests;\n```\n\n**Dependency security automation:**\n```xml\n\u003C!-- .csproj — NuGet audit on every build -->\n\u003CPropertyGroup>\n    \u003CNuGetAudit>true\u003C\u002FNuGetAudit>\n    \u003CNuGetAuditMode>all\u003C\u002FNuGetAuditMode>\n    \u003CNuGetAuditLevel>low\u003C\u002FNuGetAuditLevel>\n    \u003CTreatWarningsAsErrors>true\u003C\u002FTreatWarningsAsErrors>\n\u003C\u002FPropertyGroup>\n```\n\n```yaml\n# .github\u002Fdependabot.yml\nversion: 2\nupdates:\n  - package-ecosystem: \"npm\"\n    directory: \"\u002Ffrontend\"\n    schedule: { interval: \"weekly\" }\n  - package-ecosystem: \"nuget\"\n    directory: \"\u002Fbackend\"\n    schedule: { interval: \"weekly\" }\n  - package-ecosystem: \"pip\"\n    directory: \"\u002Fdatabricks\"\n    schedule: { interval: \"weekly\" }\n```\n\n---\n\n## DOMAIN 4: DATA LAYER SECURITY (COSMOSDB, POSTGRESQL, DATABRICKS)\n\n### Foundational — Managed Identity Access, Encryption Defaults\n\nAll three platforms encrypt data at rest with AES-256 by default and enforce TLS 1.2+ in\ntransit. The foundational security step is eliminating connection strings with keys.\n\n**CosmosDB — assign Built-in Data Contributor role:**\n```bash\naz cosmosdb sql role assignment create \\\n  --account-name myCosmosAccount --resource-group myRG \\\n  --role-definition-id \"00000000-0000-0000-0000-000000000002\" \\\n  --principal-id \"\u003Cmanaged-identity-principal-id>\" --scope \"\u002F\"\n```\n\n```csharp\nvar cosmosClient = new CosmosClient(\n    \"https:\u002F\u002Fyour-account.documents.azure.com:443\u002F\",\n    new DefaultAzureCredential(),\n    new CosmosClientOptions { ConnectionMode = ConnectionMode.Direct });\n```\n\n**Critical pitfall:** Azure control-plane roles like \"Cosmos DB Account Contributor\" do NOT\ngrant data-plane access. You must assign Cosmos DB's native data-plane RBAC roles separately.\nAlways include `readMetadata` permission or queries fail with 403.\n\n**PostgreSQL — enable Entra ID auth, create Managed Identity principal:**\n```sql\n-- Run as Entra admin\nSELECT * FROM pgaadauth_create_principal('\u003Cidentity-name>', false, false);\nGRANT ALL ON ALL TABLES IN SCHEMA public TO \"\u003Cidentity-name>\";\n```\n\n**Databricks — Unity Catalog storage credentials with Managed Identity:**\n```sql\nCREATE STORAGE CREDENTIAL my_credential\nWITH (AZURE_MANAGED_IDENTITY = '\u003Cmanaged-identity-resource-id>');\nCREATE EXTERNAL LOCATION my_location\nURL 'abfss:\u002F\u002F\u003Ccontainer>@\u003Cstorage-account>.dfs.core.windows.net\u002F\u003Cpath>'\nWITH (STORAGE CREDENTIAL my_credential);\n```\n\nDatabricks notebook secrets: `dbutils.secrets.get(scope=\"my-kv-scope\", key=\"db-password\")`.\nSecret values are redacted in notebook output. Never hardcode credentials.\n\n### Intermediate — PostgreSQL RLS Tenant Isolation, CosmosDB Partition Keys, Audit Logging\n\n**PostgreSQL Row-Level Security — database-enforced multi-tenant isolation:**\n```sql\nCREATE TABLE tenant_data (\n    id SERIAL PRIMARY KEY,\n    tenant_id UUID NOT NULL,\n    data TEXT\n);\nALTER TABLE tenant_data ENABLE ROW LEVEL SECURITY;\nALTER TABLE tenant_data FORCE ROW LEVEL SECURITY; -- Apply even to table owners\n\nCREATE FUNCTION current_tenant_id() RETURNS UUID AS $$\nBEGIN\n    RETURN NULLIF(current_setting('app.tenant_id', true), '')::UUID;\nEND;\n$$ LANGUAGE plpgsql STABLE;\n\nCREATE POLICY tenant_isolation ON tenant_data\n    FOR ALL USING (tenant_id = current_tenant_id());\n```\n\nSet tenant context from .NET middleware before each request's DB operations:\n```csharp\nawait using var cmd = conn.CreateCommand();\ncmd.CommandText = \"SET LOCAL app.tenant_id = @tenantId\";\ncmd.Parameters.AddWithValue(\"tenantId\", tenantIdFromJwt);\nawait cmd.ExecuteNonQueryAsync();\n```\n\n**RLS is deny-by-default:** enabling it without policies blocks ALL access. Always index\n`tenant_id` columns for performance.\n\n**CosmosDB multi-tenant isolation** — hierarchical partition keys for large tenants:\n```csharp\nContainerProperties properties = new(\n    id: \"events\",\n    partitionKeyPaths: new List\u003Cstring> { \"\u002FtenantId\", \"\u002FuserId\", \"\u002FsessionId\" });\n```\n\nFor many small tenants, use `tenantId` as the partition key (most cost-effective). For tenants\nexceeding 20GB, use Hierarchical Partition Keys.\n\n**pgAudit for PostgreSQL audit logging:**\n```bash\naz postgres flexible-server parameter set \\\n  --server-name myserver --resource-group myRG \\\n  --name pgaudit.log --value \"WRITE,DDL\"\n```\n\nQuery audit logs: `AzureDiagnostics | where Message contains \"AUDIT:\" | where TimeGenerated > ago(1d)`\n\n### Advanced — Customer-Managed Keys, Unity Catalog Column Security, Purview\n\n**Disable key-based CosmosDB auth entirely to enforce RBAC:**\n```bash\naz cosmosdb update --name myaccount --resource-group myRG --disable-local-auth true\n```\n\n**Databricks Unity Catalog column-level security via masking functions:**\n```sql\nCREATE FUNCTION mask_email(email STRING) RETURNS STRING\nRETURN CASE\n  WHEN IS_ACCOUNT_GROUP_MEMBER('pii-readers') THEN email\n  ELSE CONCAT('***', SUBSTRING(email, LOCATE('@', email)))\nEND;\n\nALTER TABLE customers ALTER COLUMN email SET MASK mask_email;\n```\n\n**Row filters:**\n```sql\nALTER TABLE sales SET ROW FILTER filter_fn ON (region);\n```\n\nUse Unity Catalog for all data governance in Databricks. Never access data directly via storage\naccount keys — use service principals with Unity Catalog RBAC.\n\n**Microsoft Purview** for cross-platform data classification: register CosmosDB (schema from\nfirst 10 docs per container), PostgreSQL, and Unity Catalog (full metadata + lineage) in Purview\nData Map. Configure scanning schedules and apply sensitivity labels.\n\n---\n\n## DOMAIN 5: AI TOOL SECURITY (CLAUDE CODE AND CURSOR)\n\n### Foundational — The Threat Model Every Team Must Understand\n\nAI coding tools introduce five systemic risks:\n1. **Data exfiltration** — code sent to external APIs may include secrets\n2. **Prompt injection** via malicious context (doc strings, comments, file names)\n3. **Model hallucination** of insecure patterns\n4. **Intellectual property exposure**\n5. **Compliance gaps** — 63% of breached organizations lacked AI tool governance\n\nResearch from Apiiro (September 2025): AI-generated code introduced **10,000+ new security\nfindings per month** — a 10x increase from December 2024. Veracode found only **55% of\nAI-generated code was secure** across 100+ LLMs.\n\n**Most common security anti-patterns AI tools generate:**\n- **CWE-798 Hardcoded credentials:** `var connString = \"Server=prod;Password=abc123\";`\n- **CWE-89 SQL injection:** `FromSqlRaw($\"SELECT * FROM Users WHERE Id = {userId}\")`\n- **CWE-862 Missing authorization:** Controller actions without `[Authorize]`\n- **CWE-79 XSS in React:** `dangerouslySetInnerHTML={{ __html: userData.bio }}`\n- **CWE-502 Insecure deserialization:** `TypeNameHandling = TypeNameHandling.All`\n- **CWE-327 Weak cryptography:** `MD5.Create()` for password hashing\n\nTreat all AI-generated code as an untrusted pull request from a junior developer.\n\n### Intermediate — Claude Code and Cursor Enterprise Configuration\n\n**Claude Code settings hierarchy** (highest to lowest precedence):\n1. Enterprise `managed-settings.json` (cannot be overridden by users)\n2. CLI arguments\n3. `.claude\u002Fsettings.local.json`\n4. `.claude\u002Fsettings.json` (committed to repository)\n5. User settings\n\n**Enterprise-managed configuration — deploy this to every developer machine:**\n```json\n\u002F\u002F Linux:   \u002Fetc\u002Fclaude-code\u002Fmanaged-settings.json\n\u002F\u002F macOS:   \u002FLibrary\u002FApplication Support\u002FClaudeCode\u002Fmanaged-settings.json\n\u002F\u002F Windows: %ALLUSERSPROFILE%\\ClaudeCode\\managed-settings.json\n{\n  \"permissions\": {\n    \"deny\": [\n      \"Read(.\u002F.env)\",\n      \"Read(.\u002F.env.*)\",\n      \"Read(.\u002Fsecrets\u002F**)\",\n      \"Read(.\u002Fappsettings.*.json)\",\n      \"Read(~\u002F.aws\u002F**)\",\n      \"Read(~\u002F.ssh\u002F**)\",\n      \"Read(~\u002F.azure\u002F**)\",\n      \"Bash(curl:*)\",\n      \"Bash(wget:*)\",\n      \"Bash(nc:*)\"\n    ],\n    \"disableBypassPermissionsMode\": \"disable\",\n    \"defaultMode\": \"ask\"\n  },\n  \"sandbox\": { \"enabled\": true, \"allowUnsandboxedCommands\": false },\n  \"enableAllProjectMcpServers\": false,\n  \"forceLoginMethod\": \"console\",\n  \"forceLoginOrgUUID\": \"YOUR-ORG-UUID\"\n}\n```\n\n**Cursor privacy and file exclusions:**\n- Enable Privacy Mode: Settings → General → Privacy Mode (enforces zero data retention)\n- Create `.cursorignore` in every repository:\n```\n.env\n.env.*\n*.pem\n*.key\n*.pfx\nappsettings.Production.json\nappsettings.Staging.json\nsecrets\u002F\n.azure\u002F\n.aws\u002F\n.ssh\u002F\nlocal.settings.json\nlaunchSettings.json\n```\n\n**Known limitation:** `.cursorignore` blocks the agent from reading files but does not prevent\nit from suggesting code that references those files by name. CVE-2025-59944 demonstrated a\nfilename case bypass on Windows\u002FmacOS. Do not rely on `.cursorignore` as the sole control.\n\n**Certifications:** Claude Code has SOC 2 Type II, ISO 27001:2022, and ISO\u002FIEC 42001:2023.\nCursor has SOC 2 Type II. Both offer zero-retention agreements for enterprise\u002Fteam plans. Code\nis **not used for training** under commercial terms.\n\n### Advanced — PostToolUse Semgrep Hook, Security-First Prompting, Org Policy\n\n**PostToolUse Semgrep hook — wire this in every project's `.claude\u002Fsettings.json`:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": {\n      \"Edit\": \"semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten --quiet ${CLAUDE_FILE_PATH}\"\n    }\n  }\n}\n```\n\nThis runs Semgrep on every file edit automatically. If Semgrep finds an issue, fix it before\nproceeding — never move to the next step with an open finding.\n\n**Claude Code Security Review GitHub Action:**\n```yaml\n- uses: anthropics\u002Fclaude-code-security-review@main\n  with:\n    comment-pr: true\n    claude-api-key: ${{ secrets.CLAUDE_API_KEY }}\n```\n\n**Security-first prompting template:**\n```\nCreate a .NET 8 Web API endpoint for user registration.\nTHREAT MODEL: Public-facing, potential credential stuffing.\nSECURITY REQUIREMENTS:\n  - Authentication: [Authorize(Policy = \"WriterOrAdmin\")]\n  - Authorization: no user-owned data, standard RBAC\n  - Input validation: FluentValidation with email, name, password complexity\n  - Rate limiting: 5 requests\u002Fmin per IP\n  - Logging: log attempt with userId, never log password\n  - Error messages: generic (no account enumeration)\n```\n\n**Organizational AI security policy elements:**\n- Approved tool list (e.g., Claude Code + Cursor only, with enterprise configs deployed)\n- Data classification rules: PHI\u002FPCI\u002Fcredentials never enter AI context\n- Mandatory human security review for all AI-generated code before merging\n- Immediate credential rotation if an AI tool reads a secrets file\n- Annual AI security awareness training\n\n---\n\n## DOMAIN 6: AZURE INFRASTRUCTURE AND DEVSECOPS\n\n### Foundational — Key Vault, Private Endpoints, Network Isolation\n\n**Azure Key Vault — required Bicep configuration:**\n```bicep\nresource vault 'Microsoft.KeyVault\u002Fvaults@2023-07-01' = {\n  name: 'kv-${uniqueString(resourceGroup().id)}'\n  location: location\n  properties: {\n    sku: { family: 'A', name: 'premium' }\n    tenantId: tenant().tenantId\n    enableRbacAuthorization: true       \u002F\u002F Use RBAC, not legacy access policies\n    enableSoftDelete: true\n    softDeleteRetentionInDays: 90\n    enablePurgeProtection: true         \u002F\u002F Cannot be disabled once set — intentional\n    publicNetworkAccess: 'Disabled'\n    networkAcls: { defaultAction: 'Deny', bypass: 'AzureServices' }\n  }\n}\n```\n\n**Private Endpoints for Key Vault:**\n```bicep\nresource kvPrivateEndpoint 'Microsoft.Network\u002FprivateEndpoints@2023-05-01' = {\n  name: 'pe-keyvault'\n  location: location\n  properties: {\n    subnet: { id: dataSubnetId }\n    privateLinkServiceConnections: [{\n      name: 'kv-connection'\n      properties: {\n        privateLinkServiceId: vault.id\n        groupIds: ['vault']\n      }\n    }]\n  }\n}\n```\n\n**Required private DNS zones (always hardcode — never use suffixes expressions):**\n- Key Vault: `privatelink.vaultcore.azure.net`\n- Cosmos DB: `privatelink.documents.azure.com`\n- PostgreSQL: `privatelink.postgres.database.azure.com`\n- Databricks: `privatelink.azuredatabricks.net`\n- Storage: `privatelink.blob.core.windows.net`\n\n**Known Bicep bug:** `environment().suffixes.keyvaultDns` returns `.vault.azure.net` but the\ncorrect private DNS zone is `privatelink.vaultcore.azure.net` — always hardcode.\n\n**Note on Azure Blueprints:** Blueprints is deprecated (EOL July 2026). Replace with Deployment\nStacks: `az stack group create --name stack-myapp --deny-settings-mode denyWriteAndDelete`\n\n### Intermediate — Defender for Cloud, KQL Detection Queries, App Insights\n\n**Enable all Microsoft Defender for Cloud plans:**\n```bash\naz security pricing create --name CloudPosture --tier Standard\naz security pricing create --name VirtualMachines --tier Standard\naz security pricing create --name AppService --tier Standard\naz security pricing create --name KeyVaults --tier Standard\naz security pricing create --name CosmosDbs --tier Standard\naz security pricing create --name Containers --tier Standard\naz security pricing create --name Arm --tier Standard\n```\n\n**Application Insights — use connection string, not instrumentation key (deprecated):**\n```bicep\nresource appInsights 'Microsoft.Insights\u002Fcomponents@2020-02-02' = {\n  name: 'ai-webapi'\n  kind: 'web'\n  properties: {\n    Application_Type: 'web'\n    WorkspaceResourceId: logAnalyticsWorkspace.id\n    DisableLocalAuth: true  \u002F\u002F Force Managed Identity, not local auth keys\n  }\n}\n```\n\n**KQL detection queries for Log Analytics:**\n\n```kql\n\u002F\u002F Brute force detection — more than 10 failed logins per hour per user\u002FIP\nSigninLogs\n| where ResultType != \"0\"\n| summarize FailedCount = count() by UserPrincipalName, IPAddress, bin(TimeGenerated, 1h)\n| where FailedCount > 10\n\n\u002F\u002F Key Vault access anomalies — unauthorized or forbidden access attempts\nAzureDiagnostics\n| where ResourceProvider == \"MICROSOFT.KEYVAULT\"\n| where ResultSignature in (\"Forbidden\", \"Unauthorized\")\n| summarize Count = count() by CallerIPAddress, OperationName\n\n\u002F\u002F Sensitive role assignments — detect privilege escalation attempts\nAzureActivity\n| where OperationNameValue =~ \"MICROSOFT.AUTHORIZATION\u002FROLEASSIGNMENTS\u002FWRITE\"\n| project TimeGenerated, Caller, OperationNameValue, ResourceGroup\n\n\u002F\u002F API rate limit violations\nAppRequests\n| where ResultCode == \"429\"\n| summarize Count = count() by ClientIP, bin(TimeGenerated, 5m)\n| where Count > 50\n```\n\n### Advanced — Full DevSecOps Pipeline, Managed Identity Chain, AKS Workload Identity\n\n**Complete DevSecOps pipeline — all gates required, no soft-fails:**\n```yaml\n# .github\u002Fworkflows\u002Fdevsecops.yml\nname: DevSecOps Pipeline\non:\n  push: { branches: [main] }\n  pull_request: { branches: [main] }\npermissions:\n  security-events: write\n  contents: read\n\njobs:\n  sast-semgrep:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: returntocorp\u002Fsemgrep-action@v1\n        with:\n          config: 'p\u002Fsecurity-audit p\u002Fowasp-top-ten p\u002Fcsharp p\u002Ftypescript'\n          generateSarif: true\n      - uses: github\u002Fcodeql-action\u002Fupload-sarif@v3\n        with: { sarif_file: semgrep.sarif }\n        if: always()\n\n  sast-codeql:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: github\u002Fcodeql-action\u002Finit@v3\n        with: { languages: 'csharp, javascript' }\n      - uses: github\u002Fcodeql-action\u002Fanalyze@v3\n\n  sca-snyk:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: snyk\u002Factions\u002Fdotnet@master\n        env: { SNYK_TOKEN: '${{ secrets.SNYK_TOKEN }}' }\n        with: { args: '--severity-threshold=high' }\n\n  secrets-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with: { fetch-depth: 0 }  # full history required\n      - uses: gitleaks\u002Fgitleaks-action@v2\n        env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }\n\n  container-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - run: docker build -t myapp:${{ github.sha }} .\n      - uses: aquasecurity\u002Ftrivy-action@master\n        with:\n          image-ref: 'myapp:${{ github.sha }}'\n          severity: 'CRITICAL,HIGH'\n          exit-code: '1'\n\n  iac-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: bridgecrewio\u002Fcheckov-action@master\n        with: { directory: 'infra\u002F', framework: bicep, soft_fail: false }\n\n  deploy:\n    needs: [sast-semgrep, sast-codeql, sca-snyk, secrets-scan, container-scan, iac-scan]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    runs-on: ubuntu-latest\n    environment: production\n    steps:\n      - run: echo \"All security gates passed — deploying\"\n```\n\n**Zero-secrets Managed Identity chain — full Bicep:**\n```bicep\n\u002F\u002F User-assigned identity shared across services\nresource appIdentity 'Microsoft.ManagedIdentity\u002FuserAssignedIdentities@2023-01-31' = {\n  name: 'id-myapp'\n  location: location\n}\n\n\u002F\u002F Key Vault Secrets User (role ID: 4633458b-17de-408a-b874-0445c86b69e6)\nresource kvRole 'Microsoft.Authorization\u002FroleAssignments@2022-04-01' = {\n  scope: vault\n  name: guid(vault.id, appIdentity.id, '4633458b-17de-408a-b874-0445c86b69e6')\n  properties: {\n    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization\u002FroleDefinitions',\n      '4633458b-17de-408a-b874-0445c86b69e6')\n    principalId: appIdentity.properties.principalId\n    principalType: 'ServicePrincipal'\n  }\n}\n\n\u002F\u002F Cosmos DB Built-in Data Contributor\nresource cosmosRole 'Microsoft.DocumentDB\u002FdatabaseAccounts\u002FsqlRoleAssignments@2024-05-15' = {\n  parent: cosmosAccount\n  name: guid(cosmosAccount.id, appIdentity.properties.principalId, 'contributor')\n  properties: {\n    roleDefinitionId: '${cosmosAccount.id}\u002FsqlRoleDefinitions\u002F00000000-0000-0000-0000-000000000002'\n    principalId: appIdentity.properties.principalId\n    scope: cosmosAccount.id\n  }\n}\n\n\u002F\u002F Storage Blob Data Contributor (role ID: ba92f5b4-2d11-453d-a403-e96b0029c9fe)\nresource storageRole 'Microsoft.Authorization\u002FroleAssignments@2022-04-01' = {\n  scope: storageAccount\n  name: guid(storageAccount.id, appIdentity.id, 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')\n  properties: {\n    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization\u002FroleDefinitions',\n      'ba92f5b4-2d11-453d-a403-e96b0029c9fe')\n    principalId: appIdentity.properties.principalId\n    principalType: 'ServicePrincipal'\n  }\n}\n```\n\n**AKS Workload Identity** (Pod Identity is deprecated, EOL September 2025):\n\n```yaml\nspec:\n  securityContext:\n    runAsNonRoot: true\n    runAsUser: 1000\n    seccompProfile: { type: RuntimeDefault }\n  containers:\n  - name: api\n    securityContext:\n      allowPrivilegeEscalation: false\n      readOnlyRootFilesystem: true\n      capabilities: { drop: [ALL] }\n```\n\n---\n\n## TWELVE HIGHEST-IMPACT ACTIONS (IN PRIORITY ORDER)\n\n1. **Replace all connection-string-with-keys patterns with Managed Identity RBAC** — the single\n   biggest attack surface reduction across the entire stack.\n2. **Enforce Authorization Code + PKCE on all SPAs** while disabling implicit grant in app\n   registrations.\n3. **Deploy Private Endpoints** for every PaaS service (Key Vault, Cosmos DB, PostgreSQL,\n   Databricks, Storage).\n4. **Enable Microsoft Defender for Cloud** across all plans.\n5. **Implement the DevSecOps pipeline** with quality gates that block on HIGH\u002FCRITICAL findings.\n6. **Deploy enterprise-managed settings** for Claude Code and Cursor with file deny rules.\n7. **Add PostToolUse Semgrep hooks** to every repository's `.claude\u002Fsettings.json`.\n8. **Enable Key Vault RBAC, soft-delete, and purge protection** on every vault.\n9. **Implement PostgreSQL RLS** for multi-tenant data isolation.\n10. **Enable Unity Catalog** for all Databricks data governance with column masking on PII.\n11. **Wire Gitleaks** with full git history scan (`fetch-depth: 0`) on every PR.\n12. **Set `ClockSkew = TimeSpan.Zero`** and verify `UseAuthentication` precedes\n    `UseAuthorization` in every .NET API.\n\nThe maturity tiers are not sequential gates — they represent increasing depth. A team can\nimplement Foundational across all six domains in the first sprint, then progressively deepen\ninto Intermediate and Advanced tiers over subsequent quarters.\n\nZero-secrets architecture through Managed Identity is the foundation everything else builds upon.\nWithout it, Key Vault references, Private Endpoints, and RBAC assignments are incomplete controls.\n","# Enterprise Cybersecurity Implementation Guide\n\nProduction-ready, copy-paste security implementation for: Microsoft Azure, .NET 8 Web API,\nReact, Blazor WASM, CosmosDB, PostgreSQL, Databricks, Claude Code, Cursor IDE.\n\nThree-tier maturity model for each domain:\n- **Foundational** — get secure fast; correct flow selection and baseline controls\n- **Intermediate** — hardened for production; RBAC, rate limiting, resource authorization\n- **Advanced** — defense-in-depth; zero-secrets, network isolation, threat detection\n\n---\n\n## DOMAIN 1: IDENTITY AND AUTHENTICATION (ENTRA ID, JWT, OIDC)\n\n### Foundational — App Registrations and Correct Auth Flows\n\nCreate **separate Entra ID app registrations** for the API and each frontend (React SPA, Blazor\nWASM). Use \"Accounts in this organizational directory only\" for single-tenant internal apps.\n\n```bash\n# Create API app registration\naz ad app create --display-name \"myapp-api\" --sign-in-audience \"AzureADMyOrg\" \\\n  --identifier-uris \"api:\u002F\u002Fmyapp-api\"\n# Create SPA app registration\naz ad app create --display-name \"myapp-spa\" --sign-in-audience \"AzureADMyOrg\"\n# Create service principal (Enterprise Application)\naz ad sp create --id \u003CAPP_ID>\n```\n\n**Authentication flow selection is non-negotiable.** Wrong flows break security.\n\n| Scenario | Required Flow | Never Use |\n|---|---|---|\n| React SPA user login | Authorization Code + PKCE | Implicit Grant (deprecated, disabled) |\n| Blazor WASM user login | Authorization Code + PKCE | Implicit Grant |\n| Service-to-service \u002F daemons | Client Credentials | Shared secrets in config |\n| API calling downstream API for user | On-Behalf-Of (OBO) | Storing user tokens in service |\n| CLI tooling | Device Code | Embedded credentials |\n\n**.NET 8 Web API — Microsoft.Identity.Web** (NuGet: `Microsoft.Identity.Web` v3.x\u002Fv4.x):\n\n```csharp\n\u002F\u002F Program.cs\nusing Microsoft.Identity.Web;\nbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(\"AzureAd\"));\nbuilder.Services.AddAuthorization();\n```\n\n```json\n\u002F\u002F appsettings.json — non-secret values only; ClientSecret must NEVER appear here\n{\n  \"AzureAd\": {\n    \"Instance\": \"https:\u002F\u002Flogin.microsoftonline.com\u002F\",\n    \"TenantId\": \"your-tenant-id\",\n    \"ClientId\": \"your-api-client-id\",\n    \"Audience\": \"api:\u002F\u002Fyour-api-client-id\"\n  }\n}\n```\n\n**React with MSAL.js** (npm: `@azure\u002Fmsal-browser` v3.x, `@azure\u002Fmsal-react` v2.x):\n\n```typescript\n\u002F\u002F authConfig.ts\nexport const msalConfig: Configuration = {\n  auth: {\n    clientId: \"your-spa-client-id\",\n    authority: \"https:\u002F\u002Flogin.microsoftonline.com\u002Fyour-tenant-id\",\n    redirectUri: \"\u002F\",\n  },\n  cache: {\n    cacheLocation: \"sessionStorage\", \u002F\u002F NEVER localStorage — XSS-vulnerable\n    storeAuthStateInCookie: false,\n  },\n};\nexport const apiScopes = { scopes: [\"api:\u002F\u002Fyour-api-client-id\u002FApi.Read\"] };\n```\n\n```tsx\n\u002F\u002F index.tsx — Instantiate OUTSIDE component tree (never inside a component)\nconst msalInstance = new PublicClientApplication(msalConfig);\nawait msalInstance.initialize();\nawait msalInstance.handleRedirectPromise();\nconst accounts = msalInstance.getAllAccounts();\nif (accounts.length > 0) msalInstance.setActiveAccount(accounts[0]);\nroot.render(\u003CMsalProvider instance={msalInstance}>\u003CApp \u002F>\u003C\u002FMsalProvider>);\n```\n\n**Blazor WASM** (NuGet: `Microsoft.Authentication.WebAssembly.Msal` v8.x):\n\n```csharp\n\u002F\u002F Program.cs\nbuilder.Services.AddMsalAuthentication(options =>\n{\n    builder.Configuration.Bind(\"AzureAd\", options.ProviderOptions.Authentication);\n    options.ProviderOptions.DefaultAccessTokenScopes.Add(\n        \"api:\u002F\u002Fyour-api-client-id\u002FApi.Read\");\n    options.ProviderOptions.LoginMode = \"redirect\";\n});\n```\n\n**Critical anti-patterns to avoid:**\n- Storing tokens in `localStorage` (XSS-vulnerable)\n- Enabling implicit grant checkboxes in app registration\n- Sharing a single app registration across environments\n- Hardcoding client secrets in source code\n- Creating `PublicClientApplication` inside React components (re-created on every render)\n\n### Intermediate — JWT Validation, App Roles, Token Lifecycle\n\nJWT validation in .NET must enforce issuer, audience, lifetime, and signing key — all handled\nautomatically by `AddMicrosoftIdentityWebApi`. If configuring manually: `ClockSkew = TimeSpan.Zero`\n(the 5-minute default is too generous). Never hardcode signing keys — Microsoft rotates them via\nthe JWKS endpoint.\n\n**App Roles in manifest:**\n```json\n{\n  \"appRoles\": [\n    {\n      \"allowedMemberTypes\": [\"User\"],\n      \"displayName\": \"Admin\",\n      \"id\": \"unique-guid-here\",\n      \"isEnabled\": true,\n      \"value\": \"Admin\"\n    }\n  ]\n}\n```\n\n**Map App Roles to authorization policies:**\n```csharp\nbuilder.Services.AddAuthorizationBuilder()\n    .AddPolicy(\"AdminOnly\", policy => policy.RequireRole(\"Admin\"))\n    .AddPolicy(\"ReaderOrAdmin\", policy => policy.RequireRole(\"Reader\", \"Admin\"))\n    .AddPolicy(\"DepartmentFinance\", policy =>\n        policy.RequireClaim(\"department\", \"finance\"));\n```\n\n**Use App Roles over Group Claims.** Groups create an overage problem: users with more than 200\ngroups cause Entra ID to emit a `_claim_sources` reference instead of the groups array, requiring\na Graph API call. App Roles are portable and don't have this limitation.\n\n**Token storage in SPAs:** MSAL.js keeps tokens in-memory by default. `sessionStorage` is the\nmost secure persistent option (per-tab isolation, auto-clears on tab close). **Refresh token\nrotation is automatic** — SPAs receive one-time-use refresh tokens that rotate on each use.\nReplaying a used token revokes the entire token family.\n\n### Advanced — Managed Identities, Conditional Access, Zero-Secrets\n\n**Managed Identities eliminate all secrets from your .NET API configuration.** Core NuGet:\n`Azure.Identity` (v1.13.x).\n\n```csharp\n\u002F\u002F Production-optimized credential selection\nvar credential = builder.Environment.IsDevelopment()\n    ? new DefaultAzureCredential()\n    : new ManagedIdentityCredential();  \u002F\u002F Faster startup — skips environment probing\n\n\u002F\u002F CosmosDB with Managed Identity\nvar cosmosClient = new CosmosClient(\"https:\u002F\u002Fyour-account.documents.azure.com:443\u002F\", credential);\n\n\u002F\u002F PostgreSQL with periodic token refresh (tokens expire in 4-24 hours)\nvar dataSourceBuilder = new NpgsqlDataSourceBuilder(connStringWithoutPassword);\ndataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>\n{\n    var token = await credential.GetTokenAsync(new TokenRequestContext(\n        new[] { \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\" }), ct);\n    return token.Token;\n}, TimeSpan.FromHours(4), TimeSpan.FromSeconds(10));\n```\n\n```bash\n# Assign Cosmos DB Built-in Data Contributor role\naz cosmosdb sql role assignment create \\\n  --account-name myCosmosAccount --resource-group myRG \\\n  --role-definition-id \"00000000-0000-0000-0000-000000000002\" \\\n  --principal-id \"\u003Cmanaged-identity-object-id>\" --scope \"\u002F\"\n```\n\n**Conditional Access policies to deploy:**\n1. Require MFA for all users (exclude break-glass accounts)\n2. Block legacy authentication protocols (SMTP, IMAP, POP3 bypass Conditional Access)\n3. Require compliant devices via Intune\n4. Require MFA from non-trusted network locations\n\nAlways test with Report-only mode and the What If tool before enforcement.\n\n---\n\n## DOMAIN 2: API SECURITY (.NET 8 WEB API)\n\n### Foundational — Middleware Pipeline ORDER (Critical), Validation, CORS\n\n**Middleware ordering is the single most common security misconfiguration in .NET APIs.**\n`UseAuthentication` must precede `UseAuthorization` — reversing them causes authentication to\nsilently fail and authorization to pass for all requests.\n\n```csharp\nvar app = builder.Build();\n\nif (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }\nelse { app.UseHsts(); }\n\n\u002F\u002F Security headers — first substantial middleware\napp.Use(async (context, next) => {\n    context.Response.Headers[\"X-Content-Type-Options\"] = \"nosniff\";\n    context.Response.Headers[\"X-Frame-Options\"] = \"DENY\";\n    context.Response.Headers[\"Referrer-Policy\"] = \"strict-origin-when-cross-origin\";\n    context.Response.Headers[\"Permissions-Policy\"] =\n        \"accelerometer=(), camera=(), geolocation=(), microphone=()\";\n    await next();\n});\n\napp.UseHttpsRedirection();\napp.UseSerilogRequestLogging();\napp.UseRouting();\napp.UseRateLimiter();        \u002F\u002F Rate limit BEFORE auth to block brute force\napp.UseCors(\"SpaPolicy\");\napp.UseAuthentication();    \u002F\u002F WHO are you?\napp.UseAuthorization();     \u002F\u002F WHAT can you do?\napp.MapControllers();\n```\n\nRemove Kestrel Server header: `builder.WebHost.ConfigureKestrel(o => o.AddServerHeader = false);`\n\n**Input validation** with FluentValidation (NuGet: `FluentValidation` v11.x +\n`FluentValidation.DependencyInjectionExtensions`). Note: `FluentValidation.AspNetCore` is\ndeprecated — use the base package:\n\n```csharp\npublic class CreateUserRequestValidator : AbstractValidator\u003CCreateUserRequest>\n{\n    public CreateUserRequestValidator()\n    {\n        RuleFor(x => x.Name).NotEmpty().MaximumLength(100)\n            .Matches(@\"^[a-zA-Z\\s\\-']+$\").WithMessage(\"Name contains invalid characters.\");\n        RuleFor(x => x.Email).NotEmpty().EmailAddress();\n        RuleFor(x => x.Age).InclusiveBetween(18, 120);\n    }\n}\n\u002F\u002F Program.cs\nbuilder.Services.AddValidatorsFromAssemblyContaining\u003CCreateUserRequestValidator>();\n```\n\n**CORS — exact allowed origins only:**\n```csharp\nvar allowedOrigins = builder.Configuration.GetSection(\"Cors:AllowedOrigins\").Get\u003Cstring[]>()!;\nbuilder.Services.AddCors(options =>\n{\n    options.AddPolicy(\"SpaPolicy\", policy => policy\n        .WithOrigins(allowedOrigins)  \u002F\u002F NEVER AllowAnyOrigin() in production\n        .AllowAnyHeader().AllowAnyMethod().AllowCredentials());\n});\n```\n\nTrailing slash in origin URLs (`\"https:\u002F\u002Fapp.example.com\u002F\"`) causes silent comparison failure.\nOmit trailing slashes.\n\n### Intermediate — Rate Limiting, BOLA via IAuthorizationHandler, Logging\n\n**Built-in rate limiting in .NET 8** (no extra NuGet needed):\n\n```csharp\nbuilder.Services.AddRateLimiter(options =>\n{\n    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;\n    options.AddTokenBucketLimiter(\"Api\", opt =>\n    {\n        opt.TokenLimit = 100;\n        opt.ReplenishmentPeriod = TimeSpan.FromSeconds(10);\n        opt.TokensPerPeriod = 20;\n        opt.QueueLimit = 5;\n    });\n    \u002F\u002F Per-user rate limiting (falls back to IP for unauthenticated)\n    options.GlobalLimiter = PartitionedRateLimiter.Create\u003CHttpContext, string>(\n        httpContext => RateLimitPartition.GetFixedWindowLimiter(\n            partitionKey: httpContext.User.Identity?.Name\n                ?? httpContext.Connection.RemoteIpAddress?.ToString() ?? \"anon\",\n            factory: _ => new FixedWindowRateLimiterOptions\n            {\n                PermitLimit = 60, Window = TimeSpan.FromMinutes(1)\n            }));\n});\n```\n\nApply with `[EnableRateLimiting(\"Api\")]` on controllers or `.RequireRateLimiting(\"Api\")` on\nminimal API routes.\n\n**BOLA prevention via IAuthorizationHandler** (OWASP API1 — Broken Object Level Authorization):\n\n```csharp\npublic class DocumentAuthorizationHandler\n    : AuthorizationHandler\u003CSameAuthorRequirement, Document>\n{\n    protected override Task HandleRequirementAsync(\n        AuthorizationHandlerContext context,\n        SameAuthorRequirement requirement, Document resource)\n    {\n        if (context.User.Identity?.Name == resource.AuthorId)\n            context.Succeed(requirement);\n        \u002F\u002F Never call context.Succeed for unauthorized access — implicit failure is correct\n        return Task.CompletedTask;\n    }\n}\n```\n\n**Serilog with Application Insights:**\n```csharp\nbuilder.Host.UseSerilog((context, services, config) => config\n    .ReadFrom.Configuration(context.Configuration)\n    .Enrich.FromLogContext()\n    .WriteTo.Console()\n    .WriteTo.ApplicationInsights(\n        services.GetRequiredService\u003CTelemetryConfiguration>(),\n        TelemetryConverter.Traces));\n```\n\nNever log passwords, JWTs, API keys, connection strings, credit card numbers, or PII. Always log\nfailed auth, authorization denials, and suspicious input with structured fields.\n\n### Advanced — Key Vault Config, Swagger Lockdown, Minimal API Security\n\n**Zero-secrets configuration with Azure Key Vault:**\n```csharp\nvar kvUri = new Uri($\"https:\u002F\u002F{builder.Configuration[\"KeyVaultName\"]}.vault.azure.net\u002F\");\nbuilder.Configuration.AddAzureKeyVault(kvUri, new DefaultAzureCredential(),\n    new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(5) });\n```\n\nSecrets auto-refresh without restarts when using `IOptionsMonitor\u003CT>`.\n\n**Swagger must never be exposed in production:**\n```csharp\nif (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }\n\u002F\u002F For Swagger JWT auth in development — use Http type, not ApiKey\noptions.AddSecurityDefinition(\"Bearer\", new OpenApiSecurityScheme\n{\n    Type = SecuritySchemeType.Http,\n    Scheme = \"Bearer\",\n    BearerFormat = \"JWT\"\n});\n```\n\n**Minimal APIs — route group authorization:**\n```csharp\nvar admin = app.MapGroup(\"\u002Fapi\u002Fadmin\").RequireAuthorization(\"AdminOnly\");\nadmin.MapGet(\"\u002Fusers\", () => Results.Ok());\nadmin.MapDelete(\"\u002Fusers\u002F{id}\", (int id) => Results.NoContent());\n\u002F\u002F Explicit anonymous — document why\napp.MapGet(\"\u002Fapi\u002Fhealth\", () => Results.Ok(\"healthy\")).AllowAnonymous();\n```\n\n---\n\n## DOMAIN 3: FRONTEND SECURITY (REACT AND BLAZOR WASM)\n\n### Foundational — Token Management and XSS Prevention\n\n**Never store tokens in `localStorage`** — any XSS vulnerability enables trivial theft via\n`localStorage.getItem('token')`. Use `sessionStorage` (per-tab isolation, auto-clears on close).\n\n**Axios interceptor for automatic token attachment and silent refresh:**\n```typescript\n\u002F\u002F apiClient.ts\nimport axios from 'axios';\nimport { msalInstance } from '.\u002FauthConfig';\nimport { InteractionRequiredAuthError } from '@azure\u002Fmsal-browser';\n\nconst apiClient = axios.create({ baseURL: 'https:\u002F\u002Fapi.example.com' });\n\napiClient.interceptors.request.use(async (config) => {\n  const account = msalInstance.getActiveAccount();\n  if (!account) throw new Error('No active account');\n  try {\n    const response = await msalInstance.acquireTokenSilent({\n      scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'], account,\n    });\n    config.headers.Authorization = `Bearer ${response.accessToken}`;\n  } catch (error) {\n    if (error instanceof InteractionRequiredAuthError) {\n      await msalInstance.acquireTokenRedirect({\n        scopes: ['api:\u002F\u002Fyour-api-client-id\u002F.default'],\n      });\n    }\n  }\n  return config;\n});\n```\n\n**Four vectors that bypass React's auto-escaping protection:**\n1. `dangerouslySetInnerHTML` without sanitization\n2. `href` with `javascript:` protocol\n3. Direct DOM manipulation via `ref.current.innerHTML`\n4. `eval()` with user input\n\n**DOMPurify SafeHTML wrapper** (npm: `dompurify`, `@types\u002Fdompurify`):\n```tsx\nimport DOMPurify from 'dompurify';\nexport function SafeHTML({ html }: { html: string }) {\n  const sanitized = DOMPurify.sanitize(html, {\n    ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a'],\n    FORBID_TAGS: ['script', 'style', 'iframe'],\n    FORBID_ATTR: ['onerror', 'onload', 'onclick'],\n  });\n  return \u003Cdiv dangerouslySetInnerHTML={{ __html: sanitized }} \u002F>;\n}\n```\n\n### Intermediate — Blazor WASM Constraints and Protected Routes\n\n**Blazor WASM fundamental security constraint:** Everything runs client-side. All .NET assemblies\nare downloadable and decompilable with ILSpy. All `[Authorize]` attributes and `AuthorizeView`\ncomponents are cosmetic — **the server API must re-validate every request**. Never put secrets,\nsensitive business logic, or intellectual property in Blazor WASM code.\n\n**Blazor WASM auth routing:**\n```razor\n\u003C!-- App.razor -->\n\u003CCascadingAuthenticationState>\n    \u003CRouter AppAssembly=\"@typeof(Program).Assembly\">\n        \u003CFound Context=\"routeData\">\n            \u003CAuthorizeRouteView RouteData=\"@routeData\" DefaultLayout=\"@typeof(MainLayout)\">\n                \u003CNotAuthorized>\n                    @if (context.User.Identity?.IsAuthenticated != true)\n                    { \u003CRedirectToLogin \u002F> }\n                    else\n                    { \u003Cp>You are not authorized.\u003C\u002Fp> }\n                \u003C\u002FNotAuthorized>\n            \u003C\u002FAuthorizeRouteView>\n        \u003C\u002FFound>\n    \u003C\u002FRouter>\n\u003C\u002FCascadingAuthenticationState>\n```\n\n**React protected route with role checking:**\n```tsx\nfunction ProtectedRoute({ allowedRoles }: { allowedRoles?: string[] }) {\n  const isAuthenticated = useIsAuthenticated();\n  const { accounts } = useMsal();\n  const location = useLocation();\n\n  if (!isAuthenticated)\n    return \u003CNavigate to=\"\u002Flogin\" state={{ from: location }} replace \u002F>;\n  if (allowedRoles?.length) {\n    const userRoles = (accounts[0]?.idTokenClaims as any)?.roles ?? [];\n    if (!allowedRoles.some(role => userRoles.includes(role)))\n      return \u003CNavigate to=\"\u002Funauthorized\" replace \u002F>;\n  }\n  return \u003COutlet \u002F>;\n}\n```\n\nBoth React and Blazor role-based UI rendering are UX features only. The API `[Authorize]` is the\nreal security boundary.\n\n### Advanced — CSP Headers, Dependency Security, SRI\n\n**Content Security Policy for React\u002FVite:**\n```typescript\n\u002F\u002F vite.config.ts\nexport default defineConfig({\n  build: { assetsInlineLimit: 0 }, \u002F\u002F Prevent inline scripts that bypass CSP\n  server: {\n    headers: {\n      'Content-Security-Policy': [\n        \"default-src 'self'\",\n        \"script-src 'self'\",\n        \"connect-src 'self' https:\u002F\u002Flogin.microsoftonline.com https:\u002F\u002Fapi.example.com\",\n        \"img-src 'self' data: https:\",\n        \"frame-ancestors 'none'\",\n      ].join('; '),\n    },\n  },\n});\n```\n\n**Production CSP (served by .NET backend):**\n```\ndefault-src 'self';\nscript-src 'self' 'nonce-{SERVER_GENERATED}' 'strict-dynamic';\nstyle-src 'self' 'nonce-{SERVER_GENERATED}';\nconnect-src 'self' https:\u002F\u002Flogin.microsoftonline.com https:\u002F\u002Fgraph.microsoft.com;\nframe-ancestors 'none';\nupgrade-insecure-requests;\n```\n\n**Dependency security automation:**\n```xml\n\u003C!-- .csproj — NuGet audit on every build -->\n\u003CPropertyGroup>\n    \u003CNuGetAudit>true\u003C\u002FNuGetAudit>\n    \u003CNuGetAuditMode>all\u003C\u002FNuGetAuditMode>\n    \u003CNuGetAuditLevel>low\u003C\u002FNuGetAuditLevel>\n    \u003CTreatWarningsAsErrors>true\u003C\u002FTreatWarningsAsErrors>\n\u003C\u002FPropertyGroup>\n```\n\n```yaml\n# .github\u002Fdependabot.yml\nversion: 2\nupdates:\n  - package-ecosystem: \"npm\"\n    directory: \"\u002Ffrontend\"\n    schedule: { interval: \"weekly\" }\n  - package-ecosystem: \"nuget\"\n    directory: \"\u002Fbackend\"\n    schedule: { interval: \"weekly\" }\n  - package-ecosystem: \"pip\"\n    directory: \"\u002Fdatabricks\"\n    schedule: { interval: \"weekly\" }\n```\n\n---\n\n## DOMAIN 4: DATA LAYER SECURITY (COSMOSDB, POSTGRESQL, DATABRICKS)\n\n### Foundational — Managed Identity Access, Encryption Defaults\n\nAll three platforms encrypt data at rest with AES-256 by default and enforce TLS 1.2+ in\ntransit. The foundational security step is eliminating connection strings with keys.\n\n**CosmosDB — assign Built-in Data Contributor role:**\n```bash\naz cosmosdb sql role assignment create \\\n  --account-name myCosmosAccount --resource-group myRG \\\n  --role-definition-id \"00000000-0000-0000-0000-000000000002\" \\\n  --principal-id \"\u003Cmanaged-identity-principal-id>\" --scope \"\u002F\"\n```\n\n```csharp\nvar cosmosClient = new CosmosClient(\n    \"https:\u002F\u002Fyour-account.documents.azure.com:443\u002F\",\n    new DefaultAzureCredential(),\n    new CosmosClientOptions { ConnectionMode = ConnectionMode.Direct });\n```\n\n**Critical pitfall:** Azure control-plane roles like \"Cosmos DB Account Contributor\" do NOT\ngrant data-plane access. You must assign Cosmos DB's native data-plane RBAC roles separately.\nAlways include `readMetadata` permission or queries fail with 403.\n\n**PostgreSQL — enable Entra ID auth, create Managed Identity principal:**\n```sql\n-- Run as Entra admin\nSELECT * FROM pgaadauth_create_principal('\u003Cidentity-name>', false, false);\nGRANT ALL ON ALL TABLES IN SCHEMA public TO \"\u003Cidentity-name>\";\n```\n\n**Databricks — Unity Catalog storage credentials with Managed Identity:**\n```sql\nCREATE STORAGE CREDENTIAL my_credential\nWITH (AZURE_MANAGED_IDENTITY = '\u003Cmanaged-identity-resource-id>');\nCREATE EXTERNAL LOCATION my_location\nURL 'abfss:\u002F\u002F\u003Ccontainer>@\u003Cstorage-account>.dfs.core.windows.net\u002F\u003Cpath>'\nWITH (STORAGE CREDENTIAL my_credential);\n```\n\nDatabricks notebook secrets: `dbutils.secrets.get(scope=\"my-kv-scope\", key=\"db-password\")`.\nSecret values are redacted in notebook output. Never hardcode credentials.\n\n### Intermediate — PostgreSQL RLS Tenant Isolation, CosmosDB Partition Keys, Audit Logging\n\n**PostgreSQL Row-Level Security — database-enforced multi-tenant isolation:**\n```sql\nCREATE TABLE tenant_data (\n    id SERIAL PRIMARY KEY,\n    tenant_id UUID NOT NULL,\n    data TEXT\n);\nALTER TABLE tenant_data ENABLE ROW LEVEL SECURITY;\nALTER TABLE tenant_data FORCE ROW LEVEL SECURITY; -- Apply even to table owners\n\nCREATE FUNCTION current_tenant_id() RETURNS UUID AS $$\nBEGIN\n    RETURN NULLIF(current_setting('app.tenant_id', true), '')::UUID;\nEND;\n$$ LANGUAGE plpgsql STABLE;\n\nCREATE POLICY tenant_isolation ON tenant_data\n    FOR ALL USING (tenant_id = current_tenant_id());\n```\n\nSet tenant context from .NET middleware before each request's DB operations:\n```csharp\nawait using var cmd = conn.CreateCommand();\ncmd.CommandText = \"SET LOCAL app.tenant_id = @tenantId\";\ncmd.Parameters.AddWithValue(\"tenantId\", tenantIdFromJwt);\nawait cmd.ExecuteNonQueryAsync();\n```\n\n**RLS is deny-by-default:** enabling it without policies blocks ALL access. Always index\n`tenant_id` columns for performance.\n\n**CosmosDB multi-tenant isolation** — hierarchical partition keys for large tenants:\n```csharp\nContainerProperties properties = new(\n    id: \"events\",\n    partitionKeyPaths: new List\u003Cstring> { \"\u002FtenantId\", \"\u002FuserId\", \"\u002FsessionId\" });\n```\n\nFor many small tenants, use `tenantId` as the partition key (most cost-effective). For tenants\nexceeding 20GB, use Hierarchical Partition Keys.\n\n**pgAudit for PostgreSQL audit logging:**\n```bash\naz postgres flexible-server parameter set \\\n  --server-name myserver --resource-group myRG \\\n  --name pgaudit.log --value \"WRITE,DDL\"\n```\n\nQuery audit logs: `AzureDiagnostics | where Message contains \"AUDIT:\" | where TimeGenerated > ago(1d)`\n\n### Advanced — Customer-Managed Keys, Unity Catalog Column Security, Purview\n\n**Disable key-based CosmosDB auth entirely to enforce RBAC:**\n```bash\naz cosmosdb update --name myaccount --resource-group myRG --disable-local-auth true\n```\n\n**Databricks Unity Catalog column-level security via masking functions:**\n```sql\nCREATE FUNCTION mask_email(email STRING) RETURNS STRING\nRETURN CASE\n  WHEN IS_ACCOUNT_GROUP_MEMBER('pii-readers') THEN email\n  ELSE CONCAT('***', SUBSTRING(email, LOCATE('@', email)))\nEND;\n\nALTER TABLE customers ALTER COLUMN email SET MASK mask_email;\n```\n\n**Row filters:**\n```sql\nALTER TABLE sales SET ROW FILTER filter_fn ON (region);\n```\n\nUse Unity Catalog for all data governance in Databricks. Never access data directly via storage\naccount keys — use service principals with Unity Catalog RBAC.\n\n**Microsoft Purview** for cross-platform data classification: register CosmosDB (schema from\nfirst 10 docs per container), PostgreSQL, and Unity Catalog (full metadata + lineage) in Purview\nData Map. Configure scanning schedules and apply sensitivity labels.\n\n---\n\n## DOMAIN 5: AI TOOL SECURITY (CLAUDE CODE AND CURSOR)\n\n### Foundational — The Threat Model Every Team Must Understand\n\nAI coding tools introduce five systemic risks:\n1. **Data exfiltration** — code sent to external APIs may include secrets\n2. **Prompt injection** via malicious context (doc strings, comments, file names)\n3. **Model hallucination** of insecure patterns\n4. **Intellectual property exposure**\n5. **Compliance gaps** — 63% of breached organizations lacked AI tool governance\n\nResearch from Apiiro (September 2025): AI-generated code introduced **10,000+ new security\nfindings per month** — a 10x increase from December 2024. Veracode found only **55% of\nAI-generated code was secure** across 100+ LLMs.\n\n**Most common security anti-patterns AI tools generate:**\n- **CWE-798 Hardcoded credentials:** `var connString = \"Server=prod;Password=abc123\";`\n- **CWE-89 SQL injection:** `FromSqlRaw($\"SELECT * FROM Users WHERE Id = {userId}\")`\n- **CWE-862 Missing authorization:** Controller actions without `[Authorize]`\n- **CWE-79 XSS in React:** `dangerouslySetInnerHTML={{ __html: userData.bio }}`\n- **CWE-502 Insecure deserialization:** `TypeNameHandling = TypeNameHandling.All`\n- **CWE-327 Weak cryptography:** `MD5.Create()` for password hashing\n\nTreat all AI-generated code as an untrusted pull request from a junior developer.\n\n### Intermediate — Claude Code and Cursor Enterprise Configuration\n\n**Claude Code settings hierarchy** (highest to lowest precedence):\n1. Enterprise `managed-settings.json` (cannot be overridden by users)\n2. CLI arguments\n3. `.claude\u002Fsettings.local.json`\n4. `.claude\u002Fsettings.json` (committed to repository)\n5. User settings\n\n**Enterprise-managed configuration — deploy this to every developer machine:**\n```json\n\u002F\u002F Linux:   \u002Fetc\u002Fclaude-code\u002Fmanaged-settings.json\n\u002F\u002F macOS:   \u002FLibrary\u002FApplication Support\u002FClaudeCode\u002Fmanaged-settings.json\n\u002F\u002F Windows: %ALLUSERSPROFILE%\\ClaudeCode\\managed-settings.json\n{\n  \"permissions\": {\n    \"deny\": [\n      \"Read(.\u002F.env)\",\n      \"Read(.\u002F.env.*)\",\n      \"Read(.\u002Fsecrets\u002F**)\",\n      \"Read(.\u002Fappsettings.*.json)\",\n      \"Read(~\u002F.aws\u002F**)\",\n      \"Read(~\u002F.ssh\u002F**)\",\n      \"Read(~\u002F.azure\u002F**)\",\n      \"Bash(curl:*)\",\n      \"Bash(wget:*)\",\n      \"Bash(nc:*)\"\n    ],\n    \"disableBypassPermissionsMode\": \"disable\",\n    \"defaultMode\": \"ask\"\n  },\n  \"sandbox\": { \"enabled\": true, \"allowUnsandboxedCommands\": false },\n  \"enableAllProjectMcpServers\": false,\n  \"forceLoginMethod\": \"console\",\n  \"forceLoginOrgUUID\": \"YOUR-ORG-UUID\"\n}\n```\n\n**Cursor privacy and file exclusions:**\n- Enable Privacy Mode: Settings → General → Privacy Mode (enforces zero data retention)\n- Create `.cursorignore` in every repository:\n```\n.env\n.env.*\n*.pem\n*.key\n*.pfx\nappsettings.Production.json\nappsettings.Staging.json\nsecrets\u002F\n.azure\u002F\n.aws\u002F\n.ssh\u002F\nlocal.settings.json\nlaunchSettings.json\n```\n\n**Known limitation:** `.cursorignore` blocks the agent from reading files but does not prevent\nit from suggesting code that references those files by name. CVE-2025-59944 demonstrated a\nfilename case bypass on Windows\u002FmacOS. Do not rely on `.cursorignore` as the sole control.\n\n**Certifications:** Claude Code has SOC 2 Type II, ISO 27001:2022, and ISO\u002FIEC 42001:2023.\nCursor has SOC 2 Type II. Both offer zero-retention agreements for enterprise\u002Fteam plans. Code\nis **not used for training** under commercial terms.\n\n### Advanced — PostToolUse Semgrep Hook, Security-First Prompting, Org Policy\n\n**PostToolUse Semgrep hook — wire this in every project's `.claude\u002Fsettings.json`:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": {\n      \"Edit\": \"semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten --quiet ${CLAUDE_FILE_PATH}\"\n    }\n  }\n}\n```\n\nThis runs Semgrep on every file edit automatically. If Semgrep finds an issue, fix it before\nproceeding — never move to the next step with an open finding.\n\n**Claude Code Security Review GitHub Action:**\n```yaml\n- uses: anthropics\u002Fclaude-code-security-review@main\n  with:\n    comment-pr: true\n    claude-api-key: ${{ secrets.CLAUDE_API_KEY }}\n```\n\n**Security-first prompting template:**\n```\nCreate a .NET 8 Web API endpoint for user registration.\nTHREAT MODEL: Public-facing, potential credential stuffing.\nSECURITY REQUIREMENTS:\n  - Authentication: [Authorize(Policy = \"WriterOrAdmin\")]\n  - Authorization: no user-owned data, standard RBAC\n  - Input validation: FluentValidation with email, name, password complexity\n  - Rate limiting: 5 requests\u002Fmin per IP\n  - Logging: log attempt with userId, never log password\n  - Error messages: generic (no account enumeration)\n```\n\n**Organizational AI security policy elements:**\n- Approved tool list (e.g., Claude Code + Cursor only, with enterprise configs deployed)\n- Data classification rules: PHI\u002FPCI\u002Fcredentials never enter AI context\n- Mandatory human security review for all AI-generated code before merging\n- Immediate credential rotation if an AI tool reads a secrets file\n- Annual AI security awareness training\n\n---\n\n## DOMAIN 6: AZURE INFRASTRUCTURE AND DEVSECOPS\n\n### Foundational — Key Vault, Private Endpoints, Network Isolation\n\n**Azure Key Vault — required Bicep configuration:**\n```bicep\nresource vault 'Microsoft.KeyVault\u002Fvaults@2023-07-01' = {\n  name: 'kv-${uniqueString(resourceGroup().id)}'\n  location: location\n  properties: {\n    sku: { family: 'A', name: 'premium' }\n    tenantId: tenant().tenantId\n    enableRbacAuthorization: true       \u002F\u002F Use RBAC, not legacy access policies\n    enableSoftDelete: true\n    softDeleteRetentionInDays: 90\n    enablePurgeProtection: true         \u002F\u002F Cannot be disabled once set — intentional\n    publicNetworkAccess: 'Disabled'\n    networkAcls: { defaultAction: 'Deny', bypass: 'AzureServices' }\n  }\n}\n```\n\n**Private Endpoints for Key Vault:**\n```bicep\nresource kvPrivateEndpoint 'Microsoft.Network\u002FprivateEndpoints@2023-05-01' = {\n  name: 'pe-keyvault'\n  location: location\n  properties: {\n    subnet: { id: dataSubnetId }\n    privateLinkServiceConnections: [{\n      name: 'kv-connection'\n      properties: {\n        privateLinkServiceId: vault.id\n        groupIds: ['vault']\n      }\n    }]\n  }\n}\n```\n\n**Required private DNS zones (always hardcode — never use suffixes expressions):**\n- Key Vault: `privatelink.vaultcore.azure.net`\n- Cosmos DB: `privatelink.documents.azure.com`\n- PostgreSQL: `privatelink.postgres.database.azure.com`\n- Databricks: `privatelink.azuredatabricks.net`\n- Storage: `privatelink.blob.core.windows.net`\n\n**Known Bicep bug:** `environment().suffixes.keyvaultDns` returns `.vault.azure.net` but the\ncorrect private DNS zone is `privatelink.vaultcore.azure.net` — always hardcode.\n\n**Note on Azure Blueprints:** Blueprints is deprecated (EOL July 2026). Replace with Deployment\nStacks: `az stack group create --name stack-myapp --deny-settings-mode denyWriteAndDelete`\n\n### Intermediate — Defender for Cloud, KQL Detection Queries, App Insights\n\n**Enable all Microsoft Defender for Cloud plans:**\n```bash\naz security pricing create --name CloudPosture --tier Standard\naz security pricing create --name VirtualMachines --tier Standard\naz security pricing create --name AppService --tier Standard\naz security pricing create --name KeyVaults --tier Standard\naz security pricing create --name CosmosDbs --tier Standard\naz security pricing create --name Containers --tier Standard\naz security pricing create --name Arm --tier Standard\n```\n\n**Application Insights — use connection string, not instrumentation key (deprecated):**\n```bicep\nresource appInsights 'Microsoft.Insights\u002Fcomponents@2020-02-02' = {\n  name: 'ai-webapi'\n  kind: 'web'\n  properties: {\n    Application_Type: 'web'\n    WorkspaceResourceId: logAnalyticsWorkspace.id\n    DisableLocalAuth: true  \u002F\u002F Force Managed Identity, not local auth keys\n  }\n}\n```\n\n**KQL detection queries for Log Analytics:**\n\n```kql\n\u002F\u002F Brute force detection — more than 10 failed logins per hour per user\u002FIP\nSigninLogs\n| where ResultType != \"0\"\n| summarize FailedCount = count() by UserPrincipalName, IPAddress, bin(TimeGenerated, 1h)\n| where FailedCount > 10\n\n\u002F\u002F Key Vault access anomalies — unauthorized or forbidden access attempts\nAzureDiagnostics\n| where ResourceProvider == \"MICROSOFT.KEYVAULT\"\n| where ResultSignature in (\"Forbidden\", \"Unauthorized\")\n| summarize Count = count() by CallerIPAddress, OperationName\n\n\u002F\u002F Sensitive role assignments — detect privilege escalation attempts\nAzureActivity\n| where OperationNameValue =~ \"MICROSOFT.AUTHORIZATION\u002FROLEASSIGNMENTS\u002FWRITE\"\n| project TimeGenerated, Caller, OperationNameValue, ResourceGroup\n\n\u002F\u002F API rate limit violations\nAppRequests\n| where ResultCode == \"429\"\n| summarize Count = count() by ClientIP, bin(TimeGenerated, 5m)\n| where Count > 50\n```\n\n### Advanced — Full DevSecOps Pipeline, Managed Identity Chain, AKS Workload Identity\n\n**Complete DevSecOps pipeline — all gates required, no soft-fails:**\n```yaml\n# .github\u002Fworkflows\u002Fdevsecops.yml\nname: DevSecOps Pipeline\non:\n  push: { branches: [main] }\n  pull_request: { branches: [main] }\npermissions:\n  security-events: write\n  contents: read\n\njobs:\n  sast-semgrep:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: returntocorp\u002Fsemgrep-action@v1\n        with:\n          config: 'p\u002Fsecurity-audit p\u002Fowasp-top-ten p\u002Fcsharp p\u002Ftypescript'\n          generateSarif: true\n      - uses: github\u002Fcodeql-action\u002Fupload-sarif@v3\n        with: { sarif_file: semgrep.sarif }\n        if: always()\n\n  sast-codeql:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: github\u002Fcodeql-action\u002Finit@v3\n        with: { languages: 'csharp, javascript' }\n      - uses: github\u002Fcodeql-action\u002Fanalyze@v3\n\n  sca-snyk:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: snyk\u002Factions\u002Fdotnet@master\n        env: { SNYK_TOKEN: '${{ secrets.SNYK_TOKEN }}' }\n        with: { args: '--severity-threshold=high' }\n\n  secrets-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with: { fetch-depth: 0 }  # full history required\n      - uses: gitleaks\u002Fgitleaks-action@v2\n        env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }\n\n  container-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - run: docker build -t myapp:${{ github.sha }} .\n      - uses: aquasecurity\u002Ftrivy-action@master\n        with:\n          image-ref: 'myapp:${{ github.sha }}'\n          severity: 'CRITICAL,HIGH'\n          exit-code: '1'\n\n  iac-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: bridgecrewio\u002Fcheckov-action@master\n        with: { directory: 'infra\u002F', framework: bicep, soft_fail: false }\n\n  deploy:\n    needs: [sast-semgrep, sast-codeql, sca-snyk, secrets-scan, container-scan, iac-scan]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    runs-on: ubuntu-latest\n    environment: production\n    steps:\n      - run: echo \"All security gates passed — deploying\"\n```\n\n**Zero-secrets Managed Identity chain — full Bicep:**\n```bicep\n\u002F\u002F User-assigned identity shared across services\nresource appIdentity 'Microsoft.ManagedIdentity\u002FuserAssignedIdentities@2023-01-31' = {\n  name: 'id-myapp'\n  location: location\n}\n\n\u002F\u002F Key Vault Secrets User (role ID: 4633458b-17de-408a-b874-0445c86b69e6)\nresource kvRole 'Microsoft.Authorization\u002FroleAssignments@2022-04-01' = {\n  scope: vault\n  name: guid(vault.id, appIdentity.id, '4633458b-17de-408a-b874-0445c86b69e6')\n  properties: {\n    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization\u002FroleDefinitions',\n      '4633458b-17de-408a-b874-0445c86b69e6')\n    principalId: appIdentity.properties.principalId\n    principalType: 'ServicePrincipal'\n  }\n}\n\n\u002F\u002F Cosmos DB Built-in Data Contributor\nresource cosmosRole 'Microsoft.DocumentDB\u002FdatabaseAccounts\u002FsqlRoleAssignments@2024-05-15' = {\n  parent: cosmosAccount\n  name: guid(cosmosAccount.id, appIdentity.properties.principalId, 'contributor')\n  properties: {\n    roleDefinitionId: '${cosmosAccount.id}\u002FsqlRoleDefinitions\u002F00000000-0000-0000-0000-000000000002'\n    principalId: appIdentity.properties.principalId\n    scope: cosmosAccount.id\n  }\n}\n\n\u002F\u002F Storage Blob Data Contributor (role ID: ba92f5b4-2d11-453d-a403-e96b0029c9fe)\nresource storageRole 'Microsoft.Authorization\u002FroleAssignments@2022-04-01' = {\n  scope: storageAccount\n  name: guid(storageAccount.id, appIdentity.id, 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')\n  properties: {\n    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization\u002FroleDefinitions',\n      'ba92f5b4-2d11-453d-a403-e96b0029c9fe')\n    principalId: appIdentity.properties.principalId\n    principalType: 'ServicePrincipal'\n  }\n}\n```\n\n**AKS Workload Identity** (Pod Identity is deprecated, EOL September 2025):\n\n```yaml\nspec:\n  securityContext:\n    runAsNonRoot: true\n    runAsUser: 1000\n    seccompProfile: { type: RuntimeDefault }\n  containers:\n  - name: api\n    securityContext:\n      allowPrivilegeEscalation: false\n      readOnlyRootFilesystem: true\n      capabilities: { drop: [ALL] }\n```\n\n---\n\n## TWELVE HIGHEST-IMPACT ACTIONS (IN PRIORITY ORDER)\n\n1. **Replace all connection-string-with-keys patterns with Managed Identity RBAC** — the single\n   biggest attack surface reduction across the entire stack.\n2. **Enforce Authorization Code + PKCE on all SPAs** while disabling implicit grant in app\n   registrations.\n3. **Deploy Private Endpoints** for every PaaS service (Key Vault, Cosmos DB, PostgreSQL,\n   Databricks, Storage).\n4. **Enable Microsoft Defender for Cloud** across all plans.\n5. **Implement the DevSecOps pipeline** with quality gates that block on HIGH\u002FCRITICAL findings.\n6. **Deploy enterprise-managed settings** for Claude Code and Cursor with file deny rules.\n7. **Add PostToolUse Semgrep hooks** to every repository's `.claude\u002Fsettings.json`.\n8. **Enable Key Vault RBAC, soft-delete, and purge protection** on every vault.\n9. **Implement PostgreSQL RLS** for multi-tenant data isolation.\n10. **Enable Unity Catalog** for all Databricks data governance with column masking on PII.\n11. **Wire Gitleaks** with full git history scan (`fetch-depth: 0`) on every PR.\n12. **Set `ClockSkew = TimeSpan.Zero`** and verify `UseAuthentication` precedes\n    `UseAuthorization` in every .NET API.\n\nThe maturity tiers are not sequential gates — they represent increasing depth. A team can\nimplement Foundational across all six domains in the first sprint, then progressively deepen\ninto Intermediate and Advanced tiers over subsequent quarters.\n\nZero-secrets architecture through Managed Identity is the foundation everything else builds upon.\nWithout it, Key Vault references, Private Endpoints, and RBAC assignments are incomplete controls.\n",{"name":5,"description":7},"develop","ae32736a1aabddabca5d2c96d665aa0ebc7d8700","src\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fcybersecurity-implementation",3,"https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey","https:\u002F\u002Fthe-vibey-project.github.io\u002Fvibey\u002F","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project","https:\u002F\u002Fvibewithadam.matthewsteinberger.com","freedom for software engineers","2026-11-15 05:47:42",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add the-vibey-project\u002Fvibey --skill cybersecurity-implementation",{"tool":40,"command":41},"bunx","bunx skills add the-vibey-project\u002Fvibey --skill cybersecurity-implementation",{"tool":43,"command":44},"pnpm","pnpm dlx skills add the-vibey-project\u002Fvibey --skill cybersecurity-implementation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fcybersecurity-implementation\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7AT1FQJAE1FQYAMDTF490Y4","white-paper-writing","Use when writing white papers, technical reports, policy documents, thought leadership pieces, or any long-form authoritative document. Triggers on requests to write, structure, outline, or review white papers, technical reports, position papers, policy briefs, or evidence-driven arguments. Also use for B2B content marketing strategy, technical documentation requiring authority, academic-style reports, or any document that must educate while persuading. Use when someone asks \"how should I structure this\" for a long-form document.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fwhite-paper-writing\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7AT16BJRJJKK2MASXRZS76G","prose-technical-mechanics","Use when editing or writing prose at a technical\u002Fmechanical level: choosing between Anglo-Saxon and Latinate diction, placing information in topic vs stress positions, writing periodic vs cumulative sentences, handling sentence rhythm, punctuation as logic, transitions, paragraph structure, or phonesthetics. Use when someone wants to understand WHY prose works or doesn't, not just surface-level style advice. Triggers on word choice, sentence structure, emphasis, rhythm, diction, or any deep writing mechanics question.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-technical-mechanics\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7AT0W9HT0ZZ9Y287NW99MR3","prose-mechanics","Use when writing, editing, or analyzing prose style; when trying to avoid generic AI-sounding writing; when applying specific prose styles such as journalistic, academic, narrative, KJV biblical, Hemingway plain, Latinate\u002FJamesian, Orwellian, Augustan, Victorian, Early Modern (Bacon, Browne, Milton), or free indirect discourse; or when coaching someone on writing voice and mechanics. Triggers on any request to improve, analyze, or write in a specific prose style, to fix \"AI-sounding\" writing, to make prose more vivid or concrete, to vary sentence rhythm, or to understand how a particular writer achieves their effects.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-mechanics\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7AT0KR635JX66X2X6F3E2CP","narrative-structure","Use when structuring stories, pitches, presentations, white papers, or any persuasive narrative; analyzing the hero's journey in fiction or non-fiction; applying StoryBrand for business communication; designing narrative arcs for thought leadership; or understanding Vogler, Snyder, Propp, or Campbell frameworks. Triggers on any narrative structure, storytelling, pitch structure, StoryBrand, hero's journey, three-act structure, Freytag, Save the Cat, narrative arc, or \"how should I structure this story\u002Fpitch\u002Fpresentation\" request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fnarrative-structure\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7AT0AKGW09NKKZDYBT8VRDE","legal-brief-writing","Use when writing legal briefs, motions, or any court filing; when analyzing judicial cognition and persuasion; when applying elite brief-writing techniques from Roberts, Clement, Kagan, Garner; or when structuring legal arguments for maximum persuasion. Also use for autistic\u002Fneurodivergent advocates who need to understand how their natural communication style maps to elite legal advocacy. Triggers on any legal writing, brief drafting, motion preparation, or legal argument structuring request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Flegal-brief-writing\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7AT00VWPS4Q8B5VEMXX9NQT","journal-publishability-criteria","Use whenever a research paper, article or preprint is being written, revised, reviewed or published, and specifically before every publication of docs\u002Fpaper.md. Covers what legitimate journals actually gate on, in order of gating — the editor's desk screen (scope, novelty, package problems), what reviewers judge (methodological soundness, claims the evidence can carry, statistical and qualitative reporting), EQUATOR reporting guidelines, the ICMJE authorship criteria, COPE's view of text recycling, the near-universal generative-AI policy (no AI author, disclosure, author responsibility), TOP 2025 transparency standards, how to verify a journal is legitimate, submitting without an institution, and a pre-submission checklist. Triggers on requests to evaluate, review, prepare or submit a paper, to judge publishability, to write a declarations or data-availability section, to disclose AI use, or to check a journal.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fjournal-publishability-criteria\u002FSKILL.md",[],[]]