Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions wiki/src/main/java/com/scalesec/vulnado/Comment.java.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Documentation: `Comment` Class

## Overview

The `Comment` class is a Java implementation for managing user comments. It provides functionality to create, retrieve, and delete comments from a PostgreSQL database. Each comment is represented by attributes such as `id`, `username`, `body`, and `created_on`. The class interacts with the database using SQL queries and leverages JDBC for database connectivity.

---

## Class Details

### Package
The class is part of the `com.scalesec.vulnado` package.

### Dependencies
The class relies on the following imports:
- `org.apache.catalina.Server` (Unused in the current implementation)
- `java.sql.*` (For database operations)
- `java.util.*` (For utility classes like `Date`, `List`, `ArrayList`, and `UUID`)

---

## Attributes

| Attribute | Type | Description |
|--------------|--------------|------------------------------------------|
| `id` | `String` | Unique identifier for the comment. |
| `username` | `String` | Username of the person who made the comment. |
| `body` | `String` | Content of the comment. |
| `created_on` | `Timestamp` | Timestamp indicating when the comment was created. |

---

## Constructor

### `Comment(String id, String username, String body, Timestamp created_on)`
Initializes a new `Comment` object with the provided attributes.

| Parameter | Type | Description |
|---------------|-------------|------------------------------------------|
| `id` | `String` | Unique identifier for the comment. |
| `username` | `String` | Username of the person who made the comment. |
| `body` | `String` | Content of the comment. |
| `created_on` | `Timestamp` | Timestamp indicating when the comment was created. |

---

## Methods

### `static Comment create(String username, String body)`
Creates a new comment and saves it to the database.

| Parameter | Type | Description |
|-------------|-----------|------------------------------------------|
| `username` | `String` | Username of the person creating the comment. |
| `body` | `String` | Content of the comment. |

- Generates a unique `id` using `UUID`.
- Sets the `created_on` timestamp to the current time.
- Calls the private `commit()` method to save the comment to the database.
- Throws a `BadRequest` exception if the comment cannot be saved.
- Throws a `ServerError` exception in case of other errors.

---

### `static List<Comment> fetch_all()`
Retrieves all comments from the database.

| Return Type | Description |
|-------------|------------------------------------------|
| `List<Comment>` | A list of all comments stored in the database. |

- Executes a `SELECT * FROM comments` query.
- Maps each row in the result set to a `Comment` object.
- Returns a list of `Comment` objects.

---

### `static Boolean delete(String id)`
Deletes a comment from the database based on its `id`.

| Parameter | Type | Description |
|-----------|-----------|------------------------------------------|
| `id` | `String` | Unique identifier of the comment to delete. |

| Return Type | Description |
|-------------|------------------------------------------|
| `Boolean` | `true` if the comment was successfully deleted, `false` otherwise. |

- Executes a `DELETE FROM comments WHERE id = ?` query.
- Uses a prepared statement to prevent SQL injection.

---

### `private Boolean commit() throws SQLException`
Saves the current `Comment` object to the database.

| Return Type | Description |
|-------------|------------------------------------------|
| `Boolean` | `true` if the comment was successfully saved, `false` otherwise. |

- Executes an `INSERT INTO comments` query.
- Uses a prepared statement to insert the comment attributes into the database.

---

## Insights

1. **Database Dependency**: The class relies on a `Postgres.connection()` method to establish a database connection. This method is not defined in the class and is assumed to be part of another utility class.

2. **Error Handling**:
- The `create` method throws custom exceptions (`BadRequest` and `ServerError`) for specific error scenarios.
- Other methods use `try-catch` blocks but do not propagate exceptions effectively, which may lead to silent failures.

3. **SQL Injection Prevention**: Prepared statements are used in the `commit` and `delete` methods to prevent SQL injection attacks.

4. **Unused Import**: The `org.apache.catalina.Server` import is not used in the current implementation and can be removed.

5. **Potential Bug in `delete` Method**:
- The `finally` block always returns `false`, overriding the actual result of the `executeUpdate()` method. This needs to be corrected.

