Ensure string schema with broad pattern

Ensure that any string schema in the OpenAPI document has a broad pattern using ^ and $ symbols. A string schema is a way of describing a data type that consists of a sequence of characters, such as text, dates, or identifiers. A pattern is a property that specifies a regular expression that the string value must match. A regular expression is a sequence of symbols and characters that define a search pattern for strings. A broad pattern is a pattern that does not restrict the string value much and allows many possible values. For example, the pattern ^.*$ matches any string, including an empty string. The reason why any string schema should be with broad pattern using ^ and $ in OpenAPI is to avoid ambiguity and confusion about the meaning and validity of the string value. The ^ and $ symbols are special characters in regular expressions that indicate the beginning and the end of the string, respectively. By using them, you can ensure that the whole string value matches the pattern, and not just a part of it.

Risk Level: medium
Platform: OpenAPI
Spectral Rule ID: OPENAPI019

REMEDIATION

Add or modify the pattern property for any string schema in the OpenAPI document and use ^ and $ symbols to indicate the start and end of the string value. For example:

components: schemas: Email: type: string format: email pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ # This is a broad pattern for email addresses Date: type: string format: date pattern: ^\d{4}-\d{2}-\d{2}$ # This is a broad pattern for dates in YYYY-MM-DD format
# This is a sample OpenAPI document with some string schemas without broad patterns openapi: 3.0.0 info: title: Sample API version: 1.0.0 servers: - url: https://api.example.com/v1 paths: /users/{id}: get: summary: Get user by id parameters: - name: id in: path required: true schema: type: integer format: int64 responses: '200': description: A user object content: application/json: schema: type: object properties: id: type: integer format: int64 name: type: string email: type: string format: email # This string schema has no pattern property birthday: type: string format: date # This string schema has no pattern property + # Add or modify the pattern property for any string schema in the OpenAPI document components: schemas: Email: type: string format: email + pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ # This is a broad pattern for email addresses Date: type: string format: date + pattern: ^\d{4}-\d{2}-\d{2}$ # This is a broad pattern for dates in YYYY-MM-DD format

Read more:


Did this page help you?