agentleFS
lgzarturolgzarturo/codeconductor/.cursor/skills/security/SKILL.md

security

Skill0 starsChanged 2 months agoMITView on GitHub

Provides expert knowledge for implementing and reviewing application security following OWASP Top 10 (2021), with stack-specific patterns for Spring Boot, Django, Next.js, and Astro.

  • Reads credentials
  • Installs packages

78 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use cost-reducer, trigger-dev and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • daianepepes-labSkill

    cost-reducer

    Analyze and reduce costs across cloud infrastructure, code, and services. Use when asked to cut costs, optimize spending, reduce bills, or improve cost efficiency.

    Also in 5 projects that use this

  • xfstudioSkill

    trigger-dev

    Trigger.dev expert for background jobs, AI workflows, and reliable async execution with excellent developer experience and TypeScript-first design. Use when: trigger.dev, trigger dev, background task, ai background job, long running task.

    Also in 4 projects that use this

  • ffsshhttiikkSkill

    scalability

    Core foundational concepts and principles for Scalability

    Also in 4 projects that use this

  • daianepepes-labSkill

    self-healing

    Detect, diagnose, and automatically fix recurring errors, memory issues, and system degradation. Use when a system has recurring failures, memory leaks, performance degradation, or needs automatic recovery mechanisms.

    Also in 5 projects that use this

  • xfstudioSkill

    customer-support

    Elite AI-powered customer support specialist mastering

    Also in 4 projects that use this

  • ffsshhttiikkSkill

    cicd

    Continuous integration and delivery pipelines

    Also in 4 projects that use this

  • +1 more from daianepepes-lab

The file

We split this skill into the rules it gives an agent

10 rules. 0 are common, 8 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 56 edited versions we read keep these.

  • 8

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    Use allowlists (accept known-good), not blocklists (reject known-bad)

    line 65
  2. Distinctive:

    Use JWTs for stateless API authentication.

    line 115
  3. Very specific:

    Never store access tokens in localStorage — XSS can read them.

    line 124
  4. Distinctive:

    Never store plaintext passwords.

    line 181
  5. Distinctive:

    Principle of least privilege: every endpoint must explicitly declare who can access it.

    line 206
  6. Distinctive:

    Always check authorization at the object level, not just the endpoint level.

    line 226
  7. Distinctive:

    Never commit secrets to source control: No exceptions.

    line 293
  8. Distinctive:

    Use separate credentials per environment (dev, staging, prod)

    line 305
  9. Very specific:

    Add .env to .gitignore and never commit it

    line 306
  10. Distinctive:

    Never concatenate user input into SQL strings.

    line 346

“Common” is measured: kept by at least 6 in 10 of the 56 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Security

OWASP Top 10 (2021) — Quick Reference

#CategoryWhat to check
A01Broken Access ControlIs authorization enforced on every endpoint?
A02Cryptographic FailuresAre secrets encrypted at rest and in transit?
A03InjectionIs all input sanitized or parameterized?
A04Insecure DesignIs the threat model documented?
A05Security MisconfigurationAre defaults changed? Debug off in prod?
A06Vulnerable ComponentsAre dependencies up to date?
A07Auth & Session FailuresAre sessions invalidated on logout? Token expiry set?
A08Software Integrity FailuresAre supply-chain dependencies verified?
A09Logging & Monitoring FailuresAre security events logged without leaking PII?
A10SSRFAre outbound URLs allowlisted?

Input Validation

Validate all input at system boundaries. Never trust data from: HTTP request body, query parameters, headers, cookies, or environment variables passed by external systems.

Rules:

  • Validate type, format, length, and range
  • Reject unknown fields — do not silently ignore them
  • Use allowlists (accept known-good), not blocklists (reject known-bad)
  • Validate at the API layer before it reaches the service layer
// Spring Boot — Bean Validation
data class CreateUserRequest(
    @field:NotBlank @field:Email val email: String,
    @field:Size(min = 8, max = 72) val password: String,
    @field:Size(max = 100) val name: String
)

@PostMapping
fun createUser(@Valid @RequestBody request: CreateUserRequest): ResponseEntity<UserResponse> {
    // request is guaranteed valid here
}
# Django REST Framework — serializer validation
class CreateUserSerializer(serializers.Serializer):
    email = serializers.EmailField(max_length=254)
    password = serializers.CharField(min_length=8, max_length=72, write_only=True)
    name = serializers.CharField(max_length=100)

    def validate_email(self, value):
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError("Email already registered.")
        return value.lower()
// Next.js / Astro — Zod
import { z } from 'zod';

const CreateUserSchema = z.object({
  email: z.string().email().max(254),
  password: z.string().min(8).max(72),
  name: z.string().max(100),
});

const result = CreateUserSchema.safeParse(body);
if (!result.success) {
  return Response.json({ error: result.error.flatten() }, { status: 400 });
}

Authentication

JWT (Stateless)

Use JWTs for stateless API authentication. Keep access tokens short-lived.

Token lifetimes:

TokenLifetimeStorage
Access token15 minutesMemory (never localStorage)
Refresh token7–30 daysHttpOnly cookie

Never store access tokens in localStorage — XSS can read them. Store in memory (React state, module variable) and refresh via the HttpOnly cookie.

