first commit

This commit is contained in:
Nilton Constantino
2026-04-22 14:55:58 +01:00
commit d48172539a
149 changed files with 4604 additions and 0 deletions
@@ -0,0 +1,16 @@
plugins {
id("java-library-conventions")
}
dependencies {
api(project(":main-infrastructure"))
api(project(":main-contract-subjects"))
implementation(project(":main-service"))
implementation(Dependencies.jjwtApi)
runtimeOnly(Dependencies.jjwtImpl)
runtimeOnly(Dependencies.jjwtJackson)
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("com.nimbusds:nimbus-jose-jwt")
}
@@ -0,0 +1,22 @@
package net.bquarkz.ai.gateway.controllers;
import net.bquarkz.ai.gateway.messages.ResponsePayload;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public abstract class AbstractController {
protected <T> ResponseEntity<ResponsePayload<T>> ok(T data, String requestId) {
return ResponseEntity.ok(ResponsePayload.success(data, requestId));
}
protected <T> ResponseEntity<ResponsePayload<T>> forbidden(String reason, String requestId) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ResponsePayload.error(reason, requestId));
}
protected <T> ResponseEntity<ResponsePayload<T>> badRequest(String reason, String requestId) {
return ResponseEntity.badRequest()
.body(ResponsePayload.error(reason, requestId));
}
}
@@ -0,0 +1,44 @@
package net.bquarkz.ai.gateway.controllers;
import net.bquarkz.ai.gateway.exceptions.*;
import net.bquarkz.ai.gateway.messages.ResponsePayload;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.UUID;
@ControllerAdvice
public class GenericExceptionHandler {
@ExceptionHandler(PolicyDeniedException.class)
public ResponseEntity<ResponsePayload<Void>> handlePolicyDenied(PolicyDeniedException ex) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(ResponsePayload.error(ex.getMessage(), UUID.randomUUID().toString()));
}
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ResponsePayload<Void>> handleUnauthorized(UnauthorizedException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(ResponsePayload.error(ex.getMessage(), UUID.randomUUID().toString()));
}
@ExceptionHandler(ToolNotFoundException.class)
public ResponseEntity<ResponsePayload<Void>> handleToolNotFound(ToolNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ResponsePayload.error(ex.getMessage(), UUID.randomUUID().toString()));
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity<ResponsePayload<Void>> handleValidation(ValidationException ex) {
return ResponseEntity.badRequest()
.body(ResponsePayload.error(ex.getMessage(), UUID.randomUUID().toString()));
}
@ExceptionHandler(GatewayException.class)
public ResponseEntity<ResponsePayload<Void>> handleGateway(GatewayException ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ResponsePayload.error(ex.getMessage(), UUID.randomUUID().toString()));
}
}
@@ -0,0 +1,36 @@
package net.bquarkz.ai.gateway.security;
import net.bquarkz.ai.gateway.contracts.GatewayContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Component
public class ContextBuilder {
public GatewayContext buildContext(Authentication authentication, GatewayContext.RateInfo rateInfo) {
Jwt jwt = (Jwt) authentication.getPrincipal();
String agentId = jwt.getSubject();
List<String> scopesList = jwt.getClaimAsStringList("scopes");
Set<String> scopes = scopesList != null ? new HashSet<>(scopesList) : Set.of();
String environment = jwt.getClaimAsString("environment");
return GatewayContext.builder()
.subject(GatewayContext.Subject.builder()
.agentId(agentId)
.scopes(scopes)
.build())
.context(GatewayContext.ContextData.builder()
.environment(environment != null ? environment : "local")
.timestamp(OffsetDateTime.now())
.rate(rateInfo)
.build())
.build();
}
}
@@ -0,0 +1,30 @@
package net.bquarkz.ai.gateway.security;
import org.springframework.stereotype.Component;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
@Component
public class SigningKeyProvider {
private final KeyPair keyPair;
public SigningKeyProvider() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
this.keyPair = generator.generateKeyPair();
} catch (Exception e) {
throw new RuntimeException("Failed to generate RSA key pair", e);
}
}
public RSAPublicKey getPublicKey() {
return (RSAPublicKey) keyPair.getPublic();
}
public RSAPrivateKey getPrivateKey() {
return (RSAPrivateKey) keyPair.getPrivate();
}
}
@@ -0,0 +1,38 @@
package net.bquarkz.ai.gateway.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class TokenService {
private final SigningKeyProvider signingKeyProvider;
public String generateToken(String agentId, Set<String> scopes, String environment, long expiresInSeconds) {
Date now = new Date();
Date expiry = new Date(now.getTime() + expiresInSeconds * 1000);
return Jwts.builder()
.subject(agentId)
.claim("scopes", List.copyOf(scopes))
.claim("environment", environment)
.issuedAt(now)
.expiration(expiry)
.signWith(signingKeyProvider.getPrivateKey())
.compact();
}
public Claims parseToken(String token) {
return Jwts.parser()
.verifyWith(signingKeyProvider.getPublicKey())
.build()
.parseSignedClaims(token)
.getPayload();
}
}
@@ -0,0 +1,37 @@
package net.bquarkz.ai.gateway.security;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfiguration {
private final SigningKeyProvider signingKeyProvider;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/**").authenticated()
.anyRequest().denyAll()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(jwtDecoder())))
.build();
}
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(signingKeyProvider.getPublicKey()).build();
}
}