Skip to content

Commit

Permalink
VDR: Validate subject to a sensible pattern (#3338)
Browse files Browse the repository at this point in the history
  • Loading branch information
reinkrul authored Sep 4, 2024
1 parent 256ba79 commit d0878cf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions vdr/didsubject/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/nuts-foundation/nuts-node/vdr/log"
"gorm.io/gorm"
"strings"
"regexp"
"time"
)

Expand All @@ -44,6 +45,9 @@ var ErrSubjectAlreadyExists = errors.New("subject already exists")
// ErrSubjectNotFound is returned when a subject is not found.
var ErrSubjectNotFound = errors.New("subject not found")

// subjectPattern is a regular expression for checking whether a subject follows the allowed pattern; a-z, 0-9, -, _, . (case insensitive)
var subjectPattern = regexp.MustCompile(`^[a-zA-Z0-9.-]+$`)

var _ SubjectManager = (*Manager)(nil)

type Manager struct {
Expand Down Expand Up @@ -87,6 +91,9 @@ func (r *Manager) Create(ctx context.Context, options CreationOptions) ([]did.Do
for _, option := range options.All() {
switch opt := option.(type) {
case SubjectCreationOption:
if !subjectPattern.MatchString(opt.Subject) {
return nil, "", fmt.Errorf("invalid subject (must follow pattern: %s)", subjectPattern.String())
}
subject = opt.Subject
case EncryptionKeyCreationOption:
keyFlags = keyFlags | orm.EncryptionKeyUsage()
Expand Down
22 changes: 22 additions & 0 deletions vdr/didsubject/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,28 @@ func TestManager_Create(t *testing.T) {

require.ErrorIs(t, err, ErrSubjectAlreadyExists)
})
t.Run("subject validation", func(t *testing.T) {
t.Run("empty", func(t *testing.T) {
db := testDB(t)
m := Manager{DB: db, MethodManagers: map[string]MethodManager{
"example": testMethod{},
}}

_, _, err := m.Create(audit.TestContext(), DefaultCreationOptions().With(SubjectCreationOption{Subject: ""}))

require.EqualError(t, err, "invalid subject (must follow pattern: ^[a-zA-Z0-9.-]+$)")
})
t.Run("contains illegal character (space)", func(t *testing.T) {
db := testDB(t)
m := Manager{DB: db, MethodManagers: map[string]MethodManager{
"example": testMethod{},
}}

_, _, err := m.Create(audit.TestContext(), DefaultCreationOptions().With(SubjectCreationOption{Subject: "subject with space"}))

require.EqualError(t, err, "invalid subject (must follow pattern: ^[a-zA-Z0-9.-]+$)")
})
})
}

func TestManager_List(t *testing.T) {
Expand Down

0 comments on commit d0878cf

Please sign in to comment.