Inconsistency Between Implementation and Documented Design

Description

Inconsistency Between Implementation and Documented Design occurs when the implementation of a product is not consistent with the design as described within the relevant documentation. This includes discrepancies between architecture documents and actual code structure, API documentation that doesn't match actual behavior, security design documents that describe controls not actually implemented, and configuration guides that don't reflect actual settings. These inconsistencies create confusion, increase maintenance burden, and can have security implications when assumed security controls are not actually in place.

Risk

Documentation inconsistency creates indirect but significant security risks. Security controls documented but not implemented give false assurance. Security auditors may approve systems based on inaccurate documentation. Developers may make insecure assumptions based on outdated design docs. Incident response is hindered when documentation doesn't match reality. Compliance violations occur when documented controls are not implemented. Threat models based on inaccurate architecture diagrams miss real attack vectors. Users and integrators may misconfigure systems based on wrong documentation.

Solution

Implement documentation-as-code practices where documentation is versioned alongside code. Use automated tools to generate API documentation from code (OpenAPI, JSDoc, etc.). Include documentation updates in code review checklists. Conduct regular documentation audits comparing docs to implementation. Use architecture fitness functions to verify implementation matches design. Automate testing of documented behavior. Create traceability between requirements, design docs, and implementation. Use living documentation that updates with the code. Include documentation accuracy in definition of done.

Common Consequences

ImpactDetails
OtherScope: Other

Reduce Maintainability - Inconsistent documentation makes the system harder to understand and maintain correctly.
OtherScope: Other

Quality Degradation - Developers and users make incorrect assumptions based on wrong documentation.
Access ControlScope: Access Control

Bypass Protection Mechanism - Documented security controls may not actually be implemented.

Example Code

Vulnerable Code

// The "code" for this CWE demonstrates documentation/implementation mismatch

/* ============================================================
   EXAMPLE OF DOCUMENTATION/IMPLEMENTATION INCONSISTENCY
   ============================================================

   API DOCUMENTATION (api-docs.yaml):
   ----------------------------------

   /api/users/{id}:
     get:
       description: Get user by ID
       security:
         - bearerAuth: []           # Doc says auth required
       parameters:
         - name: id
           in: path
           required: true
           schema:
             type: integer
       responses:
         200:
           description: User object
           content:
             application/json:
               schema:
                 type: object
                 properties:
                   id:
                     type: integer
                   username:
                     type: string
                   email:
                     type: string   # Doc shows email in response

   ACTUAL IMPLEMENTATION:
   ---------------------
*/

// The actual code doesn't match the documentation
@RestController
public class UserController {

    @GetMapping("/api/users/{id}")
    // MISMATCH: No @Secured annotation - auth not actually required!
    public User getUser(@PathVariable String id) {  // MISMATCH: String, not integer
        User user = userService.findById(id);

        // MISMATCH: Returns password hash too, not documented!
        return user;
    }
}

public class User {
    private String id;        // MISMATCH: String, docs say integer
    private String username;
    private String email;
    private String password;  // SECURITY: Returned but not documented!
    private String ssn;       // SECURITY: Sensitive data not in docs!
}

/* ============================================================
   SECURITY ARCHITECTURE DOCUMENT (security-design.md):
   ============================================================

   "All API endpoints require JWT authentication.
    Passwords are hashed using bcrypt with cost factor 12.
    All sensitive data is encrypted at rest using AES-256.
    Rate limiting is applied: 100 requests per minute per user."

   ACTUAL IMPLEMENTATION DISCREPANCIES:
   -----------------------------------
*/

@Configuration
public class SecurityConfig {

    // MISMATCH: Some endpoints are public, contrary to docs
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) {
        http.authorizeRequests()
            .antMatchers("/api/public/**").permitAll()  // Not documented!
            .antMatchers("/api/admin/**").permitAll()   // SECURITY HOLE!
            .anyRequest().authenticated();

        return http.build();
    }

    // MISMATCH: bcrypt cost is 10, docs say 12
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);  // Docs say 12!
    }

    // MISSING: No rate limiting implemented at all!
}

// MISSING: No encryption at rest - data stored in plaintext
@Entity
public class SensitiveData {
    private String creditCardNumber;  // Not encrypted!
    private String ssn;               // Not encrypted!
}

Fixed Code

// Fixed: Documentation automatically generated from code

/**
 * User Controller - handles user-related API operations.
 *
 * Security: All endpoints require JWT authentication unless marked otherwise.
 * Rate Limit: 100 requests/minute per authenticated user.
 */
@RestController
@RequestMapping("/api/users")
@Validated
@Tag(name = "Users", description = "User management endpoints")
public class FixedUserController {

    private final UserService userService;