6. **Scalability**:
- The `fetch_all` method retrieves all comments without any pagination or filtering, which may lead to performance issues with large datasets.

7. **Thread Safety**: The class is not thread-safe as it uses shared database connections without synchronization.

8. **Timestamp Handling**: The `created_on` timestamp is generated using the system's current time, which may lead to inconsistencies in distributed systems.

---

## Potential Enhancements

- **Pagination**: Add support for pagination in the `fetch_all` method to handle large datasets efficiently.
- **Connection Pooling**: Use a connection pool to manage database connections more effectively.
- **Validation**: Add input validation for `username` and `body` to ensure data integrity.
- **Logging**: Replace `System.err.println` with a proper logging framework for better error tracking and debugging.
- **Unit Tests**: Implement unit tests to validate the functionality of each method.
133 changes: 133 additions & 0 deletions wiki/src/main/java/com/scalesec/vulnado/CommentsController.java.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Documentation: `CommentsController.java`

## Overview

The `CommentsController` class is a RESTful controller implemented using the Spring Boot framework. It provides endpoints for managing comments, including fetching, creating, and deleting comments. The controller enforces authentication via a custom header (`x-auth-token`) and supports cross-origin requests.

## Features

- **Authentication**: Validates requests using a token passed in the `x-auth-token` header.
- **Endpoints**:
- Fetch all comments (`GET /comments`)
- Create a new comment (`POST /comments`)
- Delete a comment by ID (`DELETE /comments/{id}`)
- **Error Handling**: Custom exceptions for `BadRequest` and `ServerError` with appropriate HTTP status codes.
- **Cross-Origin Resource Sharing (CORS)**: Allows requests from any origin.

---

## Class Details

### 1. `CommentsController`

#### Annotations
- `@RestController`: Marks the class as a RESTful controller.
- `@EnableAutoConfiguration`: Enables Spring Boot's auto-configuration feature.
- `@CrossOrigin(origins = "*")`: Allows cross-origin requests from any domain.

#### Fields
| Field Name | Type | Description |
|------------|--------|--------------------------------------|
| `secret` | String | Application secret for authentication. |

#### Methods

| Method Name | HTTP Method | Endpoint | Description |
|-------------------|-------------|---------------------|-----------------------------------------------------------------------------|
| `comments` | `GET` | `/comments` | Fetches all comments. Requires `x-auth-token` for authentication. |
| `createComment` | `POST` | `/comments` | Creates a new comment. Requires `x-auth-token` and a JSON body. |
| `deleteComment` | `DELETE` | `/comments/{id}` | Deletes a comment by its ID. Requires `x-auth-token` for authentication. |

#### Method Details

1. **`comments`**
- **Parameters**:
- `@RequestHeader(value="x-auth-token") String token`: Authentication token.
- **Returns**: A list of all comments (`List<Comment>`).
- **Logic**:
- Validates the token using `User.assertAuth(secret, token)`.
- Fetches all comments using `Comment.fetch_all()`.

2. **`createComment`**
- **Parameters**:
- `@RequestHeader(value="x-auth-token") String token`: Authentication token.
- `@RequestBody CommentRequest input`: JSON body containing the comment details.
- **Returns**: The created comment (`Comment`).
- **Logic**:
- Creates a new comment using `Comment.create(input.username, input.body)`.

3. **`deleteComment`**
- **Parameters**:
- `@RequestHeader(value="x-auth-token") String token`: Authentication token.
- `@PathVariable("id") String id`: ID of the comment to delete.
- **Returns**: A boolean indicating success or failure (`Boolean`).
- **Logic**:
- Deletes the comment using `Comment.delete(id)`.

---

### 2. `CommentRequest`

#### Description
A data structure representing the request body for creating a comment.

#### Fields
| Field Name | Type | Description |
|------------|--------|------------------------------|
| `username` | String | The username of the commenter. |
| `body` | String | The content of the comment. |

#### Notes
- Implements `Serializable` for potential serialization needs.

---

### 3. `BadRequest`

