Skip to content

Commit

Permalink
Add Validator interface and example (trufflesecurity#1397)
Browse files Browse the repository at this point in the history
* Add Validator interface and example

* Close sockets and improve error messages

* Remove duplicate error

* Use var declaration so err slice can be nil
  • Loading branch information
bill-rich authored Jun 15, 2023
1 parent 6d9ae7a commit 401688d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pkg/sources/sources.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ type Progress struct {
SectionsRemaining int32
}

// Validator is an interface for validating a source. Sources can optionally implement this interface to validate
// their configuration.
type Validator interface {
Validate() []error
}

// SetProgressComplete sets job progress information for a running job based on the highest level objects in the source.
// i is the current iteration in the loop of target scope
// scope should be the len(scopedItems)
Expand Down
38 changes: 38 additions & 0 deletions pkg/sources/syslog/syslog.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,44 @@ func NewSyslog(sourceType sourcespb.SourceType, jobID, sourceID int64, sourceNam
}
}

// Validate validates the configuration of the source.
func (s *Source) Validate() []error {
var errors []error

if s.conn.TlsCert != nilString || s.conn.TlsKey != nilString {
if s.conn.TlsCert == nilString || s.conn.TlsKey == nilString {
errors = append(errors, fmt.Errorf("tls cert and key must both be set"))
}
if _, err := tls.LoadX509KeyPair(s.conn.TlsCert, s.conn.TlsKey); err != nil {
errors = append(errors, fmt.Errorf("error loading tls cert and key: %s", err))
}
}

if s.conn.ListenAddress != nilString {
switch s.conn.Protocol {
case "tcp":
srv, err := net.Listen(s.conn.Protocol, s.conn.ListenAddress)
if err != nil {
errors = append(errors, fmt.Errorf("error listening on tcp socket: %s", err))
}
srv.Close()
case "udp":
srv, err := net.ListenPacket(s.conn.Protocol, s.conn.ListenAddress)
if err != nil {
errors = append(errors, fmt.Errorf("error listening on udp socket: %s", err))
}
srv.Close()
}
}
if s.conn.Protocol != "tcp" && s.conn.Protocol != "udp" {
errors = append(errors, fmt.Errorf("protocol must be 'tcp' or 'udp', got: %s", s.conn.Protocol))
}
if s.conn.Format != "rfc5424" && s.conn.Format != "rfc3164" {
errors = append(errors, fmt.Errorf("format must be 'rfc5424' or 'rfc3164', got: %s", s.conn.Format))
}
return errors
}

// Ensure the Source satisfies the interface at compile time.
var _ sources.Source = (*Source)(nil)

Expand Down

0 comments on commit 401688d

Please sign in to comment.