    /**
     * Get user by ID.
     *
     * @param id User ID (UUID format)
     * @return User details (excludes sensitive fields)
     * @throws NotFoundException if user not found
     */
    @GetMapping("/{id}")
    @Secured("ROLE_USER")  // Fixed: Auth enforced by annotation
    @Operation(
        summary = "Get user by ID",
        description = "Retrieves user details. Requires authentication.",
        security = @SecurityRequirement(name = "bearerAuth")
    )
    @ApiResponses({
        @ApiResponse(
            responseCode = "200",
            description = "User found",
            content = @Content(schema = @Schema(implementation = UserResponse.class))
        ),
        @ApiResponse(responseCode = "401", description = "Not authenticated"),
        @ApiResponse(responseCode = "404", description = "User not found")
    })
    public UserResponse getUser(
        @Parameter(description = "User UUID", required = true)
        @PathVariable UUID id  // Fixed: Type matches documentation
    ) {
        User user = userService.findById(id);
        return UserResponse.fromUser(user);  // Fixed: DTO excludes sensitive data
    }
}

// Fixed: Response DTO - only contains documented fields
@Schema(description = "User response object")
public class UserResponse {

    @Schema(description = "User ID", example = "123e4567-e89b-12d3-a456-426614174000")
    private UUID id;

    @Schema(description = "Username", example = "johndoe")
    private String username;

    @Schema(description = "Email address", example = "[email protected]")
    private String email;

    // Fixed: No password, SSN, or other sensitive fields exposed

    public static UserResponse fromUser(User user) {
        UserResponse response = new UserResponse();
        response.id = user.getId();
        response.username = user.getUsername();
        response.email = user.getEmail();
        // Sensitive fields intentionally excluded
        return response;
    }
}
// Fixed: Security configuration matches documentation
@Configuration
@EnableWebSecurity
public class FixedSecurityConfig {

    // Fixed: Configuration matches security design document
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                // Fixed: Public endpoints explicitly documented
                .antMatchers("/api/health", "/api/docs/**").permitAll()
                // Fixed: All other endpoints require authentication
                .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer()
                .jwt();

        return http.build();
    }

    // Fixed: bcrypt cost matches documentation (12)
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

    // Fixed: Rate limiting implemented as documented
    @Bean
    public RateLimiter rateLimiter() {
        return RateLimiter.of("api",
            RateLimiterConfig.custom()
                .limitForPeriod(100)           // 100 requests
                .limitRefreshPeriod(Duration.ofMinutes(1))  // per minute
                .build());
    }
}

// Fixed: Encryption at rest implemented as documented
@Entity
@EntityListeners(EncryptionListener.class)
public class FixedSensitiveData {

    @Id
    private UUID id;

    @Encrypted  // Custom annotation triggers AES-256 encryption
    private String creditCardNumber;

    @Encrypted
    private String ssn;
}

// Fixed: Automated documentation verification test
@SpringBootTest
public class DocumentationConsistencyTest {

    @Autowired
    private SecurityFilterChain securityFilterChain;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Test
    void securityConfigurationMatchesDocumentation() {
        // Verify bcrypt cost factor is 12 as documented
        BCryptPasswordEncoder bcrypt = (BCryptPasswordEncoder) passwordEncoder;
        // Assert configuration matches docs

        // Verify all non-public endpoints require authentication
        // This test fails if configuration doesn't match documentation
    }

    @Test
    void allSensitiveFieldsAreEncrypted() {
        // Use reflection to verify all @Encrypted fields
        // are properly handled
    }
}
# Fixed: OpenAPI spec generated from code annotations
# Generated by springdoc-openapi from actual code

openapi: 3.0.3
info:
  title: User Management API
  version: 1.0.0
  description: |
    API for user management operations.

    ## Security
    All endpoints require JWT authentication unless specified otherwise.

    ## Rate Limiting
    100 requests per minute per authenticated user.

security:
  - bearerAuth: []

paths:
  /api/users/{id}:
    get:
      tags:
        - Users
      summary: Get user by ID
      description: Retrieves user details. Requires authentication.
      operationId: getUser
      parameters:
        - name: id
          in: path
          description: User UUID
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: User found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserResponse'
        '401':
          description: Not authenticated
        '404':
          description: User not found
      security:
        - bearerAuth: []

components:
  schemas:
    UserResponse:
      type: object
      description: User response object
      properties:
        id:
          type: string
          format: uuid
          description: User ID
          example: 123e4567-e89b-12d3-a456-426614174000
        username:
          type: string
          description: Username
          example: johndoe
        email:
          type: string
          format: email
          description: Email address
          example: [email protected]
      # Note: password, ssn, and other sensitive fields
      # are intentionally excluded from the response

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

CVE Examples

This CWE is marked as PROHIBITED for direct CVE mapping as it represents a documentation/quality concern rather than a direct security vulnerability.


  • CWE-710: Improper Adherence to Coding Standards (parent)
  • CWE-1059: Insufficient Technical Documentation (related)
  • CWE-1225: Documentation Issues (category member)

References

  1. MITRE Corporation. "CWE-1068: Inconsistency Between Implementation and Documented Design." https://cwe.mitre.org/data/definitions/1068.html
  2. Docs as Code. "Documentation as Code Principles." https://www.writethedocs.org/guide/docs-as-code/
  3. OpenAPI Initiative. "OpenAPI Specification." https://swagger.io/specification/