// Spring Security 6 + JWT
@Configuration
@EnableWebSecurity
class SecurityConfig(private val jwtFilter: JwtAuthenticationFilter) {

    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain = http
        .csrf { it.disable() }                         // stateless API — CSRF not needed
        .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
        .authorizeHttpRequests { auth ->
            auth
                .requestMatchers("/api/auth/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
        }
        .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter::class.java)
        .build()
}
# Django — djangorestframework-simplejwt
# settings.py
SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=7),
    "ROTATE_REFRESH_TOKENS": True,
    "BLACKLIST_AFTER_ROTATION": True,
    "ALGORITHM": "HS256",
    "AUTH_HEADER_TYPES": ("Bearer",),
}
// Next.js — Auth.js (NextAuth v5)
// auth.ts
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';

export const { auth, signIn, signOut } = NextAuth({
  providers: [
    Credentials({
      authorize: async (credentials) => {
        // validate and return user or null
      },
    }),
  ],
  session: { strategy: 'jwt', maxAge: 7 * 24 * 60 * 60 },
});

Password Hashing

Never store plaintext passwords. Never use MD5 or SHA-1 for password hashing.

AlgorithmUseWork factor
bcryptdefaultcost=12
Argon2idpreferred when availablem=65536, t=3
PBKDF2FIPS environmentsiterations=600000
// Spring Security uses bcrypt by default
@Bean
fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder(12)
# Django uses PBKDF2 by default; switch to Argon2 for stronger hashing
# pip install django[argon2]
PASSWORD_HASHERS = [
    "django.contrib.auth.hashers.Argon2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2PasswordHasher",  # fallback for existing hashes
]

Authorization

Principle of least privilege: every endpoint must explicitly declare who can access it. Deny by default.

// Spring — method-level security
@PreAuthorize("hasRole('ADMIN') or #userId == authentication.name")
fun getUser(userId: String): UserResponse { ... }
# Django REST Framework
class UserDetailView(RetrieveUpdateAPIView):
    permission_classes = [IsAuthenticated, IsOwnerOrAdmin]
    queryset = User.objects.all()

class IsOwnerOrAdmin(BasePermission):
    def has_object_permission(self, request, view, obj):
        return request.user.is_staff or obj == request.user

Always check authorization at the object level, not just the endpoint level. An authenticated user should not be able to access another user's data by changing an ID in the URL.

CORS

// Spring Boot — explicit allowlist; never use "*" in production
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
    val config = CorsConfiguration().apply {
        allowedOrigins = listOf("https://app.example.com")
        allowedMethods = listOf("GET", "POST", "PUT", "DELETE")
        allowedHeaders = listOf("Authorization", "Content-Type")
        allowCredentials = true
        maxAge = 3600L
    }
    return UrlBasedCorsConfigurationSource().apply {
        registerCorsConfiguration("/api/**", config)
    }
}
# Django — django-cors-headers
CORS_ALLOWED_ORIGINS = [
    "https://app.example.com",
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = False  # never True in production

Security Headers

Set these headers on every response. They defend against XSS, clickjacking, and MIME sniffing.

Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
// Next.js — next.config.ts
const securityHeaders = [
  { key: 'X-Frame-Options', value: 'DENY' },
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
  {
    key: 'Strict-Transport-Security',
    value: 'max-age=63072000; includeSubDomains; preload',
  },
];

export default {
  headers: async () => [
    { source: '/(.*)', headers: securityHeaders },
  ],
};

Secrets Management

Never commit secrets to source control. No exceptions.

✗ DATABASE_URL = "postgres://user:password@prod.example.com/db"  # in source
✓ DATABASE_URL = env("DATABASE_URL")                              # from environment

Rules:

  • Load secrets from environment variables or a secrets manager (AWS Secrets Manager, Vault, GCP Secret Manager)
  • Rotate credentials on any suspected exposure
  • Use separate credentials per environment (dev, staging, prod)
  • Add .env to .gitignore and never commit it
# Django — django-environ
import environ
env = environ.Env()
environ.Env.read_env()  # reads .env in development only

SECRET_KEY = env("SECRET_KEY")
DATABASE_URL = env.db("DATABASE_URL")

Rate Limiting

Protect authentication endpoints. Brute-force without rate limiting can compromise any account with a weak password.

// Spring Boot — Bucket4j
@Component
class RateLimitFilter(private val rateLimiter: RateLimiter) : OncePerRequestFilter() {

    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, chain: FilterChain) {
        if (request.requestURI.startsWith("/api/auth/")) {
            val probe = rateLimiter.tryConsumeAndReturnRemaining(1)
            if (!probe.isConsumed) {
                response.status = HttpStatus.TOO_MANY_REQUESTS.value()
                return
            }
        }
        chain.doFilter(request, response)
    }
}

Minimum rate limits for auth endpoints: 5 requests per minute per IP. Stricter limits (e.g., 3 per 15 minutes) are better for login endpoints.

SQL Injection Prevention

Never concatenate user input into SQL strings. Always use parameterized queries or an ORM.

// bad — SQL injection risk
val user = jdbcTemplate.queryForObject("SELECT * FROM users WHERE email = '$email'")

// good — parameterized
val user = jdbcTemplate.queryForObject(
    "SELECT * FROM users WHERE email = ?",
    UserRowMapper(),
    email
)
# bad
User.objects.raw(f"SELECT * FROM users WHERE email = '{email}'")

# good — Django ORM handles parameterization automatically
User.objects.filter(email=email)

Logging Security Events

Log authentication events without including sensitive data.

Log:   login success/failure, permission denied, password reset, token refresh
Never: passwords, tokens, PII (full email in prod logs), credit card numbers
// Log security events at INFO level; failures at WARN
log.info("Authentication successful for user={}", userId)
log.warn("Authentication failed: invalid credentials for user={}", maskedEmail)
log.warn("Authorization denied: user={} attempted access to resource={}", userId, resourceId)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.