Ejemplo n.º 1
0
func (t *Test) evaluateBody() {
	if !t.Response.BodyCheck {
		return
	}
	if t.Response.BodyString != "" {
		b := []byte(t.Response.BodyString)
		if bytes.Equal(t.Response.body, b) {
			return
		}
		t.fail(fmt.Errorf("expect response body to equal %q, given %q", t.Response.BodyString, t.Response.body))
	} else if t.Response.BodyJsonSchema != nil {
		var v interface{}
		if err := json.Unmarshal(t.Response.body, &v); err != nil {
			t.fail(fmt.Errorf("response json body error %s", err))
			return
		}
		result, err := gojsonschema.Validate(gojsonschema.NewGoLoader(t.Response.BodyJsonSchema), gojsonschema.NewGoLoader(v))
		if err != nil {
			t.fail(fmt.Errorf("validation error %s", err))
			return
		}
		if !result.Valid() {
			for _, desc := range result.Errors() {
				t.fail(fmt.Errorf("JSON schema expect %s", desc))
			}
		}
	}
}
Ejemplo n.º 2
0
// Refute refutes that the given subject will validate against a particular
// schema.
func (v *SchemaValidator) Refute(t *testing.T) {
	if result, err := gojsonschema.Validate(v.Schema, v.Subject); err != nil {
		t.Fatal(err)
	} else if result.Valid() {
		t.Fatal("api/schema: expected validation to fail, succeeded")
	}
}
Ejemplo n.º 3
0
//Validate will validate a file with a Nulecule Specification
func Validate(schemaVersion string, location *url.URL) (bool, error) {
	var rc error

	// check if schemaVersion equals nulecule.NuleculeReleasedVersions
	if schemaVersion != nulecule.NuleculeReleasedVersions {
		return false, fmt.Errorf("The specified version (%s) of the Nulecule Specification is invalid", schemaVersion)
	}

	schemaLoader := gojsonschema.NewReferenceLoader(schemaLocation[schemaVersion])
	documentLoader := gojsonschema.NewReferenceLoader(location.String())

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		return false, err
	}

	if result.Valid() {
		return true, nil
	}

	fmt.Printf("The document is not valid. see errors :\n")
	for _, desc := range result.Errors() {
		rc = multierror.Append(rc, fmt.Errorf("%s\n", desc.Description()))
		fmt.Printf("- %s\n", desc)
	}

	rc = multierror.Append(fmt.Errorf("The document is not valid with Nulecule Specification version %s", schemaVersion))

	return false, rc
}
Ejemplo n.º 4
0
func validateServiceConstraintsv2(service RawService, serviceName string) error {
	if err := setupSchemaLoaders(servicesSchemaDataV2, &schemaV2, &schemaLoaderV2, &constraintSchemaLoaderV2); err != nil {
		return err
	}

	service = convertServiceKeysToStrings(service)

	var validationErrors []string

	dataLoader := gojsonschema.NewGoLoader(service)

	result, err := gojsonschema.Validate(constraintSchemaLoaderV2, dataLoader)
	if err != nil {
		return err
	}

	if !result.Valid() {
		for _, err := range result.Errors() {
			if err.Type() == "required" {
				_, containsImage := service["image"]
				_, containsBuild := service["build"]

				if containsBuild || !containsImage && !containsBuild {
					validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has neither an image nor a build context specified. At least one must be provided.", serviceName))
				}
			}
		}
		return fmt.Errorf(strings.Join(validationErrors, "\n"))
	}

	return nil
}
Ejemplo n.º 5
0
// and define an implementation for that type that performs the schema validation
func (r *schemaValidatorType) validateSchema(schema, cfg string) []serror.SnapError {
	schemaLoader := gojsonschema.NewStringLoader(schema)
	testDoc := gojsonschema.NewStringLoader(cfg)
	result, err := gojsonschema.Validate(schemaLoader, testDoc)
	var serrors []serror.SnapError
	// Check for invalid json
	if err != nil {
		serrors = append(serrors, serror.New(err))
		return serrors
	}
	// check if result passes validation
	if result.Valid() {
		return nil
	}
	for _, err := range result.Errors() {
		serr := serror.New(errors.New("Validate schema error"))
		serr.SetFields(map[string]interface{}{
			"value":       err.Value(),
			"context":     err.Context().String("::"),
			"description": err.Description(),
		})
		serrors = append(serrors, serr)
	}
	return serrors
}
Ejemplo n.º 6
0
//middleware for json schema validation
func JsonSchemaValidator() gin.HandlerFunc {

	return func(c *gin.Context) {

		contextCopy := c.Copy()
		var schema string
		validateSchema := true

		switch c.Request.RequestURI {
		case "/signup":
			schema = "signup.json"
		case "/login":
			schema = "login.json"
		default:
			validateSchema = false
		}

		if validateSchema {

			schemaLoader := gojsonschema.NewReferenceLoader("file://" + myConstants.JsonSchemasFilesLocation + "/" +
				schema)

			body, _ := ioutil.ReadAll(contextCopy.Request.Body)
			//fmt.Printf("%s", body)

			documentLoader := gojsonschema.NewStringLoader(string(body))

			result, err := gojsonschema.Validate(schemaLoader, documentLoader)

			if err != nil {
				log.Fatalln(myMessages.JsonSchemaValidationError + err.Error())
			}

			if !result.Valid() {
				//fmt.Printf("The document is not valid. see errors :\n")
				type errorsList []string
				type JsonErrorOutput struct {
					Error   bool
					Message string
					Faults  errorsList
				}
				var el errorsList
				for _, desc := range result.Errors() {
					//fmt.Printf("- %s\n", desc)
					el = append(el, fmt.Sprintf("%s", desc))
				}
				var jeo JsonErrorOutput
				jeo.Error = true
				jeo.Message = myMessages.JsonSchemaValidationFailed
				jeo.Faults = el
				c.JSON(http.StatusBadRequest, jeo)
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
Ejemplo n.º 7
0
func TestValidRegistry(t *testing.T) {
	schemaLoader := gojsonschema.NewReferenceLoader("file://./just-install-schema.json")
	documentLoader := gojsonschema.NewReferenceLoader("file://./just-install.json")

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)

	assert.Nil(t, err)
	assert.Empty(t, result.Errors())
	assert.True(t, result.Valid())
}
Ejemplo n.º 8
0
// Assert preforms the validation assertion against the given *testing.T.
func (v *SchemaValidator) Assert(t *testing.T) {
	if result, err := gojsonschema.Validate(v.Schema, v.Subject); err != nil {
		t.Fatal(err)
	} else if !result.Valid() {
		for _, err := range result.Errors() {
			t.Logf("Validation error: %s", err.Description())
		}
		t.Fail()
	}
}
Ejemplo n.º 9
0
// ValidateJSON validates the given runtime against its defined schema
func (cfg *RuntimeOptions) ValidateJSON() error {
	schema := gojson.NewStringLoader(RuntimeSchema)
	doc := gojson.NewGoLoader(cfg)

	if result, err := gojson.Validate(schema, doc); err != nil {
		return err
	} else if !result.Valid() {
		return combineErrors(result.Errors())
	}

	return nil
}
Ejemplo n.º 10
0
func (c *InterfaceController) Update(w http.ResponseWriter, r *http.Request) {
	// Get ID
	id := mux.Vars(r)["id"]

	// Validate ObjectId
	if !bson.IsObjectIdHex(id) {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Get object id
	oid := bson.ObjectIdHex(id)

	// Initialize empty struct
	s := models.Interface{}

	// Decode JSON into struct
	err := json.NewDecoder(r.Body).Decode(&s)
	if err != nil {
		jsonError(w, r, "Failed to deconde JSON: "+err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Validate input using JSON Schema
	docLoader := gojsonschema.NewGoLoader(s)
	schemaLoader := gojsonschema.NewReferenceLoader(c.schemaURI)

	res, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		jsonError(w, r, "Failed to load schema: "+err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	if !res.Valid() {
		var errors []string
		for _, e := range res.Errors() {
			errors = append(errors, fmt.Sprintf("%s: %s", e.Context().String(), e.Description()))
		}
		jsonError(w, r, errors, http.StatusInternalServerError, c.envelope)
		return
	}

	// Update entry
	if err := c.session.DB(c.database).C("interfaces").UpdateId(oid, s); err != nil {
		jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Write content-type, header and payload
	jsonWriter(w, r, s, http.StatusOK, c.envelope)
}
Ejemplo n.º 11
0
// validateRequestData takes in a schema path and the request
// and will do the legwork of determining if the post data is valid
func validateRequestData(schemaPath string, r *web.Request) (
	document map[string]interface{},
	result *gojsonschema.Result,
	err error,
) {
	err = json.NewDecoder(r.Body).Decode(&document)
	if err == nil && schemaPath != "" {
		schemaLoader := gojsonschema.NewReferenceLoader(schemaPath)
		documentLoader := gojsonschema.NewGoLoader(document)

		result, err = gojsonschema.Validate(schemaLoader, documentLoader)
	}

	return document, result, err
}
Ejemplo n.º 12
0
// Parse takes a state json and returns the state for it
func Parse(b []byte) (*State, error) {
	schema, err := getSchema()
	if err != nil {
		return nil, err
	}
	result, err := gojsonschema.Validate(schema, gojsonschema.NewStringLoader(string(b)))
	if err != nil {
		return nil, err
	}
	if !result.Valid() {
		return nil, &SchemaError{result.Errors()}
	}
	var s State
	return &s, json.Unmarshal(b, &s)
}
Ejemplo n.º 13
0
//Validate validates json object using jsoncschema
func (schema *Schema) Validate(jsonSchema interface{}, object interface{}) error {
	schemaLoader := gojsonschema.NewGoLoader(jsonSchema)
	documentLoader := gojsonschema.NewGoLoader(object)
	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		return err
	}
	if result.Valid() {
		return nil
	}
	errDescription := "Json validation error:"
	for _, err := range result.Errors() {
		errDescription += fmt.Sprintf("\n\t%v,", err)
	}
	return fmt.Errorf(errDescription)
}
Ejemplo n.º 14
0
func validate(sl gojsonschema.JSONLoader, dl gojsonschema.JSONLoader) (error, []string) {
	result, err := gojsonschema.Validate(sl, dl)
	if err != nil {
		return err, nil
	}
	if result.Valid() {
		return nil, nil
	} else {
		ss := make([]string, 0, len(result.Errors()))
		for _, desc := range result.Errors() {
			ss = append(ss, desc.Description())
		}

		return nil, ss
	}
}
Ejemplo n.º 15
0
func validateJSON(schema string, obj Entity) error {
	schemaObj := gojson.NewStringLoader(schema)
	doc := gojson.NewGoLoader(obj)

	if result, err := gojson.Validate(schemaObj, doc); err != nil {
		return err
	} else if !result.Valid() {
		var errors []string
		for _, err := range result.Errors() {
			errors = append(errors, fmt.Sprintf("%s\n", err))
		}
		return errored.New(strings.Join(errors, "\n"))
	}

	return nil
}
Ejemplo n.º 16
0
func validateJson(schemaUrl, docUrl string) {
	schemaLoader := gojsonschema.NewReferenceLoader(schemaUrl)
	docLoader := gojsonschema.NewReferenceLoader(docUrl)
	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	utils.ExitOnFail(err)
	if result.Valid() {
		fmt.Printf("Document '%v' is valid against '%v'.\n", docUrl, schemaUrl)
	} else {
		fmt.Printf("Document '%v' is INVALID against '%v'.\n", docUrl, schemaUrl)
		for _, desc := range result.Errors() {
			fmt.Println("")
			fmt.Printf("- %s\n", desc)
		}
		// os.Exit(70)
	}
}
Ejemplo n.º 17
0
func (ts *ThreatSpec) Validate() error {
	schemaLoader := gojsonschema.NewStringLoader(ThreatSpecSchemaStrictv0)
	documentLoader := gojsonschema.NewStringLoader(ts.ToJson())

	if result, err := gojsonschema.Validate(schemaLoader, documentLoader); err != nil {
		return err
	} else if result.Valid() {
		return nil
	} else {
		var errs []string
		for _, desc := range result.Errors() {
			errs = append(errs, fmt.Sprintf("  - %s", desc))
		}
		return errors.New(strings.Join(errs, "\n"))
	}
}
Ejemplo n.º 18
0
func validateV2(serviceMap RawServiceMap) error {
	if err := setupSchemaLoaders(servicesSchemaDataV2, &schemaV2, &schemaLoaderV2, &constraintSchemaLoaderV2); err != nil {
		return err
	}

	serviceMap = convertServiceMapKeysToStrings(serviceMap)

	dataLoader := gojsonschema.NewGoLoader(serviceMap)

	result, err := gojsonschema.Validate(schemaLoaderV2, dataLoader)
	if err != nil {
		return err
	}

	return generateErrorMessages(serviceMap, schemaV2, result)
}
Ejemplo n.º 19
0
//ValidateSchema validates json schema
func (manager *Manager) ValidateSchema(schemaPath, filePath string) error {
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath)
	documentLoader := gojsonschema.NewReferenceLoader("file://" + filePath)
	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}
	if result.Valid() {
		return nil
	}
	var errMessage string
	for _, err := range result.Errors() {
		errMessage += fmt.Sprintf("%v   ", err)
	}
	return fmt.Errorf("Invalid json: %s", errMessage)
}
Ejemplo n.º 20
0
func main() {
	nargs := len(os.Args[1:])
	if nargs == 0 || nargs > 2 {
		fmt.Printf("ERROR: usage is: %s <schema.json> [<document.json>]\n", os.Args[0])
		os.Exit(1)
	}

	schemaPath, err := filepath.Abs(os.Args[1])
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath)
	var documentLoader gojsonschema.JSONLoader

	if nargs > 1 {
		documentPath, err := filepath.Abs(os.Args[2])
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		documentLoader = gojsonschema.NewReferenceLoader("file://" + documentPath)
	} else {
		documentBytes, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		documentString := string(documentBytes)
		documentLoader = gojsonschema.NewStringLoader(documentString)
	}

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document is valid\n")
	} else {
		fmt.Printf("The document is not valid. see errors :\n")
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
		os.Exit(1)
	}
}
Ejemplo n.º 21
0
func isValidJson(schema, json string) bool {
	schema = strings.TrimSpace(schema)
	if len(schema) == 2 {
		schema = `{"additionalProperties": false}`
	} else {
		schema = schema[:len(schema)-1] + `,"additionalProperties":false}`
	}

	dataLoader := gojsonschema.NewStringLoader(json)
	schemaLoader := gojsonschema.NewStringLoader(schema)

	if result, validateErr := gojsonschema.Validate(schemaLoader, dataLoader); validateErr == nil {
		return result.Valid()
	} else {
		return false
	}
}
Ejemplo n.º 22
0
func validateJSON(jsonText string, schemaText string) error {
	schemaLoader := gojsonschema.NewStringLoader(schemaText)
	docLoader := gojsonschema.NewStringLoader(jsonText)

	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		return err
	}

	if !result.Valid() {
		errMessage := "The JSON data is not valid:\n"
		for _, desc := range result.Errors() {
			errMessage += fmt.Sprintf("  %v\n", desc)
		}
		return errors.New(errMessage)
	}
	return nil
}
Ejemplo n.º 23
0
func validateFunc(e Etcdtool, dir string, d interface{}) {
	// Map directory to routes.
	var schema string
	for _, r := range e.Routes {
		match, err := regexp.MatchString(r.Regexp, dir)
		if err != nil {
			fatal(err.Error())
		}
		if match {
			schema = r.Schema
		}
	}

	if schema == "" {
		fatal("Couldn't determine which JSON schema to use for validation")
	}

	/*
	   if schema == "" && len(c.Args()) == 1 {
	       fatal("You need to specify JSON schema URI")
	   }

	   if len(c.Args()) > 1 {
	       schema = c.Args()[1]
	   }
	*/

	// Validate directory.
	infof("Using JSON schema: %s", schema)
	schemaLoader := gojsonschema.NewReferenceLoader(schema)
	docLoader := gojsonschema.NewGoLoader(d)
	result, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		fatal(err.Error())
	}

	// Print results.
	if !result.Valid() {
		for _, err := range result.Errors() {
			fmt.Printf("%s: %s\n", strings.Replace(err.Context().String("/"), "(root)", dir, 1), err.Description())
		}
		fatal("Data validation failed aborting")
	}
}
Ejemplo n.º 24
0
func (c *TenantController) Create(w http.ResponseWriter, r *http.Request) {
	// Initialize empty struct
	s := models.Tenant{}

	// Decode JSON into struct
	err := json.NewDecoder(r.Body).Decode(&s)
	if err != nil {
		jsonError(w, r, "Failed to deconde JSON: "+err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Set ID
	s.ID = bson.NewObjectId()

	// Validate input using JSON Schema
	log.Printf("Using schema: %s", c.schemaURI)
	docLoader := gojsonschema.NewGoLoader(s)
	schemaLoader := gojsonschema.NewReferenceLoader(c.schemaURI)

	res, err := gojsonschema.Validate(schemaLoader, docLoader)
	if err != nil {
		jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	if !res.Valid() {
		var errors []string
		for _, e := range res.Errors() {
			errors = append(errors, fmt.Sprintf("%s: %s", e.Context().String(), e.Description()))
		}
		jsonError(w, r, errors, http.StatusInternalServerError, c.envelope)
		return
	}

	// Insert entry
	if err := c.session.DB(c.database).C("tenants").Insert(s); err != nil {
		jsonError(w, r, err.Error(), http.StatusInternalServerError, c.envelope)
		return
	}

	// Write content-type, header and payload
	jsonWriter(w, r, s, http.StatusCreated, c.envelope)
}
Ejemplo n.º 25
0
// Read loadmodel from document - you can provide your own schema to validate the loadmodel.
func (test *TestConfig) ReadConfigValidate(document string, schema string) error {
	documentLoader := gojsonschema.NewStringLoader(document)
	schemaLoader := gojsonschema.NewStringLoader(schema)

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		return err
	}

	if !result.Valid() {
		msg := "the loadmodel is not valid:"
		for _, desc := range result.Errors() {
			msg += fmt.Sprintf("\n- %s", desc)
		}
		return fmt.Errorf(msg)
	}

	return json.Unmarshal([]byte(document), &test.config)
}
Ejemplo n.º 26
0
func checkSchema(chain *chain, value, schema interface{}) {
	if chain.failed() {
		return
	}

	valueLoader := gojsonschema.NewGoLoader(value)

	var schemaLoader gojsonschema.JSONLoader

	if str, ok := toString(schema); ok {
		if ok, _ := regexp.MatchString(`^\w+://`, str); ok {
			schemaLoader = gojsonschema.NewReferenceLoader(str)
		} else {
			schemaLoader = gojsonschema.NewStringLoader(str)
		}
	} else {
		schemaLoader = gojsonschema.NewGoLoader(schema)
	}

	result, err := gojsonschema.Validate(schemaLoader, valueLoader)
	if err != nil {
		chain.fail("\n%s\n\nschema:\n%s\n\nvalue:\n%s",
			err.Error(),
			dumpSchema(schema),
			dumpValue(value))
		return
	}

	if !result.Valid() {
		errors := ""
		for _, err := range result.Errors() {
			errors += fmt.Sprintf(" %s\n", err)
		}

		chain.fail(
			"\njson schema validation failed, schema:\n%s\n\nvalue:%s\n\nerrors:\n%s",
			dumpSchema(schema),
			dumpValue(value),
			errors)

		return
	}
}
Ejemplo n.º 27
0
// Validate uses the jsonschema to validate the configuration
func Validate(config map[string]interface{}) error {
	schemaData, err := Asset("data/config_schema_v3.0.json")
	if err != nil {
		return err
	}

	schemaLoader := gojsonschema.NewStringLoader(string(schemaData))
	dataLoader := gojsonschema.NewGoLoader(config)

	result, err := gojsonschema.Validate(schemaLoader, dataLoader)
	if err != nil {
		return err
	}

	if !result.Valid() {
		return toError(result)
	}

	return nil
}
Ejemplo n.º 28
0
func main() {

	schemaLoader := gojsonschema.NewReferenceLoader("file:///code/schema.json")
	documentLoader := gojsonschema.NewReferenceLoader("file:///code/sample.json")

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		panic(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document is valid\n")
	} else {
		fmt.Printf("The document is not valid. see errors :\n")
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
	}

}
Ejemplo n.º 29
0
/**
 * Function validates JSON schema for `device` od `channel` models
 * By convention, Schema files must be kept as:
 * - ./models/deviceSchema.json
 * - ./models/channelSchema.json
 */
func validateJsonSchema(model string, body map[string]interface{}) bool {
	pwd, _ := os.Getwd()
	schemaLoader := gojsonschema.NewReferenceLoader("file://" + pwd +
		"/schema/" + model + "Schema.json")
	bodyLoader := gojsonschema.NewGoLoader(body)
	result, err := gojsonschema.Validate(schemaLoader, bodyLoader)
	if err != nil {
		log.Print(err.Error())
	}

	if result.Valid() {
		fmt.Printf("The document is valid\n")
		return true
	} else {
		fmt.Printf("The document is not valid. See errors :\n")
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
		return false
	}
}
Ejemplo n.º 30
0
func validateServiceConstraints(service RawService, serviceName string) error {
	if err := setupSchemaLoaders(); err != nil {
		return err
	}

	service = convertServiceKeysToStrings(service)

	var validationErrors []string

	dataLoader := gojsonschema.NewGoLoader(service)

	result, err := gojsonschema.Validate(constraintSchemaLoader, dataLoader)
	if err != nil {
		return err
	}

	if !result.Valid() {
		for _, err := range result.Errors() {
			if err.Type() == "number_any_of" {
				_, containsImage := service["image"]
				_, containsBuild := service["build"]
				_, containsDockerfile := service["dockerfile"]

				if containsImage && containsBuild {
					validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has both an image and build path specified. A service can either be built to image or use an existing image, not both.", serviceName))
				} else if !containsImage && !containsBuild {
					validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has neither an image nor a build path specified. Exactly one must be provided.", serviceName))
				} else if containsImage && containsDockerfile {
					validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has both an image and alternate Dockerfile. A service can either be built to image or use an existing image, not both.", serviceName))
				}
			}
		}

		return fmt.Errorf(strings.Join(validationErrors, "\n"))
	}

	return nil
}