feat: establish AIOA identity and organization baseline

This commit is contained in:
selfrelease
2026-07-18 08:05:45 +08:00
commit bbb09ed56f
42 changed files with 2473 additions and 0 deletions
+42
View File
@@ -0,0 +1,42 @@
# Backend
Kotlin + Spring Boot 模块化单体。计划模块:`boot``identity``organization``authorization``workflow``form``approval``document``notification``ai-orchestration``audit`
模块必须通过应用接口协作,不能直接访问其他模块拥有的表。
## 本地构建
```bash
export JAVA_HOME=/usr/local/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home
export GRADLE_USER_HOME=/tmp/aioa-gradle-home
./gradlew test
```
本机默认 `~/.gradle` 原生缓存存在加载问题,因此当前建议为项目构建显式设置 `GRADLE_USER_HOME`
## 当前能力
- Spring Boot 3.5.3 / Kotlin 2.1.21 / JDK 21
- OAuth2 Resource Server,健康检查匿名可访问,业务 API 默认要求认证
- `X-Trace-Id` 接收、校验、生成、响应回传与日志上下文
- RFC 9457 `application/problem+json` 风格的统一异常处理
- PostgreSQL、jOOQ 与 Flyway
- 基础 Schema 和审计事件表迁移
- 租户、用户、部门、岗位、任职关系和业务角色模型
- `/api/v1/me` 根据 JWT 租户与 Subject 查询 OA 权威用户数据
## 开发身份
本地 Keycloak Realm 为 `aioa`,移动端公共客户端为 `aioa-mobile`,启用 Authorization Code + PKCE。为了便于本地联调,还暂时启用了 Direct Access Grant。
开发环境的 OIDC Issuer 固定为 `http://localhost:8081/realms/aioa`;客户端和后端不能混用 `127.0.0.1`,因为 JWT Issuer 必须完全一致。
| 用户名 | 密码 | 角色 |
|---|---|---|
| `employee` | `Employee123!` | 普通员工 |
| `manager` | `Manager123!` | 员工、部门主管 |
| `admin` | `Admin123!` | 员工、OA 管理员 |
这些凭据只允许用于本地开发,生产 Realm 不得导入测试用户,也不得启用密码模式。
PostgreSQL 使用版本化开发卷 `postgres-data-v1`,避免复用其他项目或旧凭据初始化的数据目录。切换卷版本不会删除旧卷。
开发数据库通过宿主机端口 `15432` 访问,容器内部仍使用 PostgreSQL 默认端口 `5432`
+40
View File
@@ -0,0 +1,40 @@
plugins {
id("org.springframework.boot")
id("io.spring.dependency-management")
kotlin("jvm")
kotlin("plugin.spring")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
kotlin {
compilerOptions {
freeCompilerArgs.addAll("-Xjsr305=strict")
}
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-jooq")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.flywaydb:flyway-core")
implementation("org.flywaydb:flyway-database-postgresql")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.security:spring-security-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.withType<Test> {
useJUnitPlatform()
}
@@ -0,0 +1,11 @@
package com.all8ai.aioa
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class AioaApplication
fun main(args: Array<String>) {
runApplication<AioaApplication>(*args)
}
@@ -0,0 +1,46 @@
package com.all8ai.aioa.identity.api
import com.all8ai.aioa.identity.application.CurrentUserService
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.UUID
@RestController
@RequestMapping("/api/v1/me")
class CurrentUserController(
private val currentUserService: CurrentUserService,
) {
@GetMapping
fun currentUser(@AuthenticationPrincipal jwt: Jwt): CurrentUserResponse {
val currentUser = currentUserService.get(jwt.subject, jwt.getClaimAsString("tenant_id"))
return CurrentUserResponse(
id = currentUser.id,
tenantId = currentUser.tenantId,
username = currentUser.username,
displayName = currentUser.displayName,
email = currentUser.email,
department = currentUser.department?.let { OrganizationRef(it.id, it.name) },
position = currentUser.position?.let { OrganizationRef(it.id, it.name) },
roles = currentUser.roles,
)
}
}
data class CurrentUserResponse(
val id: UUID,
val tenantId: UUID,
val username: String,
val displayName: String,
val email: String?,
val department: OrganizationRef?,
val position: OrganizationRef?,
val roles: Set<String>,
)
data class OrganizationRef(
val id: UUID,
val name: String,
)
@@ -0,0 +1,27 @@
package com.all8ai.aioa.identity.application
import com.all8ai.aioa.identity.domain.CurrentUser
import com.all8ai.aioa.identity.domain.CurrentUserRepository
import com.all8ai.aioa.shared.web.ApiException
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import java.util.UUID
@Service
class CurrentUserService(
private val repository: CurrentUserRepository,
) {
fun get(subject: String, tenantClaim: String?): CurrentUser {
val tenantId = tenantClaim?.let(::parseTenantId)
?: throw ApiException(HttpStatus.FORBIDDEN, "TENANT_CLAIM_MISSING", "登录身份缺少租户信息")
return repository.findActiveBySubject(tenantId, subject)
?: throw ApiException(HttpStatus.FORBIDDEN, "USER_NOT_PROVISIONED", "当前用户尚未同步到 OA 系统")
}
private fun parseTenantId(value: String): UUID = try {
UUID.fromString(value)
} catch (_: IllegalArgumentException) {
throw ApiException(HttpStatus.FORBIDDEN, "TENANT_CLAIM_INVALID", "登录身份中的租户信息无效")
}
}
@@ -0,0 +1,23 @@
package com.all8ai.aioa.identity.domain
import java.util.UUID
data class CurrentUser(
val id: UUID,
val tenantId: UUID,
val username: String,
val displayName: String,
val email: String?,
val department: OrganizationRef?,
val position: OrganizationRef?,
val roles: Set<String>,
)
data class OrganizationRef(
val id: UUID,
val name: String,
)
fun interface CurrentUserRepository {
fun findActiveBySubject(tenantId: UUID, subject: String): CurrentUser?
}
@@ -0,0 +1,77 @@
package com.all8ai.aioa.identity.infrastructure
import com.all8ai.aioa.identity.domain.CurrentUser
import com.all8ai.aioa.identity.domain.CurrentUserRepository
import com.all8ai.aioa.identity.domain.OrganizationRef
import org.jooq.DSLContext
import org.springframework.stereotype.Repository
import java.util.UUID
@Repository
class JooqCurrentUserRepository(
private val dsl: DSLContext,
) : CurrentUserRepository {
override fun findActiveBySubject(tenantId: UUID, subject: String): CurrentUser? {
val record = dsl.fetchOne(
"""
SELECT
u.id,
u.tenant_id,
u.username,
u.display_name,
u.email,
d.id AS department_id,
d.name AS department_name,
p.id AS position_id,
p.name AS position_name
FROM identity.user_account u
LEFT JOIN organization.user_assignment a
ON a.tenant_id = u.tenant_id
AND a.user_id = u.id
AND a.is_primary = TRUE
AND a.effective_from <= CURRENT_TIMESTAMP
AND (a.effective_until IS NULL OR a.effective_until > CURRENT_TIMESTAMP)
LEFT JOIN organization.department d ON d.id = a.department_id
LEFT JOIN organization.position p ON p.id = a.position_id
WHERE u.tenant_id = ?
AND u.keycloak_subject = ?
AND u.status = 'ACTIVE'
""".trimIndent(),
tenantId,
subject,
) ?: return null
val userId = record.get("id", UUID::class.java)!!
val roles = dsl.fetch(
"""
SELECT r.code
FROM authz.user_role ur
JOIN authz.role r
ON r.tenant_id = ur.tenant_id
AND r.id = ur.role_id
WHERE ur.tenant_id = ?
AND ur.user_id = ?
AND ur.effective_from <= CURRENT_TIMESTAMP
AND (ur.effective_until IS NULL OR ur.effective_until > CURRENT_TIMESTAMP)
AND r.status = 'ACTIVE'
ORDER BY r.code
""".trimIndent(),
tenantId,
userId,
).mapNotNull { it.get("code", String::class.java) }.toSortedSet()
return CurrentUser(
id = userId,
tenantId = record.get("tenant_id", UUID::class.java)!!,
username = record.get("username", String::class.java)!!,
displayName = record.get("display_name", String::class.java)!!,
email = record.get("email", String::class.java),
department = ref(record.get("department_id", UUID::class.java), record.get("department_name", String::class.java)),
position = ref(record.get("position_id", UUID::class.java), record.get("position_name", String::class.java)),
roles = roles,
)
}
private fun ref(id: UUID?, name: String?): OrganizationRef? =
if (id != null && name != null) OrganizationRef(id, name) else null
}
@@ -0,0 +1,20 @@
package com.all8ai.aioa.shared.security
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.Customizer.withDefaults
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain
@Configuration
class SecurityConfiguration {
@Bean
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain = http
.csrf { it.disable() }
.authorizeHttpRequests {
it.requestMatchers("/actuator/health", "/actuator/info").permitAll()
.anyRequest().authenticated()
}
.oauth2ResourceServer { it.jwt(withDefaults()) }
.build()
}
@@ -0,0 +1,9 @@
package com.all8ai.aioa.shared.web
import org.springframework.http.HttpStatus
class ApiException(
val status: HttpStatus,
val code: String,
override val message: String,
) : RuntimeException(message)
@@ -0,0 +1,48 @@
package com.all8ai.aioa.shared.web
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.ConstraintViolationException
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.http.HttpStatus
import org.springframework.http.ProblemDetail
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import java.net.URI
@RestControllerAdvice
class GlobalExceptionHandler {
private val logger = LoggerFactory.getLogger(javaClass)
@ExceptionHandler(ApiException::class)
fun handleApiException(exception: ApiException, request: HttpServletRequest): ResponseEntity<ProblemDetail> =
response(exception.status, exception.code, exception.message, request)
@ExceptionHandler(MethodArgumentNotValidException::class, ConstraintViolationException::class)
fun handleValidation(exception: Exception, request: HttpServletRequest): ResponseEntity<ProblemDetail> =
response(HttpStatus.BAD_REQUEST, "REQUEST_INVALID", exception.message ?: "请求参数无效", request)
@ExceptionHandler(Exception::class)
fun handleUnexpected(exception: Exception, request: HttpServletRequest): ResponseEntity<ProblemDetail> {
logger.error("Unhandled request error", exception)
return response(HttpStatus.INTERNAL_SERVER_ERROR, "INTERNAL_ERROR", "服务器处理请求失败", request)
}
private fun response(
status: HttpStatus,
code: String,
detail: String,
request: HttpServletRequest,
): ResponseEntity<ProblemDetail> {
val problem = ProblemDetail.forStatusAndDetail(status, detail).apply {
type = URI.create("https://aioa.all8ai.com/problems/${code.lowercase().replace('_', '-')}")
title = status.reasonPhrase
instance = URI.create(request.requestURI)
setProperty("code", code)
setProperty("traceId", MDC.get(TraceIdFilter.MDC_TRACE_ID) ?: "unknown")
}
return ResponseEntity.status(status).body(problem)
}
}
@@ -0,0 +1,39 @@
package com.all8ai.aioa.shared.web
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.MDC
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import java.util.UUID
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class TraceIdFilter : OncePerRequestFilter() {
override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain,
) {
val traceId = request.getHeader(TRACE_ID_HEADER)
?.takeIf { TRACE_ID_PATTERN.matches(it) }
?: UUID.randomUUID().toString()
MDC.put(MDC_TRACE_ID, traceId)
response.setHeader(TRACE_ID_HEADER, traceId)
try {
filterChain.doFilter(request, response)
} finally {
MDC.remove(MDC_TRACE_ID)
}
}
companion object {
const val TRACE_ID_HEADER = "X-Trace-Id"
const val MDC_TRACE_ID = "traceId"
private val TRACE_ID_PATTERN = Regex("[A-Za-z0-9._:-]{8,128}")
}
}
@@ -0,0 +1,40 @@
spring:
application:
name: aioa-backend
datasource:
url: ${DB_URL:jdbc:postgresql://127.0.0.1:15432/aioa}
username: ${DB_USER:aioa}
password: ${DB_PASSWORD:change-me}
hikari:
maximum-pool-size: ${DB_POOL_SIZE:10}
minimum-idle: 1
flyway:
enabled: true
locations: classpath:db/migration
jooq:
sql-dialect: postgres
security:
oauth2:
resourceserver:
jwt:
issuer-uri: ${OIDC_ISSUER_URI:http://localhost:8081/realms/aioa}
server:
port: ${SERVER_PORT:8080}
shutdown: graceful
error:
include-message: never
management:
endpoints:
web:
exposure:
include: health,info,prometheus
endpoint:
health:
probes:
enabled: true
logging:
pattern:
correlation: "[traceId=%X{traceId:-}] "
@@ -0,0 +1,30 @@
CREATE SCHEMA IF NOT EXISTS identity;
CREATE SCHEMA IF NOT EXISTS organization;
CREATE SCHEMA IF NOT EXISTS authz;
CREATE SCHEMA IF NOT EXISTS workflow;
CREATE SCHEMA IF NOT EXISTS form;
CREATE SCHEMA IF NOT EXISTS business;
CREATE SCHEMA IF NOT EXISTS knowledge;
CREATE SCHEMA IF NOT EXISTS integration;
CREATE SCHEMA IF NOT EXISTS audit;
CREATE SCHEMA IF NOT EXISTS flowable;
CREATE TABLE audit.event (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL,
actor_id UUID NOT NULL,
action VARCHAR(120) NOT NULL,
resource_type VARCHAR(120) NOT NULL,
resource_id VARCHAR(200),
trace_id VARCHAR(128) NOT NULL,
idempotency_key VARCHAR(128),
result VARCHAR(32) NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
details JSONB NOT NULL DEFAULT '{}'::jsonb
);
CREATE INDEX idx_audit_event_tenant_time
ON audit.event (tenant_id, occurred_at DESC);
CREATE INDEX idx_audit_event_trace
ON audit.event (trace_id);
@@ -0,0 +1,103 @@
CREATE TABLE identity.tenant (
id UUID PRIMARY KEY,
code VARCHAR(64) NOT NULL UNIQUE,
name VARCHAR(200) NOT NULL,
status VARCHAR(32) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
version BIGINT NOT NULL DEFAULT 0
);
CREATE TABLE organization.department (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES identity.tenant(id),
parent_id UUID REFERENCES organization.department(id),
code VARCHAR(64) NOT NULL,
name VARCHAR(200) NOT NULL,
status VARCHAR(32) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
version BIGINT NOT NULL DEFAULT 0,
UNIQUE (tenant_id, code),
UNIQUE (tenant_id, id)
);
CREATE TABLE organization.position (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES identity.tenant(id),
code VARCHAR(64) NOT NULL,
name VARCHAR(200) NOT NULL,
status VARCHAR(32) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
version BIGINT NOT NULL DEFAULT 0,
UNIQUE (tenant_id, code),
UNIQUE (tenant_id, id)
);
CREATE TABLE identity.user_account (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES identity.tenant(id),
keycloak_subject VARCHAR(100) NOT NULL,
username VARCHAR(100) NOT NULL,
display_name VARCHAR(200) NOT NULL,
email VARCHAR(320),
status VARCHAR(32) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
version BIGINT NOT NULL DEFAULT 0,
UNIQUE (tenant_id, keycloak_subject),
UNIQUE (tenant_id, username),
UNIQUE (tenant_id, id)
);
CREATE TABLE organization.user_assignment (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES identity.tenant(id),
user_id UUID NOT NULL,
department_id UUID NOT NULL,
position_id UUID,
is_primary BOOLEAN NOT NULL DEFAULT FALSE,
effective_from TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
effective_until TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_assignment_user FOREIGN KEY (tenant_id, user_id)
REFERENCES identity.user_account(tenant_id, id),
CONSTRAINT fk_assignment_department FOREIGN KEY (tenant_id, department_id)
REFERENCES organization.department(tenant_id, id),
CONSTRAINT fk_assignment_position FOREIGN KEY (tenant_id, position_id)
REFERENCES organization.position(tenant_id, id)
);
CREATE UNIQUE INDEX uq_user_primary_assignment
ON organization.user_assignment (tenant_id, user_id)
WHERE is_primary = TRUE AND effective_until IS NULL;
CREATE TABLE authz.role (
id UUID PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES identity.tenant(id),
code VARCHAR(100) NOT NULL,
name VARCHAR(200) NOT NULL,
status VARCHAR(32) NOT NULL,
UNIQUE (tenant_id, code),
UNIQUE (tenant_id, id)
);
CREATE TABLE authz.user_role (
tenant_id UUID NOT NULL REFERENCES identity.tenant(id),
user_id UUID NOT NULL,
role_id UUID NOT NULL,
effective_from TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
effective_until TIMESTAMPTZ,
PRIMARY KEY (tenant_id, user_id, role_id),
CONSTRAINT fk_user_role_user FOREIGN KEY (tenant_id, user_id)
REFERENCES identity.user_account(tenant_id, id),
CONSTRAINT fk_user_role_role FOREIGN KEY (tenant_id, role_id)
REFERENCES authz.role(tenant_id, id)
);
CREATE INDEX idx_user_account_subject
ON identity.user_account (tenant_id, keycloak_subject);
CREATE INDEX idx_assignment_department
ON organization.user_assignment (tenant_id, department_id);
@@ -0,0 +1,37 @@
INSERT INTO identity.tenant (id, code, name, status)
VALUES ('00000000-0000-7000-8000-000000000001', 'demo', 'AIOA 演示组织', 'ACTIVE');
INSERT INTO organization.department (id, tenant_id, code, name, status)
VALUES ('20000000-0000-7000-8000-000000000001', '00000000-0000-7000-8000-000000000001', 'product', '产品研发部', 'ACTIVE');
INSERT INTO organization.position (id, tenant_id, code, name, status)
VALUES
('30000000-0000-7000-8000-000000000001', '00000000-0000-7000-8000-000000000001', 'employee', '员工', 'ACTIVE'),
('30000000-0000-7000-8000-000000000002', '00000000-0000-7000-8000-000000000001', 'manager', '部门主管', 'ACTIVE'),
('30000000-0000-7000-8000-000000000003', '00000000-0000-7000-8000-000000000001', 'oa-admin', 'OA 管理员', 'ACTIVE');
INSERT INTO identity.user_account (id, tenant_id, keycloak_subject, username, display_name, email, status)
VALUES
('40000000-0000-7000-8000-000000000001', '00000000-0000-7000-8000-000000000001', '10000000-0000-7000-8000-000000000001', 'employee', '员工小明', 'employee@example.local', 'ACTIVE'),
('40000000-0000-7000-8000-000000000002', '00000000-0000-7000-8000-000000000001', '10000000-0000-7000-8000-000000000002', 'manager', '王主管', 'manager@example.local', 'ACTIVE'),
('40000000-0000-7000-8000-000000000003', '00000000-0000-7000-8000-000000000001', '10000000-0000-7000-8000-000000000003', 'admin', 'OA 管理员', 'admin@example.local', 'ACTIVE');
INSERT INTO organization.user_assignment (id, tenant_id, user_id, department_id, position_id, is_primary)
VALUES
('50000000-0000-7000-8000-000000000001', '00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000001', '20000000-0000-7000-8000-000000000001', '30000000-0000-7000-8000-000000000001', TRUE),
('50000000-0000-7000-8000-000000000002', '00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000002', '20000000-0000-7000-8000-000000000001', '30000000-0000-7000-8000-000000000002', TRUE),
('50000000-0000-7000-8000-000000000003', '00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000003', '20000000-0000-7000-8000-000000000001', '30000000-0000-7000-8000-000000000003', TRUE);
INSERT INTO authz.role (id, tenant_id, code, name, status)
VALUES
('60000000-0000-7000-8000-000000000001', '00000000-0000-7000-8000-000000000001', 'employee', '普通员工', 'ACTIVE'),
('60000000-0000-7000-8000-000000000002', '00000000-0000-7000-8000-000000000001', 'department_manager', '部门主管', 'ACTIVE'),
('60000000-0000-7000-8000-000000000003', '00000000-0000-7000-8000-000000000001', 'oa_admin', 'OA 管理员', 'ACTIVE');
INSERT INTO authz.user_role (tenant_id, user_id, role_id)
VALUES
('00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000001', '60000000-0000-7000-8000-000000000001'),
('00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000002', '60000000-0000-7000-8000-000000000001'),
('00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000002', '60000000-0000-7000-8000-000000000002'),
('00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000003', '60000000-0000-7000-8000-000000000001'),
('00000000-0000-7000-8000-000000000001', '40000000-0000-7000-8000-000000000003', '60000000-0000-7000-8000-000000000003');
@@ -0,0 +1,55 @@
package com.all8ai.aioa.identity.application
import com.all8ai.aioa.identity.domain.CurrentUser
import com.all8ai.aioa.identity.domain.CurrentUserRepository
import com.all8ai.aioa.shared.web.ApiException
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.springframework.http.HttpStatus
import java.util.UUID
class CurrentUserServiceTest {
private val tenantId = UUID.fromString("00000000-0000-7000-8000-000000000001")
@Test
fun `loads provisioned user within claimed tenant`() {
val expected = CurrentUser(
id = UUID.randomUUID(),
tenantId = tenantId,
username = "employee",
displayName = "员工小明",
email = null,
department = null,
position = null,
roles = setOf("employee"),
)
val service = CurrentUserService(CurrentUserRepository { actualTenant, subject ->
expected.takeIf { actualTenant == tenantId && subject == "subject-1" }
})
assertThat(service.get("subject-1", tenantId.toString())).isEqualTo(expected)
}
@Test
fun `rejects missing tenant claim`() {
val service = CurrentUserService(CurrentUserRepository { _, _ -> null })
assertThatThrownBy { service.get("subject-1", null) }
.isInstanceOfSatisfying(ApiException::class.java) {
assertThat(it.status).isEqualTo(HttpStatus.FORBIDDEN)
assertThat(it.code).isEqualTo("TENANT_CLAIM_MISSING")
}
}
@Test
fun `rejects user not provisioned in claimed tenant`() {
val service = CurrentUserService(CurrentUserRepository { _, _ -> null })
assertThatThrownBy { service.get("unknown", tenantId.toString()) }
.isInstanceOfSatisfying(ApiException::class.java) {
assertThat(it.status).isEqualTo(HttpStatus.FORBIDDEN)
assertThat(it.code).isEqualTo("USER_NOT_PROVISIONED")
}
}
}
@@ -0,0 +1,36 @@
package com.all8ai.aioa.shared.web
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
class TraceIdFilterTest {
private val filter = TraceIdFilter()
@Test
fun `preserves a valid client trace id`() {
val request = MockHttpServletRequest().apply {
addHeader(TraceIdFilter.TRACE_ID_HEADER, "client-trace-123")
}
val response = MockHttpServletResponse()
filter.doFilter(request, response, MockFilterChain())
assertThat(response.getHeader(TraceIdFilter.TRACE_ID_HEADER)).isEqualTo("client-trace-123")
}
@Test
fun `replaces an invalid client trace id`() {
val request = MockHttpServletRequest().apply {
addHeader(TraceIdFilter.TRACE_ID_HEADER, "bad value")
}
val response = MockHttpServletResponse()
filter.doFilter(request, response, MockFilterChain())
assertThat(response.getHeader(TraceIdFilter.TRACE_ID_HEADER))
.matches("[0-9a-f-]{36}")
}
}
+11
View File
@@ -0,0 +1,11 @@
plugins {
id("org.springframework.boot") version "3.5.3" apply false
id("io.spring.dependency-management") version "1.1.7" apply false
kotlin("jvm") version "2.1.21" apply false
kotlin("plugin.spring") version "2.1.21" apply false
}
allprojects {
group = "com.all8ai.aioa"
version = "0.1.0-SNAPSHOT"
}
+4
View File
@@ -0,0 +1,4 @@
org.gradle.configuration-cache=true
org.gradle.caching=true
org.gradle.parallel=true
kotlin.code.style=official
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+82
View File
@@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute Gradle
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+16
View File
@@ -0,0 +1,16 @@
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
}
}
rootProject.name = "aioa-backend"
include("boot")