feat(sshd_config): Add analyzer support for tokens

This commit is contained in:
Myzel394 2024-10-15 16:25:14 +02:00
parent c463053bbf
commit 33a58a3cc3
No known key found for this signature in database
GPG Key ID: ED20A1D1D423AF3F
3 changed files with 112 additions and 0 deletions

View File

@ -55,6 +55,7 @@ func Analyze(
} }
analyzeMatchBlocks(ctx) analyzeMatchBlocks(ctx)
analyzeTokens(ctx)
return ctx.diagnostics return ctx.diagnostics
} }

View File

@ -0,0 +1,49 @@
package analyzer
import (
"config-lsp/common"
"config-lsp/handlers/sshd_config/fields"
"config-lsp/utils"
"fmt"
"strings"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func analyzeTokens(
ctx *analyzerContext,
) {
for _, option := range ctx.document.Config.GetAllOptions() {
if option.Key == nil || option.OptionValue == nil {
continue
}
key := option.Key.Key
text := option.OptionValue.Value.Value
var tokens []string
if foundTokens, found := fields.OptionsTokensMap[key]; found {
tokens = foundTokens
} else {
tokens = []string{}
}
disallowedTokens := utils.Without(utils.KeysOfMap(fields.AvailableTokens), tokens)
for _, token := range disallowedTokens {
if strings.Contains(text, token) {
optionName := string(key)
if formatted, found := fields.FieldsNameFormattedMap[key]; found {
optionName = formatted
}
ctx.diagnostics = append(ctx.diagnostics, protocol.Diagnostic{
Range: option.OptionValue.ToLSPRange(),
Message: fmt.Sprintf("Token '%s' is not allowed for option '%s'", token, optionName),
Severity: &common.SeverityError,
})
}
}
}
}

View File

@ -0,0 +1,62 @@
package analyzer
import (
testutils_test "config-lsp/handlers/sshd_config/test_utils"
"testing"
protocol "github.com/tliron/glsp/protocol_3_16"
)
func TestInvalidTokensForNonExisting(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
ThisOptionDoesNotExist Hello%%World
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if !(len(ctx.diagnostics) == 1) {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}
func TestInvalidTokensForExistingOption(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
Tunnel Hello%%World
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if !(len(ctx.diagnostics) == 1) {
t.Errorf("Expected 1 error, got %v", len(ctx.diagnostics))
}
}
func TestValidTokens(
t *testing.T,
) {
d := testutils_test.DocumentFromInput(t, `
AuthorizedPrincipalsCommand Hello World %% and %d
`)
ctx := &analyzerContext{
document: d,
diagnostics: make([]protocol.Diagnostic, 0),
}
analyzeTokens(ctx)
if len(ctx.diagnostics) > 0 {
t.Fatalf("Expected no errors, but got %v", len(ctx.diagnostics))
}
}