# 09 — Authentication, teams, and authorization

> **Assessment review:** The supplied OAuth/JWT lecture describes a different authentication architecture. This project uses custom opaque tokens; the rubric does not explicitly require JWT. See [architecture corrections](../review.md#architecture-corrections-for-the-course).

Authentication establishes an actor. Authorization decides what that actor may do to a particular document, team, or account. Read both paths before treating a successful login as access to every resource.

## Trace opaque-token authentication

`AuthServiceImpl` locks the user lookup, verifies the supported stored password representation, and generates 32 random bytes for a URL-safe bearer token. It removes previous tokens for the user and stores a digest with expiry. The raw token is returned to the caller; the stored `AccessToken` model carries digest, user ID, and expiry.

`LocalTokenIntrospector` checks incoming tokens through persistence and produces the authenticated principal. This is an opaque-token flow, not a JWT verification flow. Read `SecurityConfig` for which endpoints require authentication and how the principal reaches services.

## Authorization follows the resource

For an owner-only document, the actor must match the owner. For a shared document, membership allows reading, while write roles are `READ_WRITE` or `ADMIN`. Changing sharing additionally requires the uploader. Inaccessible documents may be reported as not found; that prevents the endpoint from simply confirming another user's document exists.

These rules must apply to listing, search, metadata access, download, update, and deletion. Checking only the controller's get-by-ID route is insufficient. Search therefore obtains actor-filtered candidates through persistence before ranking them.

## Cross-feature coordination

Authentication uses `UserPersistence` and `AccessTokenPersistence`, not `UserService`. Team and document operations similarly rely on persistence ports under their own service transaction. Trace account deletion and token revocation in `UserServiceImpl` as an example of a use case spanning multiple stored concepts.

## Practice

Build an access matrix for owner, unrelated user, read-only member, write member, and team administrator. Evaluate both owner-only and shared documents. Distinguish changing title from moving a document to another team.

Use `DocumentSecurityIntegrationTest` as executable evidence for request-level behavior. Inspect `SecurityIntegrationTest` for login replacement/revocation and concurrent login behavior. For every row in your matrix, point to a test or record a missing case to add in your practice project.

## Verification gate

Explain the difference between raw token, token digest, and password hash. Identify where actor identity is read and where resource permissions are checked. Show why domain-facing persistence access does not eliminate the caller's obligation to authorize the operation.

## Read the implementation

- [AuthServiceImpl.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/auth/service/AuthServiceImpl.kt)
- [LocalTokenIntrospector.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/auth/service/LocalTokenIntrospector.kt)
- [AccessToken.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/auth/model/AccessToken.kt)
- [SecurityConfig.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/config/SecurityConfig.kt)
- [Role.kt](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/team/model/Role.kt)
- [DocumentSecurityIntegrationTest.kt](../reference/source/paperless-backend/src/test/kotlin/at/fhtw/swen3/paperless/auth/DocumentSecurityIntegrationTest.kt)

## Complete source walkthrough

Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.

### AuthServiceImpl.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/auth/service/AuthServiceImpl.kt)

```kotlin
package at.fhtw.swen3.paperless.auth.service

import at.fhtw.swen3.paperless.auth.model.AccessToken
import at.fhtw.swen3.paperless.auth.model.AuthenticatedUser
import at.fhtw.swen3.paperless.auth.model.LoginCredentials
import at.fhtw.swen3.paperless.auth.persistence.AccessTokenPersistence
import at.fhtw.swen3.paperless.exception.InvalidCredentialsException
import at.fhtw.swen3.paperless.exception.UserNotFoundException
import at.fhtw.swen3.paperless.user.model.User
import at.fhtw.swen3.paperless.user.persistence.UserPersistence
import java.security.SecureRandom
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.Base64
import java.util.UUID
import org.slf4j.LoggerFactory
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional
class AuthServiceImpl(
    private val userRepository: UserPersistence,
    private val passwordEncoder: PasswordEncoder,
    private val tokenRepository: AccessTokenPersistence
) : AuthService {
    private val log = LoggerFactory.getLogger(javaClass)
    private val random = SecureRandom()

    override fun login(credentials: LoginCredentials): AuthenticatedUser {
        val user = userRepository.findLockedByUsername(credentials.username)
            ?: throw InvalidCredentialsException()
        if (!user.password.startsWith("{pbkdf2@SpringSecurity_v5_8}") ||
            !passwordEncoder.matches(credentials.password, user.password)) {
            throw InvalidCredentialsException()
        }
        val userId = requireNotNull(user.id)
        val bytes = ByteArray(32).also(random::nextBytes)
        val token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
        tokenRepository.deleteByUserId(userId)
        tokenRepository.save(AccessToken(TokenDigests.sha256(token), userId, Instant.now().plus(1, ChronoUnit.DAYS)))
        log.info("[AUTH] - ACTION: login: userId: {}", userId)

        return AuthenticatedUser(user, token)
    }

    @Transactional(readOnly = true)
    override fun getCurrentUser(userId: UUID): User =
        userRepository.findById(userId).orElseThrow { UserNotFoundException() }
}
```

### LocalTokenIntrospector.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/auth/service/LocalTokenIntrospector.kt)

```kotlin
package at.fhtw.swen3.paperless.auth.service

import at.fhtw.swen3.paperless.auth.persistence.AccessTokenPersistence
import java.time.Instant
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal
import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional

@Component
class LocalTokenIntrospector(private val tokens: AccessTokenPersistence) : OpaqueTokenIntrospector {
    @Transactional(readOnly = true)
    override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
        val stored = tokens.findById(TokenDigests.sha256(token))
            .orElseThrow { BadOpaqueTokenException("Invalid bearer token") }
        if (!stored.expiresAt.isAfter(Instant.now())) throw BadOpaqueTokenException("Expired bearer token")
        return DefaultOAuth2AuthenticatedPrincipal(
            stored.userId.toString(),
            mapOf("user_id" to stored.userId),
            emptyList<SimpleGrantedAuthority>()
        )
    }
}
```

### AccessToken.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/auth/model/AccessToken.kt)

```kotlin
package at.fhtw.swen3.paperless.auth.model

import java.time.Instant
import java.util.UUID

data class AccessToken(val digest: String, val userId: UUID, val expiresAt: Instant)
```

### SecurityConfig.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/config/SecurityConfig.kt)

```kotlin
package at.fhtw.swen3.paperless.config

import at.fhtw.swen3.paperless.auth.service.LocalTokenIntrospector
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.http.HttpHeaders
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.crypto.password.DelegatingPasswordEncoder
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.SecurityFilterChain
import org.springframework.http.HttpMethod

@Configuration
@EnableWebSecurity
class SecurityConfig(private val introspector: LocalTokenIntrospector) {
    private val log = LoggerFactory.getLogger(javaClass)

    @Bean
    fun passwordEncoder(): PasswordEncoder {
        val id = "pbkdf2@SpringSecurity_v5_8"
        return DelegatingPasswordEncoder(id, mapOf(id to Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()))
    }

    @Bean
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        http
            .csrf { it.disable() }
            .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
            .httpBasic { it.disable() }
            .formLogin { it.disable() }
            .authorizeHttpRequests { auth ->
                auth
                    .requestMatchers(HttpMethod.POST, "/api/v1/auth/login", "/api/v1/users").permitAll()
                    .requestMatchers(
                        "/swagger-ui/**",
                        "/swagger-ui.html",
                        "/v3/api-docs/**",
                        "/v3/api-docs.yaml"
                    ).permitAll()
                    .anyRequest().authenticated()
            }
            .oauth2ResourceServer {
                it.authenticationEntryPoint { _, response, _ -> problem(response, 401, "Unauthorized", "Authentication is required.") }
                it.opaqueToken { opaque -> opaque.introspector(introspector) }
            }
            .exceptionHandling {
                it.authenticationEntryPoint { _, response, _ -> problem(response, 401, "Unauthorized", "Authentication is required.") }
                it.accessDeniedHandler { _, response, _ -> problem(response, 403, "Forbidden", "Access is denied.") }
            }
        return http.build()
    }

    private fun problem(response: HttpServletResponse, status: Int, title: String, detail: String) {
        log.warn("[SECURITY] - ACTION: rejectRequest: status: {}", status)
        response.status = status
        response.contentType = MediaType.APPLICATION_PROBLEM_JSON_VALUE
        if (status == 401) response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer")
        response.writer.write("""{"type":"urn:problem-type:$status","title":"$title","status":$status,"detail":"$detail"}""")
    }
}
```

### Role.kt

[Browse source](../reference/source/paperless-backend/src/main/kotlin/at/fhtw/swen3/paperless/team/model/Role.kt)

```kotlin
package at.fhtw.swen3.paperless.team.model

enum class Role {
    ADMIN,
    READONLY,
    READ_WRITE
}
```

### DocumentSecurityIntegrationTest.kt

[Browse source](../reference/source/paperless-backend/src/test/kotlin/at/fhtw/swen3/paperless/auth/DocumentSecurityIntegrationTest.kt)

```kotlin
package at.fhtw.swen3.paperless.auth

import at.fhtw.swen3.paperless.auth.persistence.repository.AccessTokenRepository
import at.fhtw.swen3.paperless.document.persistence.repository.DocumentRepository
import at.fhtw.swen3.paperless.user.persistence.repository.UserRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc
import org.springframework.http.MediaType
import org.springframework.mock.web.MockMultipartFile
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import java.nio.file.Files
import java.nio.file.Paths
import java.util.UUID

@SpringBootTest(properties = [
    "spring.datasource.url=jdbc:h2:mem:documentsecuritytest;DB_CLOSE_DELAY=-1",
    "spring.flyway.locations=classpath:db/migration/h2",
    "spring.datasource.driver-class-name=org.h2.Driver",
    "spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
    "spring.jpa.hibernate.ddl-auto=create-drop"
])
@AutoConfigureMockMvc
class DocumentSecurityIntegrationTest(
    @Autowired private val mvc: MockMvc,
    @Autowired private val documents: DocumentRepository,
    @Autowired private val users: UserRepository,
    @Autowired private val tokens: AccessTokenRepository
) {
    private val createdDocuments = linkedMapOf<UUID, String>()

    @Test
    fun bearer_chain_enforces_private_and_team_document_access() {
        val suffix = System.nanoTime()
        val owner = registerAndLogin("owner$suffix")
        val writer = registerAndLogin("writer$suffix")
        val reader = registerAndLogin("reader$suffix")
        val outsider = registerAndLogin("outsider$suffix")

        val teamId = createTeam(owner.token, suffix)
        addMember(owner.token, teamId, writer, "READ_WRITE")
        addMember(owner.token, teamId, reader, "READONLY")

        val privateDocument = upload(owner, owner, "ownerprivateprobe")
        val outsiderPrivateDocument = upload(outsider, outsider, "outsiderprivateprobe")
        val adminTeamDocument = upload(owner, owner, "adminteamprobe", teamId)
        val writerTeamDocument = upload(writer, owner, "writerteamprobe", teamId)

        assertThat(documents.findById(privateDocument.id)).isPresent
        mvc.perform(delete("/api/v1/teams/$teamId").header("Authorization", owner.bearer))
            .andExpect(status().isConflict)
        mvc.perform(delete("/api/v1/users/${owner.id}").header("Authorization", owner.bearer))
            .andExpect(status().isConflict)
        mvc.perform(get("/api/v1/auth/me").header("Authorization", owner.bearer))
            .andExpect(status().isOk)

        mvc.perform(get("/api/v1/documents/${privateDocument.id}").header("Authorization", owner.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.id").value(privateDocument.id.toString()))
        mvc.perform(get("/api/v1/documents/${privateDocument.id}/download").header("Authorization", owner.bearer))
            .andExpect(status().isOk)
            .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content().bytes(privateDocument.content))
        mvc.perform(get("/api/v1/documents").header("Authorization", owner.bearer).param("size", "1"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(3))
            .andExpect(jsonPath("$.pagination.total_pages").value(3))
        mvc.perform(get("/api/v1/search").header("Authorization", owner.bearer)
            .param("query", "ownerprivateprobe").param("fuzzy", "false"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(1))
            .andExpect(jsonPath("$.items[0].document.id").value(privateDocument.id.toString()))

        mvc.perform(get("/api/v1/documents/${privateDocument.id}").header("Authorization", outsider.bearer))
            .andExpect(status().isNotFound)
        mvc.perform(get("/api/v1/documents/${privateDocument.id}").header("Authorization", reader.bearer))
            .andExpect(status().isNotFound)
        mvc.perform(get("/api/v1/documents/${privateDocument.id}/download").header("Authorization", outsider.bearer))
            .andExpect(status().isNotFound)
        mvc.perform(get("/api/v1/documents").header("Authorization", outsider.bearer).param("size", "1"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(1))
            .andExpect(jsonPath("$.pagination.total_pages").value(1))
            .andExpect(jsonPath("$.items[0].id").value(outsiderPrivateDocument.id.toString()))
        mvc.perform(get("/api/v1/search").header("Authorization", outsider.bearer)
            .param("query", "ownerprivateprobe").param("fuzzy", "false"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(0))

        mvc.perform(get("/api/v1/documents/${adminTeamDocument.id}").header("Authorization", reader.bearer))
            .andExpect(status().isOk)
        mvc.perform(get("/api/v1/documents/${writerTeamDocument.id}/download").header("Authorization", reader.bearer))
            .andExpect(status().isOk)
            .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content().bytes(writerTeamDocument.content))
        mvc.perform(get("/api/v1/documents").header("Authorization", reader.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(2))
        mvc.perform(get("/api/v1/search").header("Authorization", reader.bearer)
            .param("query", "teamprobe").param("fuzzy", "false"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(2))
        mvc.perform(get("/api/v1/search").header("Authorization", reader.bearer)
            .param("query", "ownerprivateprobe").param("fuzzy", "false"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(0))

        mvc.perform(uploadRequest("readonlyuploadprobe", teamId)
            .header("Authorization", reader.bearer))
            .andExpect(status().isForbidden)
        mvc.perform(put("/api/v1/documents/${adminTeamDocument.id}").header("Authorization", reader.bearer)
            .contentType(MediaType.APPLICATION_JSON).content("""{"title":"forbidden edit"}"""))
            .andExpect(status().isForbidden)
        mvc.perform(delete("/api/v1/documents/${adminTeamDocument.id}").header("Authorization", reader.bearer))
            .andExpect(status().isForbidden)

        mvc.perform(get("/api/v1/documents/${adminTeamDocument.id}").header("Authorization", outsider.bearer))
            .andExpect(status().isNotFound)
        mvc.perform(get("/api/v1/documents/${writerTeamDocument.id}/download").header("Authorization", outsider.bearer))
            .andExpect(status().isNotFound)
        mvc.perform(get("/api/v1/search").header("Authorization", outsider.bearer)
            .param("query", "teamprobe").param("fuzzy", "false"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(0))

        mvc.perform(delete("/api/v1/teams/$teamId/members/${writer.id}").header("Authorization", owner.bearer))
            .andExpect(status().isNoContent)
        mvc.perform(get("/api/v1/auth/me").header("Authorization", writer.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.id").value(writer.id.toString()))
        mvc.perform(get("/api/v1/documents/${writerTeamDocument.id}").header("Authorization", writer.bearer))
            .andExpect(status().isNotFound)
        mvc.perform(get("/api/v1/documents/${writerTeamDocument.id}/download").header("Authorization", writer.bearer))
            .andExpect(status().isNotFound)
        mvc.perform(get("/api/v1/documents").header("Authorization", writer.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(0))
        mvc.perform(get("/api/v1/search").header("Authorization", writer.bearer)
            .param("query", "writerteamprobe").param("fuzzy", "false"))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.pagination.total_elements").value(0))
        mvc.perform(get("/api/v1/documents/${writerTeamDocument.id}").header("Authorization", owner.bearer))
            .andExpect(status().isOk)
    }

    @Test
    fun deleting_user_with_private_document_conflicts_and_rolls_back_account_and_token_deletion() {
        val suffix = System.nanoTime()
        val account = registerAndLogin("privateowner$suffix")
        mvc.perform(get("/api/v1/teams").header("Authorization", account.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.items").isEmpty)

        val privateDocument = upload(account, account, "deleteownerprobe")
        assertThat(tokens.countByUserId(account.id)).isEqualTo(1)

        mvc.perform(delete("/api/v1/users/${account.id}").header("Authorization", account.bearer))
            .andExpect(status().isConflict)

        assertThat(users.findById(account.id)).isPresent
        assertThat(tokens.countByUserId(account.id)).isEqualTo(1)
        assertThat(documents.findById(privateDocument.id)).isPresent
        mvc.perform(get("/api/v1/auth/me").header("Authorization", account.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.id").value(account.id.toString()))
        mvc.perform(get("/api/v1/documents/${privateDocument.id}").header("Authorization", account.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.id").value(privateDocument.id.toString()))
    }

    @AfterEach
    fun cleanupUploadedDocuments() {
        createdDocuments.forEach { (id, cleanupToken) ->
            val file = documents.findById(id).orElse(null)?.storageKey?.let { key ->
                Paths.get(System.getProperty("java.io.tmpdir"), "paperless-documents", key.substringAfterLast('/'))
            }
            val deleted = runCatching {
                mvc.perform(delete("/api/v1/documents/$id").header("Authorization", "Bearer $cleanupToken"))
                    .andReturn().response.status == 204
            }.getOrDefault(false)
            if (!deleted) file?.let { runCatching { Files.deleteIfExists(it) } }
        }
        createdDocuments.clear()
    }

    @Test
    fun document_type_can_be_explicitly_cleared_without_changing_null_update_semantics_ok() {
        // given
        val suffix = System.nanoTime()
        val owner = registerAndLogin("typeowner$suffix")
        val document = upload(owner, owner, "typeclearprobe")
        val typeId = mvc.perform(post("/api/v1/document-types").header("Authorization", owner.bearer)
            .contentType(MediaType.APPLICATION_JSON).content("""{"name":"Type $suffix"}"""))
            .andExpect(status().isCreated)
            .andReturn().response.contentAsString.let { jsonUuid(it, "id") }
        mvc.perform(put("/api/v1/documents/${document.id}").header("Authorization", owner.bearer)
            .contentType(MediaType.APPLICATION_JSON).content("""{"document_type_id":"$typeId"}"""))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.document_type.id").value(typeId.toString()))

        // when / then
        mvc.perform(put("/api/v1/documents/${document.id}").header("Authorization", owner.bearer)
            .contentType(MediaType.APPLICATION_JSON).content("""{"document_type_id":null}"""))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.document_type.id").value(typeId.toString()))
        mvc.perform(put("/api/v1/documents/${document.id}").header("Authorization", owner.bearer)
            .contentType(MediaType.APPLICATION_JSON).content("""{"title":"Renamed"}"""))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.document_type.id").value(typeId.toString()))
        mvc.perform(put("/api/v1/documents/${document.id}").header("Authorization", owner.bearer)
            .contentType(MediaType.APPLICATION_JSON)
            .content("""{"document_type_id":"$typeId","clear_document_type":true}"""))
            .andExpect(status().isBadRequest)
        mvc.perform(put("/api/v1/documents/${document.id}").header("Authorization", owner.bearer)
            .contentType(MediaType.APPLICATION_JSON).content("""{"clear_document_type":true}"""))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.document_type").value(org.hamcrest.Matchers.nullValue()))
            .andExpect(jsonPath("$.title").value("Renamed"))
        mvc.perform(get("/api/v1/documents/${document.id}").header("Authorization", owner.bearer))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.document_type").value(org.hamcrest.Matchers.nullValue()))
    }

    private fun registerAndLogin(username: String): Account {
        val password = "document-security-password"
        val registration = mvc.perform(post("/api/v1/users").contentType(MediaType.APPLICATION_JSON)
            .content("""{"username":"$username","password":"$password"}"""))
            .andExpect(status().isCreated)
            .andExpect(jsonPath("$.password").doesNotExist())
            .andReturn().response.contentAsString
        val id = jsonUuid(registration, "id")
        val login = mvc.perform(post("/api/v1/auth/login").contentType(MediaType.APPLICATION_JSON)
            .content("""{"username":"$username","password":"$password"}"""))
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.token_type").value("Bearer"))
            .andReturn().response.contentAsString
        val token = Regex("\"token\":\"([^\"]+)\"").find(login)!!.groupValues[1]
        return Account(id, token)
    }

    private fun createTeam(token: String, suffix: Long): UUID =
        mvc.perform(post("/api/v1/teams").header("Authorization", "Bearer $token")
            .contentType(MediaType.APPLICATION_JSON)
            .content("""{"name":"Document security $suffix"}"""))
            .andExpect(status().isCreated)
            .andReturn().response.contentAsString.let { jsonUuid(it, "id") }

    private fun addMember(token: String, teamId: UUID, member: Account, role: String) {
        mvc.perform(post("/api/v1/teams/$teamId/members").header("Authorization", "Bearer $token")
            .contentType(MediaType.APPLICATION_JSON)
            .content("""{"user_id":"${member.id}","role":"$role"}"""))
            .andExpect(status().isCreated)
            .andExpect(jsonPath("$.role").value(role))
    }

    private fun upload(
        uploader: Account,
        cleanupAccount: Account,
        title: String,
        teamId: UUID? = null
    ): UploadedDocument {
        val content = "$title\nGenerated integration PDF payload".toByteArray()
        val result = mvc.perform(uploadRequest(title, teamId).header("Authorization", uploader.bearer))
            .andExpect(status().isCreated)
            .andReturn()
        val body = result.response.contentAsString
        val id = jsonUuid(body, "id")
        createdDocuments[id] = cleanupAccount.token
        assertThat(result.response.getHeader("Location")).isEqualTo("/api/v1/documents/$id")
        jsonPath("$.title").value(title).match(result)
        jsonPath("$.owner_id").value(uploader.id.toString()).match(result)
        jsonPath("$.original_filename").value("$title.pdf").match(result)
        jsonPath("$.content_type").value(MediaType.APPLICATION_PDF_VALUE).match(result)
        jsonPath("$.file_size").value(content.size).match(result)
        jsonPath("$.status").value("PENDING").match(result)
        if (teamId != null) jsonPath("$.team_id").value(teamId.toString()).match(result)
        else jsonPath("$.team_id").value(org.hamcrest.Matchers.nullValue()).match(result)
        return UploadedDocument(id, content)
    }

    private fun uploadRequest(title: String, teamId: UUID?): MockMultipartHttpServletRequestBuilder {
        val request = multipart("/api/v1/documents")
            .file(MockMultipartFile("document", "$title.pdf", MediaType.APPLICATION_PDF_VALUE,
                "$title\nGenerated integration PDF payload".toByteArray()))
            .param("title", title)
        if (teamId != null) {
            request.param("team_id", teamId.toString())
        }
        return request
    }

    private fun jsonUuid(json: String, field: String): UUID =
        Regex("\"$field\":\\s*\"([^\"]+)\"").find(json)?.groupValues?.get(1)?.let(UUID::fromString)
            ?: error("Missing UUID '$field' in response: $json")

    private data class Account(val id: UUID, val token: String) {
        val bearer: String get() = "Bearer $token"
    }

    private data class UploadedDocument(val id: UUID, val content: ByteArray)
}
```
