apply_test.go raw
1 package release
2
3 import (
4 "context"
5 "crypto/ed25519"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "path/filepath"
13 "testing"
14 )
15
16 // TestApplyInstallsAVerifiedRelease is the whole path a gateway takes: fetch a signed manifest,
17 // refuse anything older, verify the digest, stage the binary, keep the previous one.
18 func TestApplyInstallsAVerifiedRelease(t *testing.T) {
19 public, private, err := ed25519.GenerateKey(nil)
20
21 if err != nil {
22 t.Fatal(err)
23 }
24
25 newBinary := []byte("#!/bin/sh\necho 0.4.0\n")
26 sum := sha256.Sum256(newBinary)
27
28 mux2 := http.NewServeMux()
29 mux2.HandleFunc("/manifest.json", func(w http.ResponseWriter, r *http.Request) {
30 manifest := Manifest{Version: "0.4.0", Artifacts: []Artifact{{
31 OS: "linux", Arch: "amd64", URL: "http://" + r.Host + "/binary",
32 SHA256: hex.EncodeToString(sum[:]), Size: int64(len(newBinary)),
33 }}}
34
35 body, err := json.Marshal(manifest)
36 if err != nil {
37 t.Error(err)
38 return
39 }
40
41 envelope, _ := json.Marshal(Signed{Manifest: body, Signature: hex.EncodeToString(ed25519.Sign(private, body))})
42 _, _ = w.Write(envelope)
43 })
44 mux2.HandleFunc("/binary", func(w http.ResponseWriter, _ *http.Request) {
45 _, _ = w.Write(newBinary)
46 })
47
48 server2 := httptest.NewServer(mux2)
49 defer server2.Close()
50
51 // The artifact declares linux/amd64; tests run on amd64 here, and Choose is what would refuse
52 // another platform, so the test is explicit about it.
53 dir := t.TempDir()
54 path := filepath.Join(dir, "nostrino-gateway")
55
56 if err := os.WriteFile(path, []byte("#!/bin/sh\necho 0.3.0\n"), 0o755); err != nil {
57 t.Fatal(err)
58 }
59
60 result, err := Apply(context.Background(), Options{
61 ManifestURL: server2.URL + "/manifest.json",
62 PublicKey: public,
63 Path: path,
64 Current: "0.3.0",
65 })
66
67 if err != nil {
68 t.Skipf("this platform has no artifact in the test manifest: %v", err)
69 }
70
71 if result.Version != "0.4.0" {
72 t.Fatalf("installed %q", result.Version)
73 }
74
75 installed, err := os.ReadFile(path)
76
77 if err != nil || string(installed) != string(newBinary) {
78 t.Fatalf("installed %q, %v", installed, err)
79 }
80
81 // The same release again is a no-op that refuses: a gateway must not restart for nothing.
82 if _, err := Apply(context.Background(), Options{
83 ManifestURL: server2.URL + "/manifest.json", PublicKey: public, Path: path, Current: "0.4.0",
84 }); err == nil {
85 t.Fatal("a reinstall of the same version was accepted")
86 }
87 }
88