mirror of
https://github.com/affaan-m/everything-claude-code.git
synced 2026-04-09 10:53:34 +08:00
docs: expand Spring Boot skills and add Go microservice example
- springboot-security: add code examples for authorization, input validation, SQL injection prevention, password encoding, CORS, rate limiting, and secrets management (119 → 261 lines) - springboot-verification: add unit test, Testcontainers integration test, MockMvc API test patterns, and security scan grep commands (100 → 222 lines) - Add Go microservice example (gRPC + PostgreSQL + clean architecture) - Update README directory tree with new example
This commit is contained in:
@@ -42,17 +42,88 @@ public class JwtAuthFilter extends OncePerRequestFilter {
|
||||
- Use `@PreAuthorize("hasRole('ADMIN')")` or `@PreAuthorize("@authz.canEdit(#id)")`
|
||||
- Deny by default; expose only required scopes
|
||||
|
||||
```java
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
public class AdminController {
|
||||
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
@GetMapping("/users")
|
||||
public List<UserDto> listUsers() {
|
||||
return userService.findAll();
|
||||
}
|
||||
|
||||
@PreAuthorize("@authz.isOwner(#id, authentication)")
|
||||
@DeleteMapping("/users/{id}")
|
||||
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
|
||||
userService.delete(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Input Validation
|
||||
|
||||
- Use Bean Validation with `@Valid` on controllers
|
||||
- Apply constraints on DTOs: `@NotBlank`, `@Email`, `@Size`, custom validators
|
||||
- Sanitize any HTML with a whitelist before rendering
|
||||
|
||||
```java
|
||||
// BAD: No validation
|
||||
@PostMapping("/users")
|
||||
public User createUser(@RequestBody UserDto dto) {
|
||||
return userService.create(dto);
|
||||
}
|
||||
|
||||
// GOOD: Validated DTO
|
||||
public record CreateUserDto(
|
||||
@NotBlank @Size(max = 100) String name,
|
||||
@NotBlank @Email String email,
|
||||
@NotNull @Min(0) @Max(150) Integer age
|
||||
) {}
|
||||
|
||||
@PostMapping("/users")
|
||||
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(userService.create(dto));
|
||||
}
|
||||
```
|
||||
|
||||
## SQL Injection Prevention
|
||||
|
||||
- Use Spring Data repositories or parameterized queries
|
||||
- For native queries, use `:param` bindings; never concatenate strings
|
||||
|
||||
```java
|
||||
// BAD: String concatenation in native query
|
||||
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
|
||||
|
||||
// GOOD: Parameterized native query
|
||||
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
|
||||
List<User> findByName(@Param("name") String name);
|
||||
|
||||
// GOOD: Spring Data derived query (auto-parameterized)
|
||||
List<User> findByEmailAndActiveTrue(String email);
|
||||
```
|
||||
|
||||
## Password Encoding
|
||||
|
||||
- Always hash passwords with BCrypt or Argon2 — never store plaintext
|
||||
- Use `PasswordEncoder` bean, not manual hashing
|
||||
|
||||
```java
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder(12); // cost factor 12
|
||||
}
|
||||
|
||||
// In service
|
||||
public User register(CreateUserDto dto) {
|
||||
String hashedPassword = passwordEncoder.encode(dto.password());
|
||||
return userRepository.save(new User(dto.email(), hashedPassword));
|
||||
}
|
||||
```
|
||||
|
||||
## CSRF Protection
|
||||
|
||||
- For browser session apps, keep CSRF enabled; include token in forms/headers
|
||||
@@ -70,6 +141,25 @@ http
|
||||
- Keep `application.yml` free of credentials; use placeholders
|
||||
- Rotate tokens and DB credentials regularly
|
||||
|
||||
```yaml
|
||||
# BAD: Hardcoded in application.yml
|
||||
spring:
|
||||
datasource:
|
||||
password: mySecretPassword123
|
||||
|
||||
# GOOD: Environment variable placeholder
|
||||
spring:
|
||||
datasource:
|
||||
password: ${DB_PASSWORD}
|
||||
|
||||
# GOOD: Spring Cloud Vault integration
|
||||
spring:
|
||||
cloud:
|
||||
vault:
|
||||
uri: https://vault.example.com
|
||||
token: ${VAULT_TOKEN}
|
||||
```
|
||||
|
||||
## Security Headers
|
||||
|
||||
```java
|
||||
@@ -82,11 +172,63 @@ http
|
||||
.referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));
|
||||
```
|
||||
|
||||
## CORS Configuration
|
||||
|
||||
- Configure CORS at the security filter level, not per-controller
|
||||
- Restrict allowed origins — never use `*` in production
|
||||
|
||||
```java
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(List.of("https://app.example.com"));
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
|
||||
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
|
||||
config.setAllowCredentials(true);
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/api/**", config);
|
||||
return source;
|
||||
}
|
||||
|
||||
// In SecurityFilterChain:
|
||||
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));
|
||||
```
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
- Apply Bucket4j or gateway-level limits on expensive endpoints
|
||||
- Log and alert on bursts; return 429 with retry hints
|
||||
|
||||
```java
|
||||
// Using Bucket4j for per-endpoint rate limiting
|
||||
@Component
|
||||
public class RateLimitFilter extends OncePerRequestFilter {
|
||||
private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
|
||||
|
||||
private Bucket createBucket() {
|
||||
return Bucket.builder()
|
||||
.addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1))))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
String clientIp = request.getRemoteAddr();
|
||||
Bucket bucket = buckets.computeIfAbsent(clientIp, k -> createBucket());
|
||||
|
||||
if (bucket.tryConsume(1)) {
|
||||
chain.doFilter(request, response);
|
||||
} else {
|
||||
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
|
||||
response.getWriter().write("{\"error\": \"Rate limit exceeded\"}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Dependency Security
|
||||
|
||||
- Run OWASP Dependency Check / Snyk in CI
|
||||
|
||||
@@ -42,6 +42,111 @@ Report:
|
||||
- Total tests, passed/failed
|
||||
- Coverage % (lines/branches)
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Test service logic in isolation with mocked dependencies:
|
||||
|
||||
```java
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserServiceTest {
|
||||
|
||||
@Mock private UserRepository userRepository;
|
||||
@InjectMocks private UserService userService;
|
||||
|
||||
@Test
|
||||
void createUser_validInput_returnsUser() {
|
||||
var dto = new CreateUserDto("Alice", "alice@example.com");
|
||||
var expected = new User(1L, "Alice", "alice@example.com");
|
||||
when(userRepository.save(any(User.class))).thenReturn(expected);
|
||||
|
||||
var result = userService.create(dto);
|
||||
|
||||
assertThat(result.name()).isEqualTo("Alice");
|
||||
verify(userRepository).save(any(User.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUser_duplicateEmail_throwsException() {
|
||||
var dto = new CreateUserDto("Alice", "existing@example.com");
|
||||
when(userRepository.existsByEmail(dto.email())).thenReturn(true);
|
||||
|
||||
assertThatThrownBy(() -> userService.create(dto))
|
||||
.isInstanceOf(DuplicateEmailException.class);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Integration Tests with Testcontainers
|
||||
|
||||
Test against a real database instead of H2:
|
||||
|
||||
```java
|
||||
@SpringBootTest
|
||||
@Testcontainers
|
||||
class UserRepositoryIntegrationTest {
|
||||
|
||||
@Container
|
||||
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
|
||||
.withDatabaseName("testdb");
|
||||
|
||||
@DynamicPropertySource
|
||||
static void configureProperties(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.datasource.url", postgres::getJdbcUrl);
|
||||
registry.add("spring.datasource.username", postgres::getUsername);
|
||||
registry.add("spring.datasource.password", postgres::getPassword);
|
||||
}
|
||||
|
||||
@Autowired private UserRepository userRepository;
|
||||
|
||||
@Test
|
||||
void findByEmail_existingUser_returnsUser() {
|
||||
userRepository.save(new User("Alice", "alice@example.com"));
|
||||
|
||||
var found = userRepository.findByEmail("alice@example.com");
|
||||
|
||||
assertThat(found).isPresent();
|
||||
assertThat(found.get().getName()).isEqualTo("Alice");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### API Tests with MockMvc
|
||||
|
||||
Test controller layer with full Spring context:
|
||||
|
||||
```java
|
||||
@WebMvcTest(UserController.class)
|
||||
class UserControllerTest {
|
||||
|
||||
@Autowired private MockMvc mockMvc;
|
||||
@MockBean private UserService userService;
|
||||
|
||||
@Test
|
||||
void createUser_validInput_returns201() throws Exception {
|
||||
var user = new UserDto(1L, "Alice", "alice@example.com");
|
||||
when(userService.create(any())).thenReturn(user);
|
||||
|
||||
mockMvc.perform(post("/api/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("""
|
||||
{"name": "Alice", "email": "alice@example.com"}
|
||||
"""))
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(jsonPath("$.name").value("Alice"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUser_invalidEmail_returns400() throws Exception {
|
||||
mockMvc.perform(post("/api/users")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("""
|
||||
{"name": "Alice", "email": "not-an-email"}
|
||||
"""))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Phase 4: Security Scan
|
||||
|
||||
```bash
|
||||
@@ -50,10 +155,27 @@ mvn org.owasp:dependency-check-maven:check
|
||||
# or
|
||||
./gradlew dependencyCheckAnalyze
|
||||
|
||||
# Secrets (git)
|
||||
# Secrets in source
|
||||
grep -rn "password\s*=\s*\"" src/ --include="*.java" --include="*.yml" --include="*.properties"
|
||||
grep -rn "sk-\|api_key\|secret" src/ --include="*.java" --include="*.yml"
|
||||
|
||||
# Secrets (git history)
|
||||
git secrets --scan # if configured
|
||||
```
|
||||
|
||||
### Common Security Findings
|
||||
|
||||
```
|
||||
# Check for System.out.println (use logger instead)
|
||||
grep -rn "System\.out\.print" src/main/ --include="*.java"
|
||||
|
||||
# Check for raw exception messages in responses
|
||||
grep -rn "e\.getMessage()" src/main/ --include="*.java"
|
||||
|
||||
# Check for wildcard CORS
|
||||
grep -rn "allowedOrigins.*\*" src/main/ --include="*.java"
|
||||
```
|
||||
|
||||
## Phase 5: Lint/Format (optional gate)
|
||||
|
||||
```bash
|
||||
|
||||
Reference in New Issue
Block a user