Skip to content

feat(system): add session check for agent api#8258

Merged
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@app
Mar 26, 2025
Merged

feat(system): add session check for agent api#8258
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@app

Conversation

@zhengkunwang223
Copy link
Copy Markdown
Member

No description provided.

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Mar 26, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

func checkSession(c *gin.Context) bool {
_, err := global.SESSION.Get(c)
return err == nil
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. handlenotroute has two calls to CheckSecurity, one inside another. This could lead to unnecessary overhead if multiple requests need to pass through this function without being redirected.

  2. Some functions like HandleNotSecurity, IsEntrancePath, etc., perform similar checks on c.Request.URL.Path. These duplicate logic can be extracted into utility functions or reused directly instead of repeating them.

  3. The function toindexhtml writes raw HTML which should always be sanitized before rendering to prevent XSS attacks.

  4. Function names are too short, making it hard to understand their responsibilities and usage within different context.

  5. Comments should be clearer about what each function does and why certain conditions were chosen.

  6. The error handling within HandleNoTSecurity seems redundant since there's no way to return from that function if an error occurs while reading the file contents.

  7. Using constants for hardcoded values like "err_domain" and "200_200" would make your code cleaner and easier to maintain.

  8. Checking IP addresses against CIDR ranges needs a dedicated helper method for better readability and clarity. Instead of using regular expressions for such comparisons.

  9. In some places where checking against empty strings (len(status.value) == 0) it might indicate that these config variables aren't properly configured at initialization stage but haven't been validated yet leading to incorrect behavior during runtime. Adding more verbose log statements can help diagnose these issues earlier.

Overall this implementation looks good overall aside mostly from the few optimizations described above.

security.HandleNotSecurity(c, "")
})

return Router
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are several changes made and improvements suggested in this code snippet:

  1. Imports: Some imports have been added back to fix compilation errors.

  2. Function Moves:

    • toIndexHtml was moved into the security package since it handles index HTML rendering which is security-related now.
    • handleNoRoute, checkEntrance, checkFrontendPath, checkBindDomain, checkIPLimit, and checkSession were all converted to security.*.
  3. Logic Changes:

    • The authentication logic has been consolidated under middleware.ApiAuth() for API routes.
    • No-route handling functions (handleNoRoute and related checks) have been deprecated and replaced with corresponding methods in the security package like HandleNotSecurity and HandleNotRoute.
  4. Documentation Update:

    • Comments mentioning isFrontendPath, checkFrontendPath, checkSession, etc., have been removed as these are no longer needed after consolidation.
  5. Variable Renames:

    • Certain variables like entrance were renamed within their respective packages to avoid conflicts or misidentification.
  6. Consistent Function Calls:

    • Most function calls across the file now use lowercase letters unless necessary (e.g., CheckSecurity instead of checkSecurity) to adhere to Go coding standards.

These changes aim to improve consistency, maintainability, and clarity, especially in areas dealing with security-related paths and functionality.

hash := md5.New()
hash.Write([]byte(param))
return hex.EncodeToString(hash.Sum(nil))
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has several issues and areas for improvement:

Issues:

  1. Magic Numbers: The use of constants like tolerance and 60 across multiple places could lead to magic numbers. Consider defining these as named variables within functions where they're used.

  2. Error Handling in Logs: The logging calls can be optimized by using formatted logs instead of printing raw errors directly to logs.

  3. Repetition in Code: Functions like isValid1PanelTimestamp, isValid1PanelToken, and GenerateMD5 have similar logic repeated in different methods. This redundancy can be streamlined.

  4. Security Concerns:

    • The MD5 hashing function should be replaced with stronger cryptographic algorithms that resist collision attacks, such as SHA-256.
  5. Documentation: Comments are present but not detailed enough to explain how each part of the code works.

  6. Performance: Ensure that parsing IP addresses and validating CIDRs efficiently.

Optimization Suggestions:

  1. Use Named Variables for Tolerances: For example, instead of writing int64(60) repeatedly, define them at the top level or in local contexts.

Example refactored version:

const (
    defaultTolerance = 60 // seconds tolerance allowed
)

// Define other constants similarly

func ValidateAPITokenAndPermissionMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core/auth") {
            c.Next()
            return
        }

        panelToken := c.GetHeader("1Panel-Token")
        apiKeyTimestamp := c.GetHeader("1Panel-Timestamp")

        // Check API interface status and timestamps etc...
    }
}

func IsValidAPIKeyTimestamp(timestampStr string, validTimeInSeconds int, currentTimeOffsetSeconds int) bool {
    currentUnixTime := getCurrentUnixTime(currentTimeOffsetSeconds)

    parsedTimestamp, err := strconv.ParseInt(timestampStr, 10, 64)
    if err != nil {
        log.Printf("Failed to parse timestamp: %v\n", err)
        return false
    }

    thresholdTime := currentUnixTime + time.Duration(validTimeInSeconds)*time.Second

    if parsedTimestamp > thresholdTime {
        log.Println("Invalid API key timestamp.")
        return false
    }

    return true
}

func GetCurrentUnixTime(offsetSeconds int) int64 {
    current := time.Now().Unix()

    // Apply offset if needed
    current += int64(offsetSeconds)
    return current
}

func GenerateSecureHash(message string) string {
    hash := sha256.New()
    hash.Write([]byte(message))
    return hex.EncodeToString(hash.Sum(nil))
}

This refactoring reduces repetition, improves logging quality by formatting messages properly, and enhances security by utilizing a stronger encryption method (sha256) and ensuring proper error handling and parameter validation.

@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown
Member

@wanghe-fit2cloud wanghe-fit2cloud left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/lgtm

@wanghe-fit2cloud
Copy link
Copy Markdown
Member

/approve

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Mar 26, 2025

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wanghe-fit2cloud

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@f2c-ci-robot f2c-ci-robot Bot merged commit 220b622 into dev-v2 Mar 26, 2025
6 checks passed
@f2c-ci-robot f2c-ci-robot Bot deleted the pr@dev-v2@app branch March 26, 2025 08:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants