diff --git a/README.md b/README.md index d8623a8..155d211 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,10 @@ specification; development agents read exactly the version that was approved, th allowed to use the app from the identity provider's directory (Keycloak or Microsoft Entra ID). - **Roles across projects:** select an existing role or create one, then describe what it does in this project. +- **Non-functional requirements baseline:** global NFRs (`BL-01`, …) by category such as performance, availability, + security or usability. Every project shows them as read-only items next to its own NFRs, and the PRD export + includes them. They are not part of project versions, so changing the baseline never changes a project's state. + Only users with the application role `ARCHITECT` maintain it (see [Identity provider](#identity-provider)). - **Whole-project review:** reviewers accept, request changes or reject a frozen candidate, and can suggest wording on any element. Authors apply or dismiss suggestions afterwards. - **Immutable versions:** approval turns the candidate into `v1`, `v2`, … A database trigger keeps approved @@ -81,9 +85,13 @@ specification; development agents read exactly the version that was approved, th |---|---| | ![Review](docs/images/review.png) | ![Compare](docs/images/compare.png) | -| Requirement with diagram, traceability and external links | +| Requirement with diagram, traceability and external links | Projects and what needs your attention | +|---|---| +| ![Requirement](docs/images/element.png) | ![Projects](docs/images/home.png) | + +| Non-functional requirements baseline, inherited by every project | |---| -| ![Requirement](docs/images/element.png) | +| ![Baseline](docs/images/baseline.png) | ## Architecture @@ -133,6 +141,7 @@ Open and sign in as `owner1` / `password`. | `owner2`, `contrib1` | second owner, contributor | | `reviewer1`, `reviewer2` | reviewers | | `viewer1` | read-only user | +| `architect1` | architect: maintains the NFR baseline | All passwords are `password`. Local services: @@ -225,13 +234,14 @@ agents that assess requirements, suggest improvements or build a backlog with th | Tool | Returns | |---|---| | `list_projects` | projects, owners, state, tags, domains | -| `get_prd` | the whole specification as one Markdown PRD | -| `search_requirements` | elements by type, tag or text | -| `get_requirement` | one element with traceability and external links | +| `get_prd` | the whole specification as one Markdown PRD, including the NFR baseline | +| `search_requirements` | elements by type, tag or text, plus matching baseline NFRs (project `baseline`) | +| `get_requirement` | one element with traceability and external links; `BL-` keys work with any project | | `get_traceability` | BR → SR → FR/NFR → scenario graph, with its gaps | | `list_versions`, `diff_versions` | version history and unified diffs | | `get_review_status` | reviewers, decisions, open suggestions | | `get_external_links`, `list_roles` | JIRA / ADO references, shared roles | +| `list_baseline_requirements` | the NFR baseline, optionally by category or text | - **Approved by default:** tools return the latest approved version unless `version` is `"2"`, `"3-rc1"` or `"draft"`, so agents never build on unreviewed work by accident. @@ -406,6 +416,8 @@ still be overridden with the variable. | `REQLITH_IDP_AUTHORIZATION_URI`, `_TOKEN_URI`, `_JWKS_URI`, `_USER_INFO_URI`, `_END_SESSION_URI` | `GENERIC` only (first three) | derived from the type | endpoint overrides | | `REQLITH_IDP_MCP_AUDIENCE` | no | not checked | required `aud` of IDP access tokens at `/mcp` (Entra: the API's application ID URI) | | `REQLITH_IDP_DIRECTORY` | no | `KEYCLOAK` (`NONE` otherwise) | invitation suggestions: `NONE`, `KEYCLOAK`, `ENTRA` or `ENTRA_ASSIGNED` | +| `REQLITH_IDP_ROLES_CLAIM` | no | `roles` | token claim with the user's IDP roles; dotted names reach nested claims (`realm_access.roles`) | +| `REQLITH_IDP_ARCHITECT_ROLES` | no | `ARCHITECT` | IDP roles (comma-separated, case-insensitive) that grant the application role `ARCHITECT` | | `MANAGEMENT_PORT` | no | `8081` | actuator port | | `LOGGING_LEVEL_IO_REQLITH` | no | `DEBUG` (`INFO` otherwise) | application log level | @@ -427,6 +439,10 @@ from the issuer. Every endpoint can be overridden with `REQLITH_IDP_*_URI`. User e-mail addresses (used to match invitations) come from the `email` claim. When that claim is missing, as it often is with Entra, they come from `preferred_username` or `upn` if those are addresses. +**Application roles** come from the claim `REQLITH_IDP_ROLES_CLAIM` (default `roles`) at sign-in. A user holding +one of `REQLITH_IDP_ARCHITECT_ROLES` becomes an `ARCHITECT` and may maintain the NFR baseline. Project roles +(owner, contributor, reviewer) are managed in Reqlith itself. A changed role takes effect at the next sign-in. + **Invitation suggestions** always include users who have signed in before. With a directory, everyone allowed to use the app can be suggested, which also shows those names and addresses to every signed-in user. @@ -440,6 +456,10 @@ the app can be suggested, which also shows those names and addresses to every si admin API (26.4+) requires it, and Reqlith requests it only for directory calls. Suggestions list the realm's enabled users. - **MCP over OAuth:** a public client for MCP clients (the local realm has `reqlith-mcp`). +- **Architects:** create the realm role `ARCHITECT` and assign it. Add a *User Realm Role* mapper to the client + with token claim name `roles`, multivalued, added to the ID token (the local realm does this, and `architect1` + has the role). To use Keycloak's built-in `realm_access.roles` instead, switch on *Add to ID token* for the + *realm roles* mapper of the `roles` client scope and set `REQLITH_IDP_ROLES_CLAIM=realm_access.roles`. @@ -461,6 +481,9 @@ the app can be suggested, which also shows those names and addresses to every si `api://reqlith`) and a scope. In the manifest, set `requestedAccessTokenVersion` (or `accessTokenAcceptedVersion`) to `2` so access tokens carry the v2 issuer. Set `REQLITH_IDP_MCP_AUDIENCE` to the audience of those tokens (usually the application ID URI or client id). Personal access tokens work regardless. +6. **Architects (optional):** under *App roles*, create a role with value `ARCHITECT` for users/groups and assign + it in the enterprise application. Entra puts assigned app roles in the ID token's `roles` claim. If your role + has another value, set `REQLITH_IDP_ARCHITECT_ROLES` to it. ```bash REQLITH_IDP_TYPE=ENTRA diff --git a/docs/images/baseline.png b/docs/images/baseline.png new file mode 100644 index 0000000..e893415 Binary files /dev/null and b/docs/images/baseline.png differ diff --git a/docs/images/compare.png b/docs/images/compare.png index 2ab11e2..9c5e58e 100644 Binary files a/docs/images/compare.png and b/docs/images/compare.png differ diff --git a/docs/images/element.png b/docs/images/element.png index a20b46a..d7b9d45 100644 Binary files a/docs/images/element.png and b/docs/images/element.png differ diff --git a/docs/images/home.png b/docs/images/home.png new file mode 100644 index 0000000..875c5b9 Binary files /dev/null and b/docs/images/home.png differ diff --git a/docs/images/overview.png b/docs/images/overview.png index 2940a03..8d231fc 100644 Binary files a/docs/images/overview.png and b/docs/images/overview.png differ diff --git a/docs/images/review.png b/docs/images/review.png index fd7d9b7..4f24021 100644 Binary files a/docs/images/review.png and b/docs/images/review.png differ diff --git a/src/main/dev/keycloak/reqlith-realm.json b/src/main/dev/keycloak/reqlith-realm.json index be31567..c8932b3 100644 --- a/src/main/dev/keycloak/reqlith-realm.json +++ b/src/main/dev/keycloak/reqlith-realm.json @@ -5,6 +5,14 @@ "sslRequired": "none", "registrationAllowed": false, "loginWithEmailAllowed": true, + "roles": { + "realm": [ + { + "name": "ARCHITECT", + "description": "Maintains the Reqlith non-functional requirements baseline" + } + ] + }, "clients": [ { "clientId": "reqlith-app", @@ -36,6 +44,23 @@ ], "optionalClientScopes": [ "kc-admin-api" + ], + "protocolMappers": [ + { + "name": "realm roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-realm-role-mapper", + "consentRequired": false, + "config": { + "multivalued": "true", + "claim.name": "roles", + "jsonType.label": "String", + "id.token.claim": "true", + "access.token.claim": "true", + "userinfo.token.claim": "true", + "introspection.token.claim": "true" + } + } ] }, { @@ -180,6 +205,26 @@ "default-roles-reqlith" ] }, + { + "id": "8e3b6f0a-2c4d-4b7e-9a51-6d2f0c9e7b13", + "username": "architect1", + "email": "architect1@reqlith.local", + "firstName": "Ada", + "lastName": "Archer", + "enabled": true, + "emailVerified": true, + "credentials": [ + { + "type": "password", + "value": "password", + "temporary": false + } + ], + "realmRoles": [ + "default-roles-reqlith", + "ARCHITECT" + ] + }, { "username": "service-account-reqlith-app", "enabled": true, diff --git a/src/main/dev/scripts/podman-dev.sh b/src/main/dev/scripts/podman-dev.sh index 74f0b0f..4d0ac0a 100755 --- a/src/main/dev/scripts/podman-dev.sh +++ b/src/main/dev/scripts/podman-dev.sh @@ -90,7 +90,7 @@ up() { fi echo "MSSQL localhost:1433 (db reqlith, user reqlith_app)" - echo "Keycloak http://localhost:8180 (admin/admin, realm reqlith, users owner1..viewer1 / password)" + echo "Keycloak http://localhost:8180 (admin/admin, realm reqlith, users owner1..viewer1, architect1 / password)" echo "Renderer http://localhost:3000 (Gotenberg, PDF export)" $with_app && echo "App http://localhost:8080 (actuator on http://localhost:8081/actuator)" return 0 diff --git a/src/main/kotlin/io/reqlith/config/ReqlithProperties.kt b/src/main/kotlin/io/reqlith/config/ReqlithProperties.kt index 0f95022..aab309c 100644 --- a/src/main/kotlin/io/reqlith/config/ReqlithProperties.kt +++ b/src/main/kotlin/io/reqlith/config/ReqlithProperties.kt @@ -41,6 +41,10 @@ data class ReqlithProperties( val directory: DirectoryType = DirectoryType.NONE, /** Required `aud` of IDP access tokens sent to /mcp (Entra: the API's application ID URI); blank = not checked. */ val mcpAudience: String? = null, + /** Claim with the user's IDP roles (Keycloak realm roles mapped to `roles`; Entra app roles). Dotted names reach nested claims. */ + val rolesClaim: String = "roles", + /** IDP roles that make a user an architect, who maintains the non-functional requirements baseline. */ + val architectRoles: List = listOf("ARCHITECT"), ) enum class IdpType { diff --git a/src/main/kotlin/io/reqlith/controller/BaselineController.kt b/src/main/kotlin/io/reqlith/controller/BaselineController.kt new file mode 100644 index 0000000..4b270b9 --- /dev/null +++ b/src/main/kotlin/io/reqlith/controller/BaselineController.kt @@ -0,0 +1,76 @@ +package io.reqlith.controller + +import io.reqlith.exception.ValidationException +import io.reqlith.model.dto.CurrentUser +import io.reqlith.model.entity.BaselineCategory +import io.reqlith.service.BaselineService +import io.reqlith.service.MarkdownRenderer +import org.springframework.security.core.annotation.AuthenticationPrincipal +import org.springframework.stereotype.Controller +import org.springframework.ui.Model +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestParam + +/** The non-functional requirements baseline: everyone reads it, architects maintain it. */ +@Controller +class BaselineController(private val baseline: BaselineService, private val markdown: MarkdownRenderer) { + + @GetMapping("/baseline") + fun list(@AuthenticationPrincipal user: CurrentUser, model: Model): String { + model.addAttribute("baseline", baseline.all().groupBy { it.category }) + model.addAttribute("categories", BaselineCategory.entries) + model.addAttribute("canEdit", baseline.canEdit(user)) + return "baseline/list" + } + + @PostMapping("/baseline") + fun create( + @AuthenticationPrincipal user: CurrentUser, + @RequestParam category: BaselineCategory, + @RequestParam title: String, + @RequestParam(required = false) body: String?, + model: Model, + ): String = try { + "redirect:/baseline/${baseline.create(user, category, title, body).key}" + } catch (e: ValidationException) { + model.addAttribute("error", e) + model.addAttribute("newCategory", category) + model.addAttribute("newTitle", title) + model.addAttribute("newBody", body) + list(user, model) + } + + @GetMapping("/baseline/{key}") + fun show(@AuthenticationPrincipal user: CurrentUser, @PathVariable key: String, model: Model): String { + val requirement = baseline.get(key) + model.addAttribute("requirement", requirement) + model.addAttribute("bodyHtml", markdown.render(requirement.bodyMd)) + model.addAttribute("categories", BaselineCategory.entries) + model.addAttribute("canEdit", baseline.canEdit(user)) + return "baseline/show" + } + + @PostMapping("/baseline/{key}") + fun update( + @AuthenticationPrincipal user: CurrentUser, + @PathVariable key: String, + @RequestParam category: BaselineCategory, + @RequestParam title: String, + @RequestParam(required = false) body: String?, + model: Model, + ): String = try { + baseline.update(user, baseline.get(key), category, title, body) + "redirect:/baseline/$key" + } catch (e: ValidationException) { + model.addAttribute("error", e) + show(user, key, model) + } + + @PostMapping("/baseline/{key}/delete") + fun delete(@AuthenticationPrincipal user: CurrentUser, @PathVariable key: String): String { + baseline.delete(user, baseline.get(key)) + return "redirect:/baseline" + } +} diff --git a/src/main/kotlin/io/reqlith/controller/ProjectController.kt b/src/main/kotlin/io/reqlith/controller/ProjectController.kt index ce169e5..3eea6b0 100644 --- a/src/main/kotlin/io/reqlith/controller/ProjectController.kt +++ b/src/main/kotlin/io/reqlith/controller/ProjectController.kt @@ -115,6 +115,7 @@ class ProjectController( model.addAttribute("document", document) model.addAttribute("changes", changesSinceApproval(project, document)) model.addAttribute("html", RenderedDocument.of(document) { support.render(it, project, document) }) + model.addAttribute("baselineHtml", support.renderBaseline()) model.addAttribute("types", ElementType.entries) model.addAttribute("incoming", document.incomingLinks()) return "project/document" diff --git a/src/main/kotlin/io/reqlith/controller/ProjectViewSupport.kt b/src/main/kotlin/io/reqlith/controller/ProjectViewSupport.kt index f64001c..f5e0126 100644 --- a/src/main/kotlin/io/reqlith/controller/ProjectViewSupport.kt +++ b/src/main/kotlin/io/reqlith/controller/ProjectViewSupport.kt @@ -8,6 +8,7 @@ import io.reqlith.model.entity.ElementType import io.reqlith.model.entity.MemberRole import io.reqlith.model.entity.Project import io.reqlith.model.entity.ProjectStatus +import io.reqlith.service.BaselineService import io.reqlith.service.MarkdownRenderer import io.reqlith.service.MembershipService import io.reqlith.service.ProjectAccess @@ -30,6 +31,7 @@ class ProjectViewSupport( private val versions: VersionService, private val reviews: ReviewService, private val codec: SnapshotCodec, + private val baseline: BaselineService, ) { fun populate(model: Model, project: Project, user: CurrentUser, document: ProjectDocument, active: String) { val role = access.roleOf(project, user) @@ -44,7 +46,9 @@ class ProjectViewSupport( model.addAttribute("locked", project.status == ProjectStatus.IN_REVIEW) model.addAttribute("owners", owners) model.addAttribute("active", active) - model.addAttribute("sections", sections(project, document)) + val baselineItems = baseline.all() + model.addAttribute("baseline", baselineItems) + model.addAttribute("sections", sections(project, document, baselineItems.size)) val state = state(project, document) model.addAttribute("stateLabel", state.first) model.addAttribute("stateClass", state.second) @@ -84,7 +88,10 @@ class ProjectViewSupport( ?: document.role(key)?.let { Reference("/roles/$key", "$key · ${it.name}") } } - private fun sections(project: Project, document: ProjectDocument): List { + /** Baseline descriptions rendered for the document views (key to HTML). */ + fun renderBaseline(): Map = baseline.all().associate { it.key to markdown.render(it.bodyMd) } + + private fun sections(project: Project, document: ProjectDocument, baselineCount: Int): List { val base = "/p/${project.key}" val basic = listOf( NavSection("Problem statement", null, "$base/draft/document#problem-statement", "problem"), @@ -94,6 +101,7 @@ class ProjectViewSupport( fun typed(type: ElementType) = NavSection(type.section, document.elementsOf(type).size, "$base/draft?type=${type.name}", type.name) return basic + listOf( typed(ElementType.BR), typed(ElementType.SR), typed(ElementType.FR), typed(ElementType.NFR), + NavSection("Baseline NFRs", baselineCount, "$base/draft/document#baseline", "baseline"), typed(ElementType.AS), typed(ElementType.RK), NavSection("Roles", document.roles.size, "$base/roles", "roles"), typed(ElementType.SC), typed(ElementType.DP), diff --git a/src/main/kotlin/io/reqlith/controller/ReqlithMcpTools.kt b/src/main/kotlin/io/reqlith/controller/ReqlithMcpTools.kt index 278bc56..30b34e9 100644 --- a/src/main/kotlin/io/reqlith/controller/ReqlithMcpTools.kt +++ b/src/main/kotlin/io/reqlith/controller/ReqlithMcpTools.kt @@ -7,6 +7,8 @@ import io.reqlith.config.ReqlithProperties import io.reqlith.exception.NotFoundException import io.reqlith.exception.ValidationException import io.reqlith.model.dto.ApprovalRow +import io.reqlith.model.dto.BaselineItem +import io.reqlith.model.dto.BaselineRow import io.reqlith.model.dto.ChangeKind import io.reqlith.model.dto.DocElement import io.reqlith.model.dto.ExportOptions @@ -30,6 +32,7 @@ import io.reqlith.model.dto.Traceability import io.reqlith.model.dto.VersionDiff import io.reqlith.model.dto.VersionRow import io.reqlith.model.dto.VersionSummary +import io.reqlith.model.entity.BaselineCategory import io.reqlith.model.entity.ElementType import io.reqlith.model.entity.Suggestion import io.reqlith.repository.McpAccessLog @@ -75,7 +78,8 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess @McpTool( name = "get_prd", description = "The whole specification of a project as one PRD in Markdown " + - "(basic information, business, stakeholder and solution requirements, roles, scenarios, solution design, traceability).", + "(basic information, business, stakeholder and solution requirements including the NFR baseline, roles, scenarios, " + + "solution design, traceability).", annotations = McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false, idempotentHint = true), ) fun getPrd( @@ -114,6 +118,7 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess ) }, notes = notes, + baseline = read.baseline().map { BaselineItem(it.key, it.category, it.title, it.bodyMarkdown) }, ) PrdMarkdownWriter.write(input, ExportOptions(traceabilityMatrix = true, approvalRecord = true, reviewComments = includeReviewComments == true)) } @@ -121,7 +126,8 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess @McpTool( name = "search_requirements", description = "Find requirements, scenarios, assumptions, risks and dependencies by type, tag or text. " + - "Searches the latest approved version of each project unless a version is given.", + "Searches the latest approved version of each project unless a version is given. Without a type or with type NFR, " + + "matching baseline non-functional requirements (keys BL-…, project \"baseline\") are included: they apply to every project.", annotations = McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false, idempotentHint = true), ) fun searchRequirements( @@ -150,18 +156,30 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess } else { read.projects().filter { it.latestApprovedVersion != null }.map { read.document(it, null) } } - sources.flatMap { doc -> + val projectHits = sources.flatMap { doc -> doc.document.elements.filter { e -> (wantedType == null || e.type == wantedType) && (wantedTag.isNullOrEmpty() || e.tags.any { it.lowercase() == wantedTag }) && (needle.isEmpty() || listOf(e.key, e.title, e.body.orEmpty()).any { it.lowercase().contains(needle) }) }.map { e -> hit(doc.document.project.key, doc.label, e, needle) } - }.take(200) + } + // Baseline requirements have no tags, so a tag search never matches them. + val baselineHits = if ((wantedType == null || wantedType == ElementType.NFR) && wantedTag.isNullOrEmpty()) { + read.baseline().filter { b -> + needle.isEmpty() || + listOf(b.key, b.title, b.category, b.bodyMarkdown.orEmpty()).any { it.lowercase().contains(needle) } + } + .map { b -> RequirementHit(BASELINE, CURRENT_BASELINE, b.key, baselineType(b), b.title, null, emptyList(), excerpt(b.bodyMarkdown, needle)) } + } else { + emptyList() + } + (projectHits + baselineHits).take(200) } @McpTool( name = "get_requirement", - description = "One element with its Markdown body, priority, tags, traceability in both directions and external links (JIRA, ADO).", + description = "One element with its Markdown body, priority, tags, traceability in both directions and external links (JIRA, ADO). " + + "Baseline keys (BL-…) work with any project key: the baseline applies to every project.", annotations = McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false, idempotentHint = true), ) fun getRequirement( @@ -172,8 +190,17 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess ): RequirementDetail = tool("get_requirement") { val p = read.project(project) audit(context, "get_requirement", p.key, mapOf("key" to key, "version" to version)) + val wanted = key.trim().uppercase() + if (wanted.startsWith("BL-")) { + val b = read.baseline().firstOrNull { it.key == wanted } ?: throw ValidationException("key", "$key is not in the baseline") + return@tool RequirementDetail( + project = p.key, version = CURRENT_BASELINE, key = b.key, type = baselineType(b), title = b.title, + priority = null, tags = emptyList(), bodyMarkdown = b.bodyMarkdown, linksTo = emptyList(), linkedFrom = emptyList(), + externalLinks = emptyList(), url = url("/baseline/${b.key}"), + ) + } val resolved = read.document(p, version) - val element = resolved.document.element(key.trim().uppercase()) + val element = resolved.document.element(wanted) ?: throw ValidationException("key", "$key is not part of ${p.key} ${resolved.label}") val incoming = resolved.document.incomingLinks()[element.key].orEmpty() RequirementDetail( @@ -326,6 +353,33 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess read.roles().filter { needle.isEmpty() || it.name.lowercase().contains(needle) || it.description.orEmpty().lowercase().contains(needle) } } + @McpTool( + name = "list_baseline_requirements", + description = "The non-functional requirements baseline: global requirements (keys BL-…) by category, e.g. performance, " + + "availability, security, usability. Every project inherits them; they are maintained by architects and not versioned with projects.", + annotations = McpTool.McpAnnotations(readOnlyHint = true, destructiveHint = false, idempotentHint = true), + ) + fun listBaselineRequirements( + @McpToolParam( + description = "Optional category: PERFORMANCE, AVAILABILITY, RELIABILITY, SCALABILITY, SECURITY, USABILITY, " + + "ACCESSIBILITY, MAINTAINABILITY, COMPLIANCE or OTHER", + required = false, + ) category: String?, + @McpToolParam(description = "Optional text to match in key, title or description", required = false) query: String?, + context: McpSyncRequestContext, + ): List = tool("list_baseline_requirements") { + audit(context, "list_baseline_requirements", null, mapOf("category" to category, "query" to query)) + val wantedCategory = category?.trim()?.uppercase()?.takeIf { it.isNotEmpty() }?.let { + runCatching { BaselineCategory.valueOf(it) } + .getOrElse { throw ValidationException("category", "Unknown category $category. Use one of ${BaselineCategory.entries.joinToString()}") } + } + val needle = query?.trim()?.lowercase().orEmpty() + read.baseline().filter { b -> + (wantedCategory == null || b.category == wantedCategory.label) && + (needle.isEmpty() || listOf(b.key, b.title, b.bodyMarkdown.orEmpty()).any { it.lowercase().contains(needle) }) + } + } + // ------------------------------------------------------------------ helpers /** @@ -375,13 +429,17 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess } } - private fun hit(project: String, version: String, e: DocElement, needle: String): RequirementHit { - val body = e.body.orEmpty().replace(Regex("\\s+"), " ").trim() + private fun hit(project: String, version: String, e: DocElement, needle: String): RequirementHit = + RequirementHit(project, version, e.key, e.type.label, e.title, e.priority?.label, e.tags, excerpt(e.body, needle)) + + private fun excerpt(markdown: String?, needle: String): String { + val body = markdown.orEmpty().replace(Regex("\\s+"), " ").trim() val at = if (needle.isEmpty()) 0 else body.lowercase().indexOf(needle).coerceAtLeast(0) - val excerpt = body.substring((at - 60).coerceAtLeast(0), (at + 180).coerceAtMost(body.length)) - return RequirementHit(project, version, e.key, e.type.label, e.title, e.priority?.label, e.tags, excerpt) + return body.substring((at - 60).coerceAtLeast(0), (at + 180).coerceAtMost(body.length)) } + private fun baselineType(b: BaselineRow) = "Baseline non-functional requirement · ${b.category}" + private fun unified(name: String, before: String?, after: String?): String { val old = before.orEmpty().lines() val new = after.orEmpty().lines() @@ -391,4 +449,10 @@ class ReqlithMcpTools(private val read: McpReadModel, private val log: McpAccess private fun target(key: String) = Suggestion.targetLabel(key) private fun url(path: String) = properties.baseUrl.trimEnd('/') + path + + companion object { + /** Project and version reported for baseline requirements, which belong to no single project or version. */ + private const val BASELINE = "baseline" + private const val CURRENT_BASELINE = "current baseline" + } } diff --git a/src/main/kotlin/io/reqlith/controller/VersionController.kt b/src/main/kotlin/io/reqlith/controller/VersionController.kt index 1d23db2..bfbde48 100644 --- a/src/main/kotlin/io/reqlith/controller/VersionController.kt +++ b/src/main/kotlin/io/reqlith/controller/VersionController.kt @@ -53,6 +53,7 @@ class VersionController( model.addAttribute("isLatest", version.versionNo != null && version.versionNo == project.latestApprovedVersion) model.addAttribute("document", document) model.addAttribute("html", RenderedDocument.of(document) { support.renderInPage(it, document) }) + model.addAttribute("baselineHtml", support.renderBaseline()) model.addAttribute("types", ElementType.entries) model.addAttribute("incoming", document.incomingLinks()) return "project/document" diff --git a/src/main/kotlin/io/reqlith/model/dto/CurrentUser.kt b/src/main/kotlin/io/reqlith/model/dto/CurrentUser.kt index a6b9bb3..cfac3b5 100644 --- a/src/main/kotlin/io/reqlith/model/dto/CurrentUser.kt +++ b/src/main/kotlin/io/reqlith/model/dto/CurrentUser.kt @@ -8,4 +8,11 @@ interface CurrentUser { val displayName: String val initials: String val emailAddress: String? + + /** May maintain the non-functional requirements baseline (application role from the IDP, see `reqlith.idp.architect-roles`). */ + val isArchitect: Boolean get() = false + + companion object { + const val ARCHITECT_AUTHORITY = "ROLE_ARCHITECT" + } } diff --git a/src/main/kotlin/io/reqlith/model/dto/McpRecords.kt b/src/main/kotlin/io/reqlith/model/dto/McpRecords.kt index 9507ed3..65fa7f9 100644 --- a/src/main/kotlin/io/reqlith/model/dto/McpRecords.kt +++ b/src/main/kotlin/io/reqlith/model/dto/McpRecords.kt @@ -49,6 +49,9 @@ data class CommentRow(val versionId: UUID, val elementKey: String?, val author: data class LinkRow(val system: String, val url: String, val label: String, val versionNo: Int?, val elementKey: String?) +/** A baseline non-functional requirement; it applies to every project. */ +data class BaselineRow(val key: String, val category: String, val title: String, val bodyMarkdown: String?, val updatedAt: Instant) + data class RoleRow(val key: String, val name: String, val description: String?, val projects: List) /** A document and where it came from. */ diff --git a/src/main/kotlin/io/reqlith/model/dto/PrdInput.kt b/src/main/kotlin/io/reqlith/model/dto/PrdInput.kt index 16c0e6c..96832ae 100644 --- a/src/main/kotlin/io/reqlith/model/dto/PrdInput.kt +++ b/src/main/kotlin/io/reqlith/model/dto/PrdInput.kt @@ -13,6 +13,9 @@ data class ApprovalRow(val version: String, val status: String, val submitted: S /** One review comment or suggestion for the optional appendix. */ data class ReviewNote(val version: String, val target: String, val author: String, val text: String) +/** A baseline non-functional requirement as printed in the PRD. */ +data class BaselineItem(val key: String, val category: String, val title: String, val body: String?) + data class PrdInput( val document: ProjectDocument, /** "v2", "v3-rc1" or "DRAFT". */ @@ -22,4 +25,6 @@ data class PrdInput( val contentHash: String?, val approvals: List, val notes: List, + /** The current global baseline; it is not versioned with the project. */ + val baseline: List = emptyList(), ) diff --git a/src/main/kotlin/io/reqlith/model/dto/ReqlithOidcUser.kt b/src/main/kotlin/io/reqlith/model/dto/ReqlithOidcUser.kt index 79c5616..ceb838d 100644 --- a/src/main/kotlin/io/reqlith/model/dto/ReqlithOidcUser.kt +++ b/src/main/kotlin/io/reqlith/model/dto/ReqlithOidcUser.kt @@ -18,6 +18,8 @@ class ReqlithOidcUser( override val emailAddress: String? get() = email + override val isArchitect: Boolean get() = authorities.any { it.authority == CurrentUser.ARCHITECT_AUTHORITY } + companion object { private const val serialVersionUID = 1L } diff --git a/src/main/kotlin/io/reqlith/model/entity/BaselineCategory.kt b/src/main/kotlin/io/reqlith/model/entity/BaselineCategory.kt new file mode 100644 index 0000000..7439e86 --- /dev/null +++ b/src/main/kotlin/io/reqlith/model/entity/BaselineCategory.kt @@ -0,0 +1,15 @@ +package io.reqlith.model.entity + +/** Quality attribute a baseline non-functional requirement belongs to. Declaration order is display order. */ +enum class BaselineCategory(val label: String) { + PERFORMANCE("Performance"), + AVAILABILITY("Availability"), + RELIABILITY("Reliability"), + SCALABILITY("Scalability"), + SECURITY("Security"), + USABILITY("Usability"), + ACCESSIBILITY("Accessibility"), + MAINTAINABILITY("Maintainability"), + COMPLIANCE("Compliance"), + OTHER("Other"), +} diff --git a/src/main/kotlin/io/reqlith/model/entity/BaselineRequirement.kt b/src/main/kotlin/io/reqlith/model/entity/BaselineRequirement.kt new file mode 100644 index 0000000..f589868 --- /dev/null +++ b/src/main/kotlin/io/reqlith/model/entity/BaselineRequirement.kt @@ -0,0 +1,30 @@ +package io.reqlith.model.entity + +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.EnumType +import jakarta.persistence.Enumerated +import jakarta.persistence.Table +import java.time.Instant +import java.util.UUID + +/** A global non-functional requirement (BL-03) that applies to every project and is maintained by architects. */ +@Entity +@Table(name = "baseline_requirement") +class BaselineRequirement( + @Column(name = "baseline_key", nullable = false, updatable = false) + val key: String, + @Enumerated(EnumType.STRING) + @Column(nullable = false) + var category: BaselineCategory, + @Column(nullable = false) + var title: String, + @Column(name = "body_md") + var bodyMd: String?, + @Column(name = "created_at", nullable = false, updatable = false) + val createdAt: Instant, + @Column(name = "updated_at", nullable = false) + var updatedAt: Instant, + @Column(name = "updated_by", nullable = false) + var updatedBy: UUID, +) : AbstractEntity() diff --git a/src/main/kotlin/io/reqlith/repository/BaselineRequirementRepository.kt b/src/main/kotlin/io/reqlith/repository/BaselineRequirementRepository.kt new file mode 100644 index 0000000..5996f79 --- /dev/null +++ b/src/main/kotlin/io/reqlith/repository/BaselineRequirementRepository.kt @@ -0,0 +1,9 @@ +package io.reqlith.repository + +import io.reqlith.model.entity.BaselineRequirement +import org.springframework.data.jpa.repository.JpaRepository +import java.util.UUID + +interface BaselineRequirementRepository : JpaRepository { + fun findByKey(key: String): BaselineRequirement? +} diff --git a/src/main/kotlin/io/reqlith/repository/McpReadModel.kt b/src/main/kotlin/io/reqlith/repository/McpReadModel.kt index cc4c1f7..dfd692d 100644 --- a/src/main/kotlin/io/reqlith/repository/McpReadModel.kt +++ b/src/main/kotlin/io/reqlith/repository/McpReadModel.kt @@ -3,6 +3,7 @@ package io.reqlith.repository import io.reqlith.config.McpReadOnlyDatabase import io.reqlith.exception.NotFoundException import io.reqlith.exception.ValidationException +import io.reqlith.model.dto.BaselineRow import io.reqlith.model.dto.CommentRow import io.reqlith.model.dto.DecisionRow import io.reqlith.model.dto.DocElement @@ -16,6 +17,7 @@ import io.reqlith.model.dto.ResolvedDocument import io.reqlith.model.dto.RoleRow import io.reqlith.model.dto.SuggestionRow import io.reqlith.model.dto.VersionRow +import io.reqlith.model.entity.BaselineCategory import io.reqlith.model.entity.ElementType import io.reqlith.model.entity.LinkKind import io.reqlith.model.entity.Priority @@ -140,6 +142,17 @@ class McpReadModel(database: McpReadOnlyDatabase, private val codec: SnapshotCod .list() } + /** The current NFR baseline, by category, then in the order the requirements were added (as in the UI). */ + fun baseline(): List = jdbc.sql("select baseline_key, category, title, body_md, updated_at from baseline_requirement order by created_at") + .query { rs, _ -> + val category = BaselineCategory.valueOf(rs.getString("category")) + category to + BaselineRow(rs.getString("baseline_key"), category.label, rs.getString("title"), rs.getString("body_md"), rs.instant("updated_at")!!) + } + .list() + .sortedBy { it.first.ordinal } // stable: keeps the creation order within a category + .map { it.second } + /** The working copy, assembled the same way as ProjectDocumentService (sorted, normalized). */ private fun workingCopy(project: ProjectRow): ProjectDocument { val (basicInfo, solutionDesign) = jdbc.sql("select basic_info_md, solution_design_md from project where id = ?").param(project.id) diff --git a/src/main/kotlin/io/reqlith/service/BaselineService.kt b/src/main/kotlin/io/reqlith/service/BaselineService.kt new file mode 100644 index 0000000..be9b900 --- /dev/null +++ b/src/main/kotlin/io/reqlith/service/BaselineService.kt @@ -0,0 +1,89 @@ +package io.reqlith.service + +import io.github.oshai.kotlinlogging.KotlinLogging +import io.reqlith.exception.NotFoundException +import io.reqlith.exception.ValidationException +import io.reqlith.model.dto.CurrentUser +import io.reqlith.model.entity.BaselineCategory +import io.reqlith.model.entity.BaselineRequirement +import io.reqlith.repository.BaselineRequirementRepository +import io.reqlith.repository.KeyCounter +import org.springframework.security.access.AccessDeniedException +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import java.security.MessageDigest +import java.time.Clock +import java.time.Instant + +private val logger = KotlinLogging.logger {} + +/** + * The non-functional requirements baseline: global requirements every project inherits as read-only items. + * Only architects maintain it. It is deliberately not part of project documents, so changes never alter a + * project's state, content hash or approved versions. + */ +@Service +class BaselineService(private val baseline: BaselineRequirementRepository, private val keyCounter: KeyCounter, private val clock: Clock) { + /** By category, then in the order they were added. */ + fun all(): List = baseline.findAll().sortedWith(compareBy({ it.category.ordinal }, { it.createdAt })) + + fun get(key: String): BaselineRequirement = baseline.findByKey(key) ?: throw NotFoundException("Baseline requirement $key not found") + + fun canEdit(user: CurrentUser): Boolean = user.isArchitect + + /** Changes whenever any baseline requirement is added, changed or removed (part of export cache keys). */ + fun fingerprint(): String { + val text = all().joinToString("\u0000") { "${it.key}|${it.category}|${it.title}|${it.bodyMd.orEmpty()}" } + return MessageDigest.getInstance("SHA-256").digest(text.toByteArray()).joinToString("") { "%02x".format(it) }.take(16) + } + + @Transactional + fun create(user: CurrentUser, category: BaselineCategory, title: String, bodyMd: String?): BaselineRequirement { + requireArchitect(user) + val now = Instant.now(clock) + return baseline.save( + BaselineRequirement( + key = "BL-%02d".format(keyCounter.next("BASELINE_KEY", "BL")), + category = category, + title = validTitle(title), + bodyMd = normalize(bodyMd), + createdAt = now, + updatedAt = now, + updatedBy = user.userId, + ), + ).also { logger.info { "Baseline requirement created key=${it.key} category=${it.category}" } } + } + + @Transactional + fun update(user: CurrentUser, requirement: BaselineRequirement, category: BaselineCategory, title: String, bodyMd: String?) { + requireArchitect(user) + requirement.category = category + requirement.title = validTitle(title) + requirement.bodyMd = normalize(bodyMd) + requirement.updatedAt = Instant.now(clock) + requirement.updatedBy = user.userId + baseline.save(requirement) + logger.info { "Baseline requirement changed key=${requirement.key}" } + } + + /** Its key stays retired, like element keys. */ + @Transactional + fun delete(user: CurrentUser, requirement: BaselineRequirement) { + requireArchitect(user) + baseline.delete(requirement) + logger.info { "Baseline requirement removed key=${requirement.key}" } + } + + private fun requireArchitect(user: CurrentUser) { + if (!canEdit(user)) throw AccessDeniedException("Only architects can change the baseline") + } + + private fun validTitle(title: String): String { + val trimmed = title.trim() + if (trimmed.isEmpty()) throw ValidationException("title", "Title is required") + if (trimmed.length > 200) throw ValidationException("title", "Keep the title under 200 characters") + return trimmed + } + + private fun normalize(markdown: String?): String? = markdown?.replace("\r\n", "\n")?.ifBlank { null } +} diff --git a/src/main/kotlin/io/reqlith/service/ExportService.kt b/src/main/kotlin/io/reqlith/service/ExportService.kt index 87721cd..eaec917 100644 --- a/src/main/kotlin/io/reqlith/service/ExportService.kt +++ b/src/main/kotlin/io/reqlith/service/ExportService.kt @@ -3,6 +3,7 @@ package io.reqlith.service import io.github.oshai.kotlinlogging.KotlinLogging import io.reqlith.controller.Formats import io.reqlith.model.dto.ApprovalRow +import io.reqlith.model.dto.BaselineItem import io.reqlith.model.dto.ExportFile import io.reqlith.model.dto.ExportOptions import io.reqlith.model.dto.PrdInput @@ -34,6 +35,7 @@ class ExportService( private val pdf: PdfRenderer, private val cache: ExportCache, private val formats: Formats, + private val baseline: BaselineService, ) { /** [version] null exports the working copy. */ fun markdown(project: Project, version: ProjectVersion?, options: ExportOptions): ExportFile { @@ -45,8 +47,10 @@ class ExportService( fun pdf(project: Project, version: ProjectVersion?, options: ExportOptions): ExportFile { val name = "${fileName(project, version)}.pdf" // A candidate and its approved version share a content hash, so label and status are part of the key. - // Open candidates are not cached: their status and review record are still changing. - val cacheKey = version?.takeIf { it.status != VersionStatus.IN_REVIEW }?.let { "${options.key}|${it.label}|${it.status}" } + // Open candidates are not cached: their status and review record are still changing. The PRD includes the + // current NFR baseline, which is not versioned, so its fingerprint is part of the key too. + val cacheKey = version?.takeIf { it.status != VersionStatus.IN_REVIEW } + ?.let { "${options.key}|${it.label}|${it.status}|${baseline.fingerprint()}" } cacheKey?.let { key -> cache.get(version.contentHash, "pdf", key)?.let { logger.info { "PRD exported project=${project.key} version=${version.label} format=pdf" } @@ -98,6 +102,7 @@ class ExportService( listOfNotNull(s.commentMd, s.proposedMd?.let { "Suggested wording: $it" }).joinToString(" — ") + " [${s.status.name.lowercase()}]", ) } + comments.map { (v, c) -> ReviewNote(v.label, c.elementKey?.let(::target) ?: "General", name(c.authorId), c.bodyMd) }, + baseline = baseline.all().map { BaselineItem(it.key, it.category.label, it.title, it.bodyMd) }, ) } diff --git a/src/main/kotlin/io/reqlith/service/IdpClaims.kt b/src/main/kotlin/io/reqlith/service/IdpClaims.kt index 602dd3a..62acbc2 100644 --- a/src/main/kotlin/io/reqlith/service/IdpClaims.kt +++ b/src/main/kotlin/io/reqlith/service/IdpClaims.kt @@ -15,5 +15,18 @@ object IdpClaims { ?: listOfNotNull(claims["given_name"] as? String, claims["family_name"] as? String).joinToString(" ").ifBlank { null } ?: claims["preferred_username"] as? String + /** + * Role names from [claim]: a list or a space-separated string. A dotted name reaches a nested claim, e.g. + * `realm_access.roles` in Keycloak access tokens. + */ + fun roles(claims: Map, claim: String): Set { + val value = claim.split('.').fold(claims) { node, part -> (node as? Map<*, *>)?.get(part) } + return when (value) { + is Collection<*> -> value.mapNotNull { it?.toString() } + is String -> value.split(' ', ',') + else -> emptyList() + }.map { it.trim() }.filter { it.isNotEmpty() }.toSet() + } + private val EMAIL = Regex("[^@\\s]+@[^@\\s]+\\.[^@\\s]+") } diff --git a/src/main/kotlin/io/reqlith/service/PrdMarkdownWriter.kt b/src/main/kotlin/io/reqlith/service/PrdMarkdownWriter.kt index 7ff6479..57bb449 100644 --- a/src/main/kotlin/io/reqlith/service/PrdMarkdownWriter.kt +++ b/src/main/kotlin/io/reqlith/service/PrdMarkdownWriter.kt @@ -61,6 +61,22 @@ object PrdMarkdownWriter { appendLine() elements(doc, type, level = 3) } + if (input.baseline.isNotEmpty()) { + appendLine("### Baseline") + appendLine() + appendLine("_Global non-functional requirements that apply to every project (current baseline, not versioned with the project)._") + appendLine() + input.baseline.forEach { b -> + appendLine("#### ${b.key} · ${b.title}") + appendLine() + appendLine("**Category:** ${b.category}") + appendLine() + b.body?.let { + appendLine(shiftHeadings(it, 3).trim()) + appendLine() + } + } + } appendLine("## ${++chapter}. Roles") appendLine() diff --git a/src/main/kotlin/io/reqlith/service/ProvisioningOidcUserService.kt b/src/main/kotlin/io/reqlith/service/ProvisioningOidcUserService.kt index 300d202..541c285 100644 --- a/src/main/kotlin/io/reqlith/service/ProvisioningOidcUserService.kt +++ b/src/main/kotlin/io/reqlith/service/ProvisioningOidcUserService.kt @@ -1,6 +1,8 @@ package io.reqlith.service import io.github.oshai.kotlinlogging.KotlinLogging +import io.reqlith.config.ReqlithProperties +import io.reqlith.model.dto.CurrentUser import io.reqlith.model.dto.ReqlithOidcUser import io.reqlith.model.entity.AppUser import org.springframework.security.core.GrantedAuthority @@ -13,9 +15,10 @@ import org.springframework.stereotype.Component private val logger = KotlinLogging.logger {} -/** Loads the OIDC user and provisions the matching [AppUser]. */ +/** Loads the OIDC user, provisions the matching [AppUser] and maps IDP roles to application roles. */ @Component -class ProvisioningOidcUserService(private val userService: UserService) : OAuth2UserService { +class ProvisioningOidcUserService(private val userService: UserService, private val properties: ReqlithProperties) : + OAuth2UserService { private val delegate = OidcUserService() @@ -26,11 +29,19 @@ class ProvisioningOidcUserService(private val userService: UserService) : OAuth2 email = IdpClaims.email(oidcUser.claims), name = IdpClaims.name(oidcUser.claims), ) - val authorities = buildList { - addAll(oidcUser.authorities) + val authorities = oidcUser.authorities + appAuthorities(oidcUser.claims) + logger.info { "User signed in user=${appUser.id} architect=${authorities.any { it.authority == CurrentUser.ARCHITECT_AUTHORITY }}" } + return ReqlithOidcUser(oidcUser, authorities, appUser.id, appUser.displayName, appUser.initials) + } + + /** ROLE_USER for everyone; ROLE_ARCHITECT when the roles claim holds one of the configured architect roles. */ + fun appAuthorities(claims: Map): List { + val idpRoles = IdpClaims.roles(claims, properties.idp.rolesClaim) + logger.debug { "IDP roles claim=${properties.idp.rolesClaim} roles=$idpRoles" } + val architect = properties.idp.architectRoles.any { wanted -> idpRoles.any { it.equals(wanted.trim(), ignoreCase = true) } } + return buildList { add(SimpleGrantedAuthority("ROLE_USER")) + if (architect) add(SimpleGrantedAuthority(CurrentUser.ARCHITECT_AUTHORITY)) } - logger.info { "User signed in user=${appUser.id}" } - return ReqlithOidcUser(oidcUser, authorities, appUser.id, appUser.displayName, appUser.initials) } } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index d468bca..23146e3 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -58,6 +58,10 @@ reqlith: mcp-audience: ${REQLITH_IDP_MCP_AUDIENCE:} # Invitation suggestions: NONE (users who signed in before), KEYCLOAK, ENTRA or ENTRA_ASSIGNED. directory: ${REQLITH_IDP_DIRECTORY:NONE} + # Claim with the user's IDP roles (dotted names reach nested claims, e.g. realm_access.roles), and the + # roles in it that grant the application role ARCHITECT (maintains the NFR baseline), comma-separated. + roles-claim: ${REQLITH_IDP_ROLES_CLAIM:roles} + architect-roles: ${REQLITH_IDP_ARCHITECT_ROLES:ARCHITECT} spring.ai.mcp.server: name: reqlith @@ -67,7 +71,8 @@ spring.ai.mcp.server: instructions: >- Read-only access to Reqlith requirement specifications (BABOK: business, stakeholder and solution requirements, scenarios, roles, risks). Tools default to the latest approved version of a project; - pass version="draft" only when you explicitly need unreviewed work in progress. + pass version="draft" only when you explicitly need unreviewed work in progress. The non-functional + requirements baseline (keys BL-...) applies to every project in addition to its own requirements. streamable-http: mcp-endpoint: /mcp diff --git a/src/main/resources/db/migration/V7__nfr_baseline.sql b/src/main/resources/db/migration/V7__nfr_baseline.sql new file mode 100644 index 0000000..05439c1 --- /dev/null +++ b/src/main/resources/db/migration/V7__nfr_baseline.sql @@ -0,0 +1,13 @@ +-- Global non-functional requirements that every project inherits, read-only. They are not part of project +-- snapshots, so adding, changing or removing one never changes a project's state or its approved versions. +create table baseline_requirement ( + id uniqueidentifier not null primary key, + baseline_key nvarchar(16) not null, + category nvarchar(32) not null, + title nvarchar(200) not null, + body_md nvarchar(max) null, + created_at datetimeoffset not null, + updated_at datetimeoffset not null, + updated_by uniqueidentifier not null references app_user (id), + constraint uq_baseline_key unique (baseline_key) +); diff --git a/src/main/resources/templates/baseline/list.html b/src/main/resources/templates/baseline/list.html new file mode 100644 index 0000000..a658f54 --- /dev/null +++ b/src/main/resources/templates/baseline/list.html @@ -0,0 +1,60 @@ + + + + Baseline + + + +
+
+

Non-functional requirements baseline

+

Global non-functional requirements that apply to every project. Projects show them as read-only items; + changing the baseline does not change a project's state or its approved versions. Architects maintain the baseline.

+
+ +
+
No baseline requirements yet.
+
+ + + + + + + + + + + + +
IDTitleCategoryModified
BL-01TitleSecuritydate
+
+
+ +
+

New baseline requirement

+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+ + diff --git a/src/main/resources/templates/baseline/show.html b/src/main/resources/templates/baseline/show.html new file mode 100644 index 0000000..7cbf2d5 --- /dev/null +++ b/src/main/resources/templates/baseline/show.html @@ -0,0 +1,53 @@ + + + + Baseline requirement + + + + +
+
+
+ BL-01 + Security + Applies to every project +
+

Title

+

Modified

+
+ +
description
+
+

Edit

+
+ +
+ + +
+
+ + +
+
+ + +
+
+
+
+
+ +
+
+ + diff --git a/src/main/resources/templates/fragments/document.html b/src/main/resources/templates/fragments/document.html index a3a0721..19b10ba 100644 --- a/src/main/resources/templates/fragments/document.html +++ b/src/main/resources/templates/fragments/document.html @@ -7,7 +7,8 @@ optional `changes` (DocumentChanges) to mark new/changed elements, optional `visibleKeys` (only these elements and roles are shown; sections without any are hidden), optional `reviewBlock` (template with an `element-review(key)` fragment appended to each element), - optional `itemDiff` (ProjectDiff) to show what changed in changed elements. + optional `itemDiff` (ProjectDiff) to show what changed in changed elements, + optional `baseline` with `baselineHtml` (key to HTML) to show the inherited NFR baseline after the non-functional section. */-->
@@ -89,6 +90,21 @@

Title

+
+

Baseline non-functional requirements

+

Inherited

+

None.

+
+
+ BL-01 +

Title

+ Security + Baseline +
+
body
+
+
diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html index 93a347a..668ab6d 100644 --- a/src/main/resources/templates/home.html +++ b/src/main/resources/templates/home.html @@ -14,6 +14,7 @@

Projects

+
+ + + + + + + + + + + + + + +
Baseline non-functional requirements · inherited, read-only
IDTitleCategoryStateModified
BL-01TitleSecurityBaselinedate
+
Add diff --git a/src/test/kotlin/io/reqlith/controller/BaselinePagesIT.kt b/src/test/kotlin/io/reqlith/controller/BaselinePagesIT.kt new file mode 100644 index 0000000..3f43743 --- /dev/null +++ b/src/test/kotlin/io/reqlith/controller/BaselinePagesIT.kt @@ -0,0 +1,121 @@ +package io.reqlith.controller + +import io.reqlith.model.dto.ReqlithOidcUser +import io.reqlith.model.entity.BaselineCategory +import io.reqlith.service.BaselineService +import io.reqlith.support.Fixtures +import io.reqlith.support.IntegrationTest +import io.reqlith.support.TestUsers +import org.hamcrest.Matchers.containsString +import org.hamcrest.Matchers.not +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oidcLogin +import org.springframework.test.web.servlet.MockMvc +import org.springframework.test.web.servlet.get +import org.springframework.test.web.servlet.post +import java.util.UUID +import kotlin.test.assertEquals + +@IntegrationTest +@AutoConfigureMockMvc +class BaselinePagesIT( + @Autowired private val mvc: MockMvc, + @Autowired private val users: TestUsers, + @Autowired private val fixtures: Fixtures, + @Autowired private val baseline: BaselineService, +) { + private fun login(user: ReqlithOidcUser) = oidcLogin().oidcUser(user) + + @Test + fun `architects add and edit baseline requirements from the baseline pages`() { + val architect = users.create("Ada Archer", architect = true) + val title = "Pages respond within 2 s " + UUID.randomUUID().toString().take(6) + + mvc.get("/") { with(login(architect)) }.andExpect { content { string(containsString("""href="/baseline"""")) } } + mvc.get("/baseline") { with(login(architect)) }.andExpect { + status { isOk() } + content { string(containsString("Add to baseline")) } + } + val location = mvc.post("/baseline") { + with(login(architect)) + with(csrf()) + param("category", "PERFORMANCE") + param("title", title) + param("body", "Measured at the 95th percentile") + }.andExpect { status { is3xxRedirection() } }.andReturn().response.redirectedUrl!! + val key = location.substringAfterLast('/') + + mvc.get(location) { with(login(architect)) }.andExpect { + status { isOk() } + content { string(containsString(title)) } + content { string(containsString("95th percentile")) } + } + mvc.post(location) { + with(login(architect)) + with(csrf()) + param("category", "SECURITY") + param("title", "") + }.andExpect { + status { isOk() } + content { string(containsString("Title is required")) } + } + mvc.post("$location/delete") { + with(login(architect)) + with(csrf()) + }.andExpect { status { is3xxRedirection() } } + assertEquals(null, baseline.all().firstOrNull { it.key == key }) + } + + @Test + fun `other users read the baseline but cannot change it`() { + val architect = users.create("Ada Archer", architect = true) + val owner = users.create("Olive Owens") + val requirement = baseline.create(architect, BaselineCategory.SECURITY, "Single sign-on " + UUID.randomUUID().toString().take(6), null) + + mvc.get("/baseline") { with(login(owner)) }.andExpect { + status { isOk() } + content { string(containsString(requirement.title)) } + content { string(not(containsString("Add to baseline"))) } + } + mvc.get("/baseline/${requirement.key}") { with(login(owner)) }.andExpect { + status { isOk() } + content { string(not(containsString("Remove ${requirement.key}"))) } + } + mvc.post("/baseline") { + with(login(owner)) + with(csrf()) + param("category", "OTHER") + param("title", "Sneaky") + }.andExpect { status { isForbidden() } } + mvc.post("/baseline/${requirement.key}/delete") { + with(login(owner)) + with(csrf()) + }.andExpect { status { isForbidden() } } + } + + @Test + fun `every project shows the baseline as read-only inherited items`() { + val architect = users.create("Ada Archer", architect = true) + val owner = users.create("Olive Owens") + val project = fixtures.project(owner) + val requirement = baseline.create(architect, BaselineCategory.AVAILABILITY, "99.9% uptime " + UUID.randomUUID().toString().take(6), "Monthly") + + listOf("/p/${project.key}/draft", "/p/${project.key}/draft?type=NFR", "/p/${project.key}/draft/document").forEach { page -> + mvc.get(page) { with(login(owner)) }.andExpect { + status { isOk() } + content { string(containsString(requirement.title)) } + content { string(containsString("/baseline/${requirement.key}")) } + content { string(containsString("Baseline NFRs")) } + } + } + mvc.get("/p/${project.key}/draft?type=FR") { with(login(owner)) }.andExpect { + content { string(not(containsString(requirement.title))) } + } + mvc.get("/p/${project.key}/draft/prd.md") { with(login(owner)) }.andExpect { + content { string(containsString("#### ${requirement.key} · ${requirement.title}")) } + } + } +} diff --git a/src/test/kotlin/io/reqlith/controller/ExportPagesIT.kt b/src/test/kotlin/io/reqlith/controller/ExportPagesIT.kt index b39d892..03c3317 100644 --- a/src/test/kotlin/io/reqlith/controller/ExportPagesIT.kt +++ b/src/test/kotlin/io/reqlith/controller/ExportPagesIT.kt @@ -129,7 +129,7 @@ class ExportPagesIT( content { contentType("application/pdf") } }.andReturn().response.contentAsByteArray assertEquals("%PDF", String(first.copyOfRange(0, 4))) - val cached = jdbc.sql("select count(*) from export_cache where options_key like '%|v1|APPROVED'").query(Int::class.java).single() + val cached = jdbc.sql("select count(*) from export_cache where options_key like '%|v1|APPROVED|%'").query(Int::class.java).single() assertTrue(cached >= 1) val second = mvc.get("/p/$key/v/1/prd.pdf") { with(login(owner)) }.andReturn().response.contentAsByteArray assertTrue(first.contentEquals(second)) diff --git a/src/test/kotlin/io/reqlith/controller/McpServerIT.kt b/src/test/kotlin/io/reqlith/controller/McpServerIT.kt index 1b5f379..0d73483 100644 --- a/src/test/kotlin/io/reqlith/controller/McpServerIT.kt +++ b/src/test/kotlin/io/reqlith/controller/McpServerIT.kt @@ -6,6 +6,7 @@ import io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTranspor import io.modelcontextprotocol.spec.McpSchema import io.reqlith.config.McpReadOnlyDatabase import io.reqlith.model.dto.ElementContent +import io.reqlith.model.entity.BaselineCategory import io.reqlith.model.entity.Decision import io.reqlith.model.entity.ElementType import io.reqlith.model.entity.LinkKind @@ -13,6 +14,7 @@ import io.reqlith.model.entity.MemberRole import io.reqlith.model.entity.TraceLink import io.reqlith.repository.McpAccessLog import io.reqlith.service.AccessTokenService +import io.reqlith.service.BaselineService import io.reqlith.service.ElementService import io.reqlith.service.ProjectService import io.reqlith.service.ReviewService @@ -33,6 +35,7 @@ import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.time.Duration +import java.util.UUID import kotlin.test.assertContains import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -54,6 +57,7 @@ class McpServerIT( @Autowired private val accessLog: McpAccessLog, @Autowired private val readOnly: McpReadOnlyDatabase, @Autowired private val jdbc: JdbcClient, + @Autowired private val baseline: BaselineService, ) { private val clients = mutableListOf() @@ -113,7 +117,7 @@ class McpServerIT( assertEquals( setOf( "list_projects", "get_prd", "search_requirements", "get_requirement", "get_traceability", "list_versions", - "diff_versions", "get_review_status", "get_external_links", "list_roles", + "diff_versions", "get_review_status", "get_external_links", "list_roles", "list_baseline_requirements", ), mcp.listTools().tools().map { it.name() }.toSet(), ) @@ -147,6 +151,37 @@ class McpServerIT( assertTrue(log.any { it.tool == "get_prd" && it.clientName == "backlog-agent" && it.tokenName == "Backlog agent" }, log.toString()) } + @Test + fun `agents get the NFR baseline with every project`() { + val (key, token) = approvedProject() + val architect = users.create("Ada Archer", architect = true) + val marker = UUID.randomUUID().toString().take(8) + val security = baseline.create(architect, BaselineCategory.SECURITY, "Encrypt data at rest $marker", "AES-256 for all stores") + val performance = baseline.create(architect, BaselineCategory.PERFORMANCE, "Fast pages $marker", "Under 2 s") + val mcp = client(token) + + val all = mcp.call("list_baseline_requirements", "query" to marker).text() + assertContains(all, security.key) + assertContains(all, performance.key) + assertTrue(all.indexOf(performance.key) < all.indexOf(security.key), "performance is listed before security: $all") + val onlySecurity = mcp.call("list_baseline_requirements", "category" to "security", "query" to marker).text() + assertContains(onlySecurity, "\"category\":\"Security\"") + assertFalse(onlySecurity.contains(performance.key)) + assertTrue(mcp.call("list_baseline_requirements", "category" to "speed").isError) + + assertContains(mcp.call("get_prd", "project" to key).text(), "#### ${security.key} · Encrypt data at rest $marker") + + val hits = mcp.call("search_requirements", "project" to key, "text" to marker).text() + assertContains(hits, "\"project\":\"baseline\"") + assertContains(hits, security.key) + assertFalse(mcp.call("search_requirements", "project" to key, "type" to "FR", "text" to marker).text().contains(security.key)) + + val detail = mcp.call("get_requirement", "project" to key, "key" to security.key.lowercase()).text() + assertContains(detail, "AES-256 for all stores") + assertContains(detail, "/baseline/${security.key}") + assertTrue(mcp.call("get_requirement", "project" to key, "key" to "BL-9999").isError) + } + @Test fun `requests without a valid token are rejected with a pointer to the resource metadata`() { val (_, token) = approvedProject() diff --git a/src/test/kotlin/io/reqlith/service/BaselineServiceIT.kt b/src/test/kotlin/io/reqlith/service/BaselineServiceIT.kt new file mode 100644 index 0000000..b8d0abc --- /dev/null +++ b/src/test/kotlin/io/reqlith/service/BaselineServiceIT.kt @@ -0,0 +1,87 @@ +package io.reqlith.service + +import io.reqlith.exception.ValidationException +import io.reqlith.model.dto.ElementContent +import io.reqlith.model.entity.BaselineCategory +import io.reqlith.model.entity.Decision +import io.reqlith.model.entity.ElementType +import io.reqlith.model.entity.MemberRole +import io.reqlith.support.Fixtures +import io.reqlith.support.IntegrationTest +import io.reqlith.support.TestUsers +import org.junit.jupiter.api.Test +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.security.access.AccessDeniedException +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +@IntegrationTest +class BaselineServiceIT( + @Autowired private val baseline: BaselineService, + @Autowired private val projects: ProjectService, + @Autowired private val elements: ElementService, + @Autowired private val reviews: ReviewService, + @Autowired private val versions: VersionService, + @Autowired private val users: TestUsers, + @Autowired private val fixtures: Fixtures, +) { + @Test + fun `architects maintain the baseline, keys are never reused`() { + val architect = users.create("Ada Archer", architect = true) + val first = baseline.create(architect, BaselineCategory.SECURITY, " Encrypt data at rest ", "AES-256\r\n") + assertTrue(first.key.matches(Regex("BL-\\d{2,}"))) + assertEquals("Encrypt data at rest", baseline.get(first.key).title) + assertEquals("AES-256\n", baseline.get(first.key).bodyMd) + + baseline.update(architect, baseline.get(first.key), BaselineCategory.COMPLIANCE, "Encrypt personal data", " ") + val changed = baseline.get(first.key) + assertEquals(BaselineCategory.COMPLIANCE, changed.category) + assertEquals(null, changed.bodyMd) + + baseline.delete(architect, changed) + assertFalse(baseline.all().any { it.key == first.key }) + val second = baseline.create(architect, BaselineCategory.PERFORMANCE, "Fast pages", null) + assertNotEquals(first.key, second.key) + assertFailsWith { baseline.create(architect, BaselineCategory.OTHER, " ", null) } + } + + @Test + fun `only architects change the baseline`() { + val architect = users.create("Ada Archer", architect = true) + val owner = users.create("Olive Owens") + fixtures.project(owner) + val requirement = baseline.create(architect, BaselineCategory.AVAILABILITY, "99.9% uptime", null) + + assertFalse(baseline.canEdit(owner)) + assertFailsWith { baseline.create(owner, BaselineCategory.OTHER, "Mine", null) } + assertFailsWith { baseline.update(owner, requirement, BaselineCategory.OTHER, "Mine", null) } + assertFailsWith { baseline.delete(owner, requirement) } + } + + @Test + fun `adding or removing baseline requirements leaves an approved project approved`() { + val architect = users.create("Ada Archer", architect = true) + val owner = users.create("Olive Owens") + val reviewer = users.create("Rita Reyes") + val project = fixtures.project(owner) + fixtures.addMember(project, reviewer, MemberRole.REVIEWER) + elements.create(owner, project, ElementType.NFR, ElementContent("Audit log", "Every change", null, emptySet(), emptySet())) + reviews.submit(owner, project, listOf(reviewer.userId)) + reviews.decide(reviewer, projects.get(project.key), Decision.ACCEPT, null) + val approved = projects.get(project.key) + assertFalse(versions.hasChangesSinceApproval(approved)) + val fingerprint = baseline.fingerprint() + + val added = baseline.create(architect, BaselineCategory.USABILITY, "Works on mobile", "Down to 360 px") + assertFalse(versions.hasChangesSinceApproval(projects.get(project.key))) + assertNotEquals(fingerprint, baseline.fingerprint()) + + baseline.delete(architect, added) + val after = projects.get(project.key) + assertFalse(versions.hasChangesSinceApproval(after)) + assertEquals(approved.updatedAt, after.updatedAt) + } +} diff --git a/src/test/kotlin/io/reqlith/service/ExportServiceTest.kt b/src/test/kotlin/io/reqlith/service/ExportServiceTest.kt index 4d07689..22a599c 100644 --- a/src/test/kotlin/io/reqlith/service/ExportServiceTest.kt +++ b/src/test/kotlin/io/reqlith/service/ExportServiceTest.kt @@ -36,9 +36,13 @@ class ExportServiceTest { private val pdf = mockk { every { render(any(), any()) } returns byteArrayOf(1, 2, 3) } private val cache = mockk(relaxUnitFun = true) private val properties = ReqlithProperties(idp = ReqlithProperties.Idp("http://idp")) + private val baseline = mockk { + every { all() } returns emptyList() + every { fingerprint() } returns "bl" + } private val service = ExportService( versions, reviews, documents, users, MarkdownRenderer(), templates, pdf, cache, - Formats(UnitFixtures.clock, properties), + Formats(UnitFixtures.clock, properties), baseline, ) private val project = UnitFixtures.project() @@ -69,7 +73,7 @@ class ExportServiceTest { @Test fun `pdfs of closed versions come from the cache when present`() { val v1 = version(VersionStatus.APPROVED) - every { cache.get(v1.contentHash, "pdf", "t1a1c0|v1|APPROVED") } returns byteArrayOf(9) + every { cache.get(v1.contentHash, "pdf", "t1a1c0|v1|APPROVED|bl") } returns byteArrayOf(9) assertContentEquals(byteArrayOf(9), service.pdf(project, v1, ExportOptions()).bytes) verify(exactly = 0) { pdf.render(any(), any()) } } @@ -80,7 +84,7 @@ class ExportServiceTest { every { versions.document(any()) } returns document every { cache.get(any(), any(), any()) } returns null service.pdf(project, v1, ExportOptions()) - verify { cache.put(v1.contentHash, "pdf", "t1a1c0|v1|APPROVED", byteArrayOf(1, 2, 3)) } + verify { cache.put(v1.contentHash, "pdf", "t1a1c0|v1|APPROVED|bl", byteArrayOf(1, 2, 3)) } service.pdf(project, version(VersionStatus.IN_REVIEW), ExportOptions()) service.pdf(project, null, ExportOptions()) diff --git a/src/test/kotlin/io/reqlith/service/IdpClaimsTest.kt b/src/test/kotlin/io/reqlith/service/IdpClaimsTest.kt index 6dd1d85..4c2a4c8 100644 --- a/src/test/kotlin/io/reqlith/service/IdpClaimsTest.kt +++ b/src/test/kotlin/io/reqlith/service/IdpClaimsTest.kt @@ -13,6 +13,15 @@ class IdpClaimsTest { assertNull(IdpClaims.email(mapOf("preferred_username" to "rita"))) } + @Test + fun `roles come from a list, a space-separated string or a nested claim`() { + assertEquals(setOf("ARCHITECT", "USER"), IdpClaims.roles(mapOf("roles" to listOf("ARCHITECT", "USER")), "roles")) + assertEquals(setOf("ARCHITECT", "USER"), IdpClaims.roles(mapOf("roles" to "ARCHITECT USER"), "roles")) + assertEquals(setOf("architect"), IdpClaims.roles(mapOf("realm_access" to mapOf("roles" to listOf("architect"))), "realm_access.roles")) + assertEquals(emptySet(), IdpClaims.roles(mapOf("roles" to listOf("ARCHITECT")), "groups")) + assertEquals(emptySet(), IdpClaims.roles(mapOf("realm_access" to "x"), "realm_access.roles")) + } + @Test fun `name falls back to given and family name, then the user name`() { assertEquals("Rita Reyes", IdpClaims.name(mapOf("name" to "Rita Reyes", "given_name" to "R"))) diff --git a/src/test/kotlin/io/reqlith/service/PrdMarkdownWriterTest.kt b/src/test/kotlin/io/reqlith/service/PrdMarkdownWriterTest.kt index 9bcaacb..083118c 100644 --- a/src/test/kotlin/io/reqlith/service/PrdMarkdownWriterTest.kt +++ b/src/test/kotlin/io/reqlith/service/PrdMarkdownWriterTest.kt @@ -1,6 +1,7 @@ package io.reqlith.service import io.reqlith.model.dto.ApprovalRow +import io.reqlith.model.dto.BaselineItem import io.reqlith.model.dto.DocElement import io.reqlith.model.dto.DocLink import io.reqlith.model.dto.DocProject @@ -66,6 +67,26 @@ class PrdMarkdownWriterTest { assertFalse(md.contains("Appendix B"), "review comments are opt-in") } + @Test + fun `the baseline is printed after the project's non-functional requirements`() { + val md = PrdMarkdownWriter.write( + input().copy(baseline = listOf(BaselineItem("BL-01", "Performance", "Fast pages", "## Target\nUnder 2 s"))), + ExportOptions(), + ) + val order = + listOf( + "## 5. Solution requirements · Non-functional", + "### Baseline", + "#### BL-01 · Fast pages", + "**Category:** Performance", + "##### Target", + "## 6. Roles", + ) + val positions = order.map { md.indexOf(it).also { pos -> assertTrue(pos >= 0, "missing '$it' in\n$md") } } + assertEquals(positions.sorted(), positions) + assertFalse(PrdMarkdownWriter.write(input(), ExportOptions()).contains("### Baseline"), "no section without a baseline") + } + @Test fun `headings inside bodies are shifted below the element heading, code fences untouched`() { val md = PrdMarkdownWriter.write(input(), ExportOptions()) diff --git a/src/test/kotlin/io/reqlith/service/ProvisioningOidcUserServiceTest.kt b/src/test/kotlin/io/reqlith/service/ProvisioningOidcUserServiceTest.kt new file mode 100644 index 0000000..410a7ee --- /dev/null +++ b/src/test/kotlin/io/reqlith/service/ProvisioningOidcUserServiceTest.kt @@ -0,0 +1,31 @@ +package io.reqlith.service + +import io.mockk.mockk +import io.reqlith.config.ReqlithProperties +import io.reqlith.model.dto.CurrentUser +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class ProvisioningOidcUserServiceTest { + private fun service(claim: String = "roles", architectRoles: List = listOf("ARCHITECT")) = ProvisioningOidcUserService( + mockk(), + ReqlithProperties(idp = ReqlithProperties.Idp(issuer = "http://idp.test", rolesClaim = claim, architectRoles = architectRoles)), + ) + + private fun ProvisioningOidcUserService.authorityNames(claims: Map) = appAuthorities(claims).map { it.authority }.toSet() + + @Test + fun `an IDP role listed as architect role grants ARCHITECT`() { + assertEquals(setOf("ROLE_USER", CurrentUser.ARCHITECT_AUTHORITY), service().authorityNames(mapOf("roles" to listOf("ARCHITECT")))) + assertEquals(setOf("ROLE_USER"), service().authorityNames(mapOf("roles" to listOf("REVIEWER")))) + assertEquals(setOf("ROLE_USER"), service().authorityNames(emptyMap())) + } + + @Test + fun `claim name and role names are configurable`() { + val custom = service("realm_access.roles", listOf("reqlith-architect", "chief-architect")) + val claims = mapOf("realm_access" to mapOf("roles" to listOf("Chief-Architect"))) + assertEquals(setOf("ROLE_USER", CurrentUser.ARCHITECT_AUTHORITY), custom.authorityNames(claims)) + assertEquals(setOf("ROLE_USER"), custom.authorityNames(mapOf("roles" to listOf("ARCHITECT")))) + } +} diff --git a/src/test/kotlin/io/reqlith/support/TestUsers.kt b/src/test/kotlin/io/reqlith/support/TestUsers.kt index 569b8a2..ebed56f 100644 --- a/src/test/kotlin/io/reqlith/support/TestUsers.kt +++ b/src/test/kotlin/io/reqlith/support/TestUsers.kt @@ -1,5 +1,6 @@ package io.reqlith.support +import io.reqlith.model.dto.CurrentUser import io.reqlith.model.dto.ReqlithOidcUser import io.reqlith.service.UserService import org.springframework.security.core.authority.SimpleGrantedAuthority @@ -13,7 +14,7 @@ import java.util.UUID @Component class TestUsers(private val userService: UserService) { - fun create(name: String = "Test User"): ReqlithOidcUser { + fun create(name: String = "Test User", architect: Boolean = false): ReqlithOidcUser { val unique = UUID.randomUUID().toString().take(8) val email = name.lowercase().replace(' ', '.') + ".$unique@reqlith.test" val subject = "sub-$unique" @@ -22,6 +23,7 @@ class TestUsers(private val userService: UserService) { .issuedAt(Instant.now()).expiresAt(Instant.now().plusSeconds(600)).build() val authorities = buildList { add(SimpleGrantedAuthority("ROLE_USER")) + if (architect) add(SimpleGrantedAuthority(CurrentUser.ARCHITECT_AUTHORITY)) } return ReqlithOidcUser(DefaultOidcUser(authorities, token), authorities, user.id, user.displayName, user.initials) }