#### Description
A custom exception representing a `400 Bad Request` error.

#### Annotations
- `@ResponseStatus(HttpStatus.BAD_REQUEST)`: Maps the exception to a `400 Bad Request` HTTP status.

#### Constructor
| Parameter | Type | Description |
|-------------|--------|---------------------------------|
| `exception` | String | The error message for the exception. |

---

### 4. `ServerError`

#### Description
A custom exception representing a `500 Internal Server Error`.

#### Annotations
- `@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)`: Maps the exception to a `500 Internal Server Error` HTTP status.

#### Constructor
| Parameter | Type | Description |
|-------------|--------|---------------------------------|
| `exception` | String | The error message for the exception. |

---

## Insights

1. **Authentication**:
- The `User.assertAuth(secret, token)` method is used for token validation. This implies a dependency on the `User` class, which is not included in this file.

2. **Comment Management**:
- The `Comment` class is responsible for fetching, creating, and deleting comments. Its implementation is not provided, but it is expected to handle database interactions or other storage mechanisms.

3. **CORS Configuration**:
- The `@CrossOrigin(origins = "*")` annotation allows requests from any origin. This is useful for development but may pose security risks in production if not restricted to specific domains.

4. **Error Handling**:
- Custom exceptions (`BadRequest` and `ServerError`) provide a clear mechanism for handling and responding to errors with appropriate HTTP status codes.

5. **Scalability**:
- The controller assumes a flat structure for comments. If nested or hierarchical comments are required, additional logic would need to be implemented.

6. **Security**:
- The use of a secret for token validation suggests a shared secret-based authentication mechanism. Consider using more robust authentication methods (e.g., OAuth2) for production systems.
45 changes: 45 additions & 0 deletions wiki/src/main/java/com/scalesec/vulnado/CowController.java.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# CowController Documentation

## Overview
The `CowController` class is a Spring Boot REST controller that provides an endpoint for generating text output using the `Cowsay` utility. It is designed to handle HTTP requests and return a response based on the input provided by the user.

## Class Details

### Metadata
- **File Name**: `CowController.java`
- **Package**: `com.scalesec.vulnado`

### Annotations
- `@RestController`: Indicates that this class is a REST controller, meaning it handles HTTP requests and returns responses in a RESTful manner.
- `@EnableAutoConfiguration`: Enables Spring Boot's auto-configuration mechanism, which automatically configures the application based on its dependencies.

### Dependencies
- **Spring Framework**: Used for REST API development and dependency injection.
- **Cowsay Utility**: A utility (assumed to be implemented elsewhere) that generates ASCII art text output.

## Endpoint

### `/cowsay`
#### Description
This endpoint generates a response using the `Cowsay` utility. The user can provide an input string, which will be processed and returned as ASCII art.

#### HTTP Method
- `GET`

#### Parameters
| Name | Type | Default Value | Description |
|------------|--------|---------------------|-----------------------------------------------------------------------------|
| `input` | String | `"I love Linux!"` | The text to be processed by the `Cowsay` utility. If not provided, defaults to `"I love Linux!"`. |

#### Response
- **Type**: `String`
- **Description**: Returns the ASCII art generated by the `Cowsay` utility based on the input string.

## Insights
- **Security Considerations**: The `input` parameter is directly passed to the `Cowsay.run()` method. If `Cowsay.run()` executes system commands or processes the input in an unsafe manner, this could lead to vulnerabilities such as command injection. Proper input validation and sanitization should be implemented to mitigate risks.
- **Default Behavior**: If no input is provided, the endpoint defaults to the message `"I love Linux!"`, ensuring the endpoint always returns a meaningful response.
- **Scalability**: The controller is lightweight and does not maintain state, making it suitable for scaling in distributed systems.
- **Extensibility**: Additional endpoints or features can be added to the controller to expand its functionality.

## Related Components
- **Cowsay Utility**: The `Cowsay.run()` method is assumed to be implemented elsewhere in the application. Its functionality and implementation details are critical to understanding the behavior of this controller.
Loading