-
Notifications
You must be signed in to change notification settings - Fork 72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[POC] Validation of zip packages using javascript #285
Draft
jsoriano
wants to merge
13
commits into
elastic:main
Choose a base branch
from
jsoriano:wasm
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 7 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6479204
Validation of zip using javascript
jsoriano d3c2ddb
Install node in CI
jsoriano 4235540
Merge remote-tracking branch 'origin/main' into wasm
jsoriano 57bda00
Add server and validator from buffer
jsoriano c04077b
Fix errors format
jsoriano 2916dc6
Recover code removed by mistake
jsoriano 7325e8c
Update readme
jsoriano 2f32981
Give a try to gopherjs
jsoriano 238aaa4
More strict validation of parameters
jsoriano 7b59f5b
Remove dependency on File type
joshdover 063a94b
Merge pull request #1 from joshdover/wasm-node
jsoriano 9baabef
Merge remote-tracking branch 'origin/main' into wasm
jsoriano 0817a76
Merge remote-tracking branch 'jsoriano/wasm' into wasm
jsoriano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
*.wasm |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
include ../go/common.mk | ||
|
||
build: | ||
GOOS=js GOARCH=wasm go build -o validator.wasm . | ||
|
||
test: | ||
GOOS=js GOARCH=wasm go test -v -exec="`go env GOROOT`/misc/wasm/go_js_wasm_exec" . ../go/... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
## CLI | ||
|
||
* Build wasm with `make build`. | ||
* Run `./validate.js /path/to/package.zip` (or `node validate.js /path/to/package.zip`). | ||
|
||
Node.js and Go are required. | ||
|
||
## Web server with client validation | ||
|
||
* Build wasm with `make build`. | ||
* Run the server with `go run server.go`. | ||
* Access http://localhost:8080 and select a file. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
<!doctype html> | ||
<html> | ||
<body> | ||
<label for="package">Select a package</label><br /> | ||
<input name="package" type="file" id="package" /> | ||
<div id="result"> | ||
</div> | ||
|
||
<script src="wasm_exec.js"></script> | ||
<script src="validate.lib.js"></script> | ||
<script> | ||
const input = document.getElementById("package"); | ||
const result = document.getElementById("result"); | ||
input.addEventListener("change", function() { | ||
const reader = new FileReader(); | ||
reader.onload = function(event) { | ||
var buffer = new Uint8Array(reader.result); | ||
validateZipBuffer(input.files[0], buffer, | ||
() => { result.innerHTML = "Package is valid" }, | ||
(errors) => { result.innerHTML = errors.replaceAll("\n", "<br />") }) | ||
}; | ||
reader.readAsArrayBuffer(input.files[0]); | ||
}) | ||
</script> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
//go:build wasm | ||
|
||
package main | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"syscall/js" | ||
|
||
"github.com/elastic/package-spec/code/go/pkg/validator" | ||
) | ||
|
||
const moduleName = "elasticPackageSpec" | ||
|
||
// asyncFunc helps creating functions that return a promise. | ||
// | ||
// Calling async JavaScript APIs causes deadlocks in the JS event loop. Not sure | ||
// how to find if a Go code does it, but for example ValidateFromZip does, so | ||
// we need to run this code in a goroutine and return the result as a promise. | ||
// Related: https://github.com/golang/go/issues/41310 | ||
func asyncFunc(fn func(this js.Value, args []js.Value) interface{}) js.Func { | ||
return js.FuncOf(func(this js.Value, args []js.Value) interface{} { | ||
handler := js.FuncOf(func(_ js.Value, handlerArgs []js.Value) interface{} { | ||
resolve := handlerArgs[0] | ||
reject := handlerArgs[1] | ||
|
||
go func() { | ||
result := fn(this, args) | ||
if err, ok := result.(error); ok { | ||
reject.Invoke(err.Error()) | ||
return | ||
} | ||
resolve.Invoke(result) | ||
}() | ||
|
||
return nil | ||
}) | ||
|
||
return js.Global().Get("Promise").New(handler) | ||
}) | ||
} | ||
|
||
func main() { | ||
// It doesn't seem to be possible yet to export values as part of the compiled instance. | ||
// So we have to expose it by setting a global value. It may worth to explore tinygo for this. | ||
// Related: https://github.com/golang/go/issues/42372 | ||
js.Global().Set(moduleName, make(map[string]interface{})) | ||
module := js.Global().Get(moduleName) | ||
module.Set("validateFromZip", asyncFunc( | ||
func(this js.Value, args []js.Value) interface{} { | ||
if len(args) == 0 || args[0].IsNull() || args[0].IsUndefined() { | ||
return fmt.Errorf("package path expected") | ||
} | ||
|
||
pkgPath := args[0].String() | ||
return validator.ValidateFromZip(pkgPath) | ||
}, | ||
)) | ||
|
||
module.Set("validateFromZipReader", asyncFunc( | ||
func(this js.Value, args []js.Value) interface{} { | ||
if len(args) < 1 || args[0].IsNull() || args[0].IsUndefined() { | ||
return fmt.Errorf("file object expected") | ||
} | ||
if len(args) < 2 || args[1].IsNull() || args[1].IsUndefined() { | ||
return fmt.Errorf("array buffer with content of package expected") | ||
} | ||
|
||
file := args[0] | ||
name := file.Get("name").String() | ||
size := int64(file.Get("size").Int()) | ||
|
||
buf := make([]byte, size) | ||
js.CopyBytesToGo(buf, args[1]) | ||
|
||
reader := bytes.NewReader(buf) | ||
return validator.ValidateFromZipReader(name, reader, size) | ||
}, | ||
)) | ||
|
||
// Go runtime must be always available at any moment where exported functionality | ||
// can be executed, so keep it running till done. | ||
done := make(chan struct{}) | ||
module.Set("stop", js.FuncOf(func(_ js.Value, _ []js.Value) interface{} { | ||
close(done) | ||
return nil | ||
})) | ||
<-done | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
//go:build !wasm | ||
|
||
package main | ||
|
||
import ( | ||
"log" | ||
"net/http" | ||
) | ||
|
||
func main() { | ||
staticHandler := http.FileServer(http.Dir(".")) | ||
http.Handle("/", staticHandler) | ||
log.Fatal(http.ListenAndServe("localhost:8080", nil)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
#!/usr/bin/env node | ||
|
||
if (process.argv.length < 3) { | ||
console.error("usage: " + process.argv[1] + " [package path]"); | ||
process.exit(1); | ||
} | ||
|
||
const path = require('path') | ||
const fs = require('fs'); | ||
|
||
require(path.join(process.env.GOROOT, "misc/wasm/wasm_exec.js")); | ||
const go = new Go(); | ||
|
||
const wasmBuffer = fs.readFileSync('validator.wasm'); | ||
WebAssembly.instantiate(wasmBuffer, go.importObject).then((validator) => { | ||
go.run(validator.instance); | ||
|
||
elasticPackageSpec.validateFromZip(process.argv[2]).then(() => | ||
console.log("OK") | ||
).catch((err) => | ||
console.error(err) | ||
).finally(() => | ||
elasticPackageSpec.stop() | ||
) | ||
}).catch((err) => { | ||
console.error(err); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
var wasmBuffer; | ||
fetch('validator.wasm').then((response) => { | ||
return response.arrayBuffer(); | ||
}).then((buffer) => { | ||
wasmBuffer = buffer; | ||
}) | ||
const go = new Go(); | ||
|
||
function validateZipBuffer(file, buffer, success, error) { | ||
WebAssembly.instantiate(wasmBuffer, go.importObject).then((validator) => { | ||
go.run(validator.instance); | ||
|
||
elasticPackageSpec.validateFromZipReader(file, buffer).then(() => | ||
success() | ||
).catch((err) => | ||
error(err) | ||
).finally(() => | ||
elasticPackageSpec.stop() | ||
) | ||
}).catch((err) => { | ||
console.error(err); | ||
}); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This doesn't work.