Merge branch 'feat/47-H2-corrections-b' into feat/47-H2-corrections
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
// exempt from that, and said so. Every build module, test step or not, must also hold a test that calls
|
||||
// conformance.LeftRunning with its own start sweep, so a step a previous process left running is ended at its start
|
||||
// (issue 1890), and one that calls conformance.Passing, so a step whose network did not answer is said as a transport fault
|
||||
// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24). Its manifest asks the capability seat-settle-delay (ADR 0664 §5).
|
||||
// (issue 1748), and one that calls conformance.StepEnds, so its steps can say a pipeline step's end (design 47 G §24), and one that calls conformance.Reproducible, so its build gives one digest per artifact in any folder (design 47 H2 H-A-591 (4)). Its manifest asks the capability seat-settle-delay (ADR 0664 §5).
|
||||
package failurekit
|
||||
|
||||
import (
|
||||
@@ -110,6 +110,16 @@ func Judge(root string) ([]Judged, error) {
|
||||
refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.StepEnds "+
|
||||
"(mesh-delivery-sdk steprun/conformance): run the kit's step-ends case with the module's own steps (design 47 G §24)", seat))
|
||||
}
|
||||
// H-A-591 (4): every build module builds one source at one version to one digest, in any folder and at any time, so every one
|
||||
// runs the kit's reproducible case over its fixture of each kind it builds.
|
||||
same, err := runsTheKit(dir, "conformance.Reproducible(")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !same {
|
||||
refused = append(refused, fmt.Sprintf("it claims %s, and no test of it calls conformance.Reproducible "+
|
||||
"(mesh-delivery-sdk steprun/conformance): run the kit's case that its build gives one digest per artifact from two folders (design 47 H2 H-A-591)", seat))
|
||||
}
|
||||
// Every build module meets the network (a fetch, a download, an install, a publish), so every one runs the passing case: its
|
||||
// steps say a network that did not answer as a transport fault the bus gives the ask again for (ADR 0664, issue 1748).
|
||||
says, err := runsTheKit(dir, "conformance.Passing(")
|
||||
|
||||
@@ -8,12 +8,12 @@ import (
|
||||
|
||||
// 1901/AC7 and 1890/AC8: a build module with a test step and no kit is refused, one that runs the kit passes, one with no
|
||||
// test step is exempt from the failure cases but not from the left-running case, a module that runs only the failure
|
||||
// cases is refused, a module that does not ask the capability seat-settle-delay is refused (ADR 0664 §5), and a module that
|
||||
// cases is refused, a module that does not ask the capability seat-settle-delay is refused (ADR 0664 §5), a module that runs the rest of the kit but not the reproducible case is refused (design 47 H2 H-A-591 (4)), and a module that
|
||||
// claims no node-build-* seat is not judged.
|
||||
func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
const imp = "package main\n\nimport \"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance\"\n\n"
|
||||
const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n"
|
||||
const sweep = "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\nfunc TestSame(t *testing.T) { conformance.Reproducible(t, nil, nil) }\n"
|
||||
kit := imp + "func TestKit(t *testing.T) { conformance.Run(t, conformance.GoTest, nil) }\n" + sweep
|
||||
for path, body := range map[string]string{
|
||||
"modules/a/module.json": `{"claims":[{"name":"node-build-a"}],"tools":["build_a_fetch","build_a_test"]}`,
|
||||
@@ -33,7 +33,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
||||
"modules/j/module.json": `{"claims":[{"name":"node-build-j"}],"capabilities":["seat-settle-delay"],"tools":["build_j_build"]}`, // the rest of the kit, and no step-ends case
|
||||
"modules/j/cmd/j/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n",
|
||||
"modules/k/module.json": `{"claims":[{"name":"node-build-k"}],"capabilities":["seat-settle-delay"],"tools":["build_k_build"]}`, // no runs-counted case
|
||||
"modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\n",
|
||||
"modules/k/cmd/k/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestSame(t *testing.T) { conformance.Reproducible(t, nil, nil) }\n",
|
||||
"modules/l/module.json": `{"claims":[{"name":"node-build-l"}],"capabilities":["seat-settle-delay"],"tools":["build_l_build"]}`, // the rest of the kit, and no reproducible case
|
||||
"modules/l/cmd/l/kit_test.go": imp + "func TestSweep(t *testing.T) { conformance.LeftRunning(t, nil) }\nfunc TestPassing(t *testing.T) { conformance.Passing(t, nil, nil) }\nfunc TestEnds(t *testing.T) { conformance.StepEnds(t, steprun.AskSteps{}) }\nfunc TestCounted(t *testing.T) { conformance.RunsCounted(t, nil) }\n",
|
||||
"modules/e/module.json": `{"claims":[{"name":"node-build-e"}],"tools":["build_e_test"]}`,
|
||||
"modules/e/cmd/e/kit.go": kit, // not a test file
|
||||
} {
|
||||
@@ -49,9 +51,9 @@ func TestABuildModuleWithATestStepMustRunTheKit(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused"}
|
||||
want := map[string]string{"a": "refused", "b": "passes", "c": "exempt", "e": "refused", "f": "refused", "g": "refused", "h": "refused", "i": "refused", "j": "refused", "k": "refused", "l": "refused"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j and k", got)
|
||||
t.Fatalf("judged %+v, want a, b, c, e, f, g, h, i, j, k and l", got)
|
||||
}
|
||||
for _, j := range got {
|
||||
is := "passes"
|
||||
|
||||
@@ -25,6 +25,10 @@ func publishOf(in reg.PublishInput) holder.PublishRequest {
|
||||
}
|
||||
|
||||
func publishAnswer(a holder.PublishAnswer) reg.PublishAnswer {
|
||||
if a.OtherBytes != nil {
|
||||
// No transfer is opened, so none is named (design 47 H2 H-A-732).
|
||||
return reg.PublishAnswer{OtherBytes: ®.PublishAnswerOtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}}
|
||||
}
|
||||
return reg.PublishAnswer{Transfer: a.Transfer, Lacks: a.Missing, Held: a.Ended && len(a.Missing) == 0}
|
||||
}
|
||||
|
||||
@@ -49,7 +53,11 @@ func versionsAnswer(v *holder.Verbs, kind string, a holder.VersionsAnswer) reg.V
|
||||
// The contract's answer has no field for why; the version is answered with no digest and the reason said here.
|
||||
logf("versions: %s %s on %s answers no digest: %v", a.Name, ver, a.Seat, err)
|
||||
}
|
||||
out.Versions = append(out.Versions, reg.Artifact{Name: a.Name, Version: ver, Digest: d, Kind: kind})
|
||||
fp, err := v.VersionFingerprint(a.Name, ver, d)
|
||||
if err != nil {
|
||||
logf("versions: the fingerprint kept for %s %s on %s cannot be read: %v", a.Name, ver, a.Seat, err)
|
||||
}
|
||||
out.Versions = append(out.Versions, reg.Artifact{Name: a.Name, Version: ver, Digest: d, Kind: kind, Fingerprint: fp})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -62,18 +62,37 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
|
||||
t.Errorf("%s's body %s is not the contract's: %v", event, b, err)
|
||||
}
|
||||
}
|
||||
// an other-bytes answer carries its digest and fingerprint and names no transfer (H-A-729, H-A-732)
|
||||
if a := publishAnswer(holder.PublishAnswer{OtherBytes: &holder.OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}}); a.Transfer != "" || a.OtherBytes == nil || a.OtherBytes.Digest != "sha256:bb" || a.OtherBytes.Fingerprint != "f1" {
|
||||
t.Errorf("publish answers %+v for other bytes", a)
|
||||
} else if b, _ := json.Marshal(a); strings.Contains(string(b), `"transfer"`) {
|
||||
t.Errorf("the other-bytes answer %s names a transfer", b)
|
||||
}
|
||||
if a := publishAnswer(holder.PublishAnswer{Transfer: "t", Missing: []string{"sha256:bb"}}); !reflect.DeepEqual(a.Lacks, []string{"sha256:bb"}) || a.Held {
|
||||
t.Errorf("publish answers %+v", a)
|
||||
}
|
||||
// versions answers the digest a reference names (design 47 G A-430a): the blob on the artifact seat, the manifest on the image seat.
|
||||
cat := twoDigests{}
|
||||
for _, c := range []struct{ seat, want string }{{holder.ArtifactSeat, "sha256:blob"}, {holder.ImageSeat, "sha256:manifest"}} {
|
||||
got := versionsAnswer(&holder.Verbs{Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}})
|
||||
if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" {
|
||||
t.Errorf("versions on %s answers %+v, want digest %s", c.seat, got.Versions, c.want)
|
||||
// and the fingerprint kept for it beside, none where the key names another digest or there is none (H-A-589 (3))
|
||||
kept := memKept{holder.FingerprintKey("m/files", "0.1.7"): {Digest: c.want, Fingerprint: "f1"}}
|
||||
got := versionsAnswer(&holder.Verbs{Holder: &holder.Holder{Fingerprints: kept}, Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}})
|
||||
if len(got.Versions) != 1 || got.Versions[0].Digest != c.want || got.Versions[0].Version != "0.1.7" || got.Versions[0].Fingerprint != "f1" {
|
||||
t.Errorf("versions on %s answers %+v, want digest %s, fingerprint f1", c.seat, got.Versions, c.want)
|
||||
}
|
||||
kept[holder.FingerprintKey("m/files", "0.1.7")] = holder.Kept{Digest: "sha256:other", Fingerprint: "f1"}
|
||||
if got := versionsAnswer(&holder.Verbs{Holder: &holder.Holder{Fingerprints: kept}, Catalog: cat}, "", holder.VersionsAnswer{Seat: c.seat, Name: "m/files", Versions: []string{"0.1.7"}}); got.Versions[0].Fingerprint != "" {
|
||||
t.Errorf("versions on %s answers fingerprint %q of a key naming another digest", c.seat, got.Versions[0].Fingerprint)
|
||||
}
|
||||
}
|
||||
if r, err := partOf(reg.PublishPartInput{Transfer: "t", Part: "sha256:bb", Data: "aGk=", Last: true}); err != nil || string(r.Data) != "hi" || r.Digest != "sha256:bb" {
|
||||
t.Errorf("publish-part read %+v, %v", r, err)
|
||||
}
|
||||
}
|
||||
|
||||
// memKept is the state fingerprints in memory.
|
||||
type memKept map[string]holder.Kept
|
||||
|
||||
func (m memKept) Get(k string) (holder.Kept, bool, error) { v, ok := m[k]; return v, ok, nil }
|
||||
func (m memKept) Put(k string, v holder.Kept) error { m[k] = v; return nil }
|
||||
func (m memKept) Delete(k string) error { delete(m, k); return nil }
|
||||
|
||||
@@ -74,6 +74,25 @@ func (k kept[T]) List() ([]T, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// fingerprints is the state fingerprints through the runtime: a write at its cap fails (design 47 H2 H-A-589 (2)).
|
||||
type fingerprints struct{}
|
||||
|
||||
func (fingerprints) Get(key string) (holder.Kept, bool, error) {
|
||||
var k holder.Kept
|
||||
e, err := stdio.State(holder.FingerprintsState).Get(key)
|
||||
if err != nil || e == nil {
|
||||
return k, false, err
|
||||
}
|
||||
return k, true, json.Unmarshal(e.Value, &k)
|
||||
}
|
||||
func (fingerprints) Put(key string, k holder.Kept) error {
|
||||
_, err := stdio.State(holder.FingerprintsState).Put(key, k)
|
||||
return err
|
||||
}
|
||||
func (fingerprints) Delete(key string) error {
|
||||
return stdio.State(holder.FingerprintsState).Delete(key)
|
||||
}
|
||||
|
||||
func say(seat, event string, body holder.Event) error {
|
||||
return stdio.SeatPublish("mesh.seat."+seat+".event."+event, eventBody(event, body), body.ID)
|
||||
}
|
||||
@@ -497,7 +516,7 @@ func main() {
|
||||
base, _ := url.Parse("http://127.0.0.1:5001")
|
||||
store := &holder.OCI{Base: base, Upstream: &holder.Upstream{}}
|
||||
h := &holder.Holder{Logf: logf, Objects: boundedObjects{parts.BusObjects(holder.IncomingObjects), busstate.ObjectsOf(holder.IncomingObjects).Purge}, Builder: holder.Reserved{Ask: stdio.Ask}, Store: store, Say: say, Finding: boundedFinding(findings.Say),
|
||||
Transfers: boundedTransfers{parts.BusTransfers[holder.Opening](holder.TransfersState)}, Cap: boundedCap(parts.BusCap(holder.IncomingObjects)), Record: recordAct, Idle: boundedArm(parts.BusArm(holder.IdleState))}
|
||||
Transfers: boundedTransfers{parts.BusTransfers[holder.Opening](holder.TransfersState)}, Fingerprints: fingerprints{}, Cap: boundedCap(parts.BusCap(holder.IncomingObjects)), Record: recordAct, Idle: boundedArm(parts.BusArm(holder.IdleState))}
|
||||
files := &holder.Files{Container: or(os.Getenv("MESH_REGISTRY_CONTAINER"), "mesh-registry"), Run: holder.ExecRunner, UID: os.Getuid()}
|
||||
v := &holder.Verbs{Holder: h, Catalog: store, Holds: kept[holder.Hold]{state: "holds", key: holder.Hold.Key}, Mirrors: mirrors{},
|
||||
Files: files}
|
||||
|
||||
@@ -215,9 +215,25 @@ func (m memHolds) List() ([]Hold, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// memFingerprints is the state fingerprints in memory; full makes a write fail as the state does at its cap.
|
||||
type memFingerprints struct {
|
||||
m map[string]Kept
|
||||
full bool
|
||||
}
|
||||
|
||||
func (f *memFingerprints) Get(k string) (Kept, bool, error) { v, ok := f.m[k]; return v, ok, nil }
|
||||
func (f *memFingerprints) Put(k string, v Kept) error {
|
||||
if f.full {
|
||||
return errors.New("the bucket is at its cap")
|
||||
}
|
||||
f.m[k] = v
|
||||
return nil
|
||||
}
|
||||
func (f *memFingerprints) Delete(k string) error { delete(f.m, k); return nil }
|
||||
|
||||
func newBed(builderOK bool) *bed {
|
||||
b := &bed{store: &fakeStore{has: map[string]bool{}}, findings: map[string]bool{}, now: time.Unix(1000, 0), cat: &fakeCatalog{tags: map[string]string{}}}
|
||||
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Builder: fakeBuilder{ok: builderOK},
|
||||
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Fingerprints: &memFingerprints{m: map[string]Kept{}}, Builder: fakeBuilder{ok: builderOK},
|
||||
Store: b.store, Now: func() time.Time { return b.now },
|
||||
Say: func(seat, event string, body Event) error {
|
||||
b.said = append(b.said, said{seat, event, body})
|
||||
@@ -353,16 +369,15 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
_, err := b.h.Publish(ArtifactSeat, builder, req("t"))
|
||||
return err
|
||||
}, "the builder did not reserve it"},
|
||||
{"a version the store holds at another digest", func(b *bed) error {
|
||||
b.store.held = map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}}
|
||||
r := req("t")
|
||||
r.Digest = "sha256:aa"
|
||||
_, err := b.h.Publish(ArtifactSeat, builder, r) // the reservation names no digest yet: the bed's builder says yes
|
||||
if !b.findings["publish-refused m/program@0.1.4"] || len(b.store.put) != 0 {
|
||||
return errors.New("not refused loudly, or stored")
|
||||
{"a version stored while the state fingerprints is at its cap", func(b *bed) error {
|
||||
b.h.Fingerprints.(*memFingerprints).full = true
|
||||
_, _ = b.h.Publish(ArtifactSeat, builder, req("t"))
|
||||
_, err := b.h.PublishPart(ArtifactSeat, builder, PartRequest{Transfer: "t", Digest: part.Digest, Last: true, Data: blob})
|
||||
if len(b.store.put) != 0 || len(b.said) != 1 || b.said[0].event != EventRefused {
|
||||
return errors.New("stored, or not refused: " + fmt.Sprint(b.said))
|
||||
}
|
||||
return err
|
||||
}, "the store holds m/program@0.1.4 at digest sha256:bb, not sha256:aa"},
|
||||
}, "fingerprints did not take the key"},
|
||||
{"an image on the artifact seat", func(b *bed) error {
|
||||
r := req("t")
|
||||
r.Kind = KindImage
|
||||
@@ -424,8 +439,9 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
}
|
||||
other := req("other")
|
||||
other.Digest = digestOf([]byte("other bytes"))
|
||||
if _, err := b.h.Publish(ArtifactSeat, builder, other); err == nil || !strings.Contains(err.Error(), "at digest "+part.Digest+", not "+other.Digest) {
|
||||
t.Errorf("other bytes at the held version = %v; want refused naming the held layer %s", err, part.Digest)
|
||||
// H-A-729, H-A-732: other bytes at the held version are answered, not failed, naming the held layer, and open no transfer.
|
||||
if a, err := b.h.Publish(ArtifactSeat, builder, other); err != nil || a.OtherBytes == nil || a.OtherBytes.Digest != part.Digest || a.Transfer != "" || len(b.said) != 1 {
|
||||
t.Errorf("other bytes at the held version = %+v, %v; want other-bytes naming the held layer %s, no transfer", a, err, part.Digest)
|
||||
}
|
||||
if len(reg.blobs) != uploads {
|
||||
t.Errorf("the store took %d blobs more; want none", len(reg.blobs)-uploads)
|
||||
@@ -437,6 +453,73 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
t.Errorf("an image held at its manifest = %q, %q, %v; want held", ref, other, err)
|
||||
}
|
||||
})
|
||||
// H-A-589, H-A-729, H-A-732, H-A-738 (1): a held version offered again is answered by the fingerprint the holder keeps for it.
|
||||
t.Run("a held version is answered by its kept fingerprint", func(t *testing.T) {
|
||||
held := map[string]heldAt{"m/program@0.1.4": {manifest: "sha256:cc", layer: "sha256:bb"}}
|
||||
offer := func(b *bed, fp string) PublishRequest {
|
||||
r := req("t")
|
||||
r.Digest, r.Fingerprint = "sha256:aa", fp
|
||||
b.store.held = held
|
||||
return r
|
||||
}
|
||||
keep := func(b *bed, fp string) {
|
||||
_ = b.h.Fingerprints.Put(FingerprintKey("m/program", "0.1.4"), Kept{Digest: "sha256:bb", Fingerprint: fp})
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
kept, offer string // the fingerprint kept (none when empty or noKey), the one offered
|
||||
noKey bool
|
||||
want *OtherBytes
|
||||
}{
|
||||
{name: "the offered fingerprint is the kept one: other-bytes carrying it", kept: "f1", offer: "f1", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}},
|
||||
{name: "another fingerprint is other-bytes with the kept one", kept: "f1", offer: "f2", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}},
|
||||
{name: "no fingerprint kept is other-bytes with none", noKey: true, offer: "f1", want: &OtherBytes{Digest: "sha256:bb"}},
|
||||
{name: "no fingerprint offered is other-bytes", kept: "f1", want: &OtherBytes{Digest: "sha256:bb", Fingerprint: "f1"}},
|
||||
} {
|
||||
b := newBed(true)
|
||||
r := offer(b, c.offer)
|
||||
if !c.noKey {
|
||||
keep(b, c.kept)
|
||||
}
|
||||
a, err := b.h.Publish(ArtifactSeat, builder, r)
|
||||
if err != nil || !reflect.DeepEqual(a.OtherBytes, c.want) || a.Transfer != "" || a.Ended || len(b.store.put) != 0 || len(a.Missing) != 0 || len(b.h.Transfers.(memTransfers)) != 0 || len(b.said) != 0 {
|
||||
t.Errorf("%s: answered %+v, %v; stored %d, transfers %d, said %+v", c.name, a, err, len(b.store.put), len(b.h.Transfers.(memTransfers)), b.said)
|
||||
}
|
||||
// the ask given again reads the same state afresh and answers the same
|
||||
if a2, err := b.h.Repeat(ArtifactSeat, builder, r); err != nil || !reflect.DeepEqual(a2.OtherBytes, c.want) {
|
||||
t.Errorf("%s: repeated ask answered %+v, %v", c.name, a2, err)
|
||||
}
|
||||
}
|
||||
// the key is written when the version is stored, read by versions, and deleted at removed
|
||||
b := newBed(true)
|
||||
r := req("k")
|
||||
r.Fingerprint = "f9"
|
||||
if _, err := b.h.Publish(ArtifactSeat, builder, r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.h.PublishPart(ArtifactSeat, builder, PartRequest{Transfer: "k", Digest: part.Digest, Last: true, Data: blob}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if k, ok, _ := b.h.Fingerprints.Get(FingerprintKey("m/program", "0.1.4")); !ok || k != (Kept{Digest: part.Digest, Fingerprint: "f9"}) {
|
||||
t.Errorf("the key after the store = %+v, %v", k, ok)
|
||||
}
|
||||
if fp, err := b.v.VersionFingerprint("m/program", "0.1.4", part.Digest); err != nil || fp != "f9" {
|
||||
t.Errorf("versions answers fingerprint %q, %v", fp, err)
|
||||
}
|
||||
if fp, _ := b.v.VersionFingerprint("m/program", "0.1.4", "sha256:other"); fp != "" {
|
||||
t.Errorf("a key naming another digest than the held one answered %q", fp)
|
||||
}
|
||||
b.cat.tags = map[string]string{"m/program:0.1.4-b": part.Digest}
|
||||
r2 := req("k")
|
||||
r2.Version = "0.1.4-b"
|
||||
_ = b.h.Fingerprints.Put(FingerprintKey("m/program", "0.1.4-b"), Kept{Digest: part.Digest, Fingerprint: "f9"})
|
||||
if _, err := b.v.Remove(ArtifactSeat, "novox.mesh-delivery-builder", RemoveRequest{Name: "m/program", Version: "0.1.4-b", Reason: "branch ended"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok, _ := b.h.Fingerprints.Get(FingerprintKey("m/program", "0.1.4-b")); ok {
|
||||
t.Errorf("the key stayed after removed")
|
||||
}
|
||||
})
|
||||
t.Run("only the missing layers are sent, and an idle transfer is dropped", func(t *testing.T) {
|
||||
b := newBed(true)
|
||||
other := []byte("layer two")
|
||||
@@ -750,13 +833,24 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
b := newBed(true)
|
||||
return publishconformance.Bed{
|
||||
Hold: func(d string) { b.store.has[d] = true },
|
||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
||||
got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Transfer: "t"})
|
||||
o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason
|
||||
// the holder holds the version at digest d, keeping fingerprint fp for it
|
||||
HoldWith: func(d, fp string) {
|
||||
b.store.held = map[string]heldAt{publishconformance.Name + "@" + publishconformance.Version: {manifest: d, layer: d}}
|
||||
b.store.has[d] = true
|
||||
if fp != "" {
|
||||
_ = b.h.Fingerprints.Put(FingerprintKey(publishconformance.Name, publishconformance.Version), Kept{Digest: d, Fingerprint: fp})
|
||||
}
|
||||
return o
|
||||
},
|
||||
Held: func(name, version string) (string, string) {
|
||||
at := b.store.held[name+"@"+version]
|
||||
fp, _ := b.v.VersionFingerprint(name, version, at.layer)
|
||||
return at.layer, fp
|
||||
},
|
||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
||||
return publish(b, name, version, digest, "")
|
||||
},
|
||||
PublishWith: func(name, version, digest, fingerprint string) publishconformance.Outcome {
|
||||
return publish(b, name, version, digest, fingerprint)
|
||||
}}
|
||||
})
|
||||
})
|
||||
@@ -1003,9 +1097,14 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
if m.Class != "core" {
|
||||
t.Errorf("class %q, want core", m.Class)
|
||||
}
|
||||
// The state fingerprints names its own cap, 16 MiB (H-A-589 (2)).
|
||||
for _, st := range m.State {
|
||||
if st.MaxMiB != 8 {
|
||||
t.Errorf("the state %s names max-mib %d, want 8", st.Name, st.MaxMiB)
|
||||
want := 8
|
||||
if st.Name == FingerprintsState {
|
||||
want = 16
|
||||
}
|
||||
if st.MaxMiB != want {
|
||||
t.Errorf("the state %s names max-mib %d, want %d", st.Name, st.MaxMiB, want)
|
||||
}
|
||||
}
|
||||
// The reservation is asked through the seat mesh-builds, so the manifest takes no package of the builder (design 47 §381).
|
||||
@@ -1116,3 +1215,17 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
|
||||
// registryForms reads a reference of the registry form, with the two seats' names this holder answers for.
|
||||
var registryForms = artifactref.Seats{Image: ImageSeat, Object: ArtifactSeat}
|
||||
|
||||
// publish is a no-parts publish of a bundle through the holder as the publish conformance kit makes it, with the outcome the
|
||||
// kit reads.
|
||||
func publish(b *bed, name, version, digest, fingerprint string) publishconformance.Outcome {
|
||||
got, err := b.h.Publish(ArtifactSeat, builder, PublishRequest{Name: name, Version: version, Kind: KindBundle, Digest: digest, Fingerprint: fingerprint, Transfer: "t"})
|
||||
o := publishconformance.Outcome{Ended: got.Ended, Lacks: len(got.Missing), Err: err}
|
||||
if got.OtherBytes != nil {
|
||||
o.Other = &publishconformance.OtherBytes{Digest: got.OtherBytes.Digest, Fingerprint: got.OtherBytes.Fingerprint}
|
||||
}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].body.Reason
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
|
||||
keyparts "git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
// The bounds of incoming (design 51 *Publishing*, ADR 0611): a part is at most 1 MiB, a transfer with no part for 24
|
||||
@@ -25,6 +26,9 @@ const (
|
||||
// IncomingObjects and TransfersState are the object store and the state distribution asks as bus state.
|
||||
IncomingObjects = "incoming"
|
||||
TransfersState = "transfers"
|
||||
// FingerprintsState is the state fingerprints: the digest and fingerprint each version this holder stored was published
|
||||
// with (design 47 H2 H-A-589 (2)).
|
||||
FingerprintsState = "fingerprints"
|
||||
// IdleState is the state of one key per open transfer with its own time to live (a state declared key-ttl): the
|
||||
// bus's marker of its end is the event that drops a transfer left with no part for TransferIdle (ADR 0611 §3), never
|
||||
// a timer.
|
||||
@@ -68,6 +72,36 @@ type PublishAnswer struct {
|
||||
Missing []string `json:"missing"`
|
||||
// Ended says the publish ended at once: everything was held, `published` or `refused` is said.
|
||||
Ended bool `json:"ended,omitempty"`
|
||||
// OtherBytes is set when the holder holds the publish's name and version with another digest and keeps another
|
||||
// fingerprint for it, or none: the call does not fail, and no transfer is opened (design 47 H2 H-A-729, H-A-732).
|
||||
OtherBytes *OtherBytes `json:"other_bytes,omitempty"`
|
||||
}
|
||||
|
||||
// OtherBytes is the digest a holder holds for a name and version, and the fingerprint it keeps for them, empty where it
|
||||
// keeps none.
|
||||
type OtherBytes struct {
|
||||
Digest string `json:"digest"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
// Kept is one key of the state fingerprints: the digest and the fingerprint the publish of a version named.
|
||||
type Kept struct {
|
||||
Digest string `json:"digest"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
// FingerprintKey is the key of name at version in the state fingerprints: `<name>.<version>`, each token escaped as a key's
|
||||
// name is (design 47 H2 H-A-589 (2)).
|
||||
func FingerprintKey(name, version string) string {
|
||||
return keyparts.EscapeName(name) + "." + keyparts.EscapeName(version)
|
||||
}
|
||||
|
||||
// FingerprintState is distribution's own state fingerprints (bus state, template state; ADR 0595), reached by the holder
|
||||
// alone; a write at its cap fails.
|
||||
type FingerprintState interface {
|
||||
Get(key string) (Kept, bool, error)
|
||||
Put(key string, k Kept) error
|
||||
Delete(key string) error
|
||||
}
|
||||
|
||||
// PartRequest is the body of `publish-part` (ADR 0611 §2): one chunk of one part.
|
||||
@@ -165,11 +199,13 @@ type Finding func(kind, subject, words string, raised bool)
|
||||
type Holder struct {
|
||||
Objects Objects
|
||||
Transfers TransferState
|
||||
Builder Builder
|
||||
Store Store
|
||||
Say Say
|
||||
Finding Finding
|
||||
Now func() time.Time
|
||||
// Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)).
|
||||
Fingerprints FingerprintState
|
||||
Builder Builder
|
||||
Store Store
|
||||
Say Say
|
||||
Finding Finding
|
||||
Now func() time.Time
|
||||
// Cap reads incoming's cap from its binding (parts.BusCap); IncomingCap when nil or when the binding names none.
|
||||
Cap func() (uint64, error)
|
||||
// Record records a hand act through the seat mesh-hand-acts (meshhandactsclient.Recorder); a drop by hand is refused
|
||||
@@ -229,10 +265,15 @@ func (h *Holder) receiver() *parts.Receiver[Opening] {
|
||||
return nil
|
||||
},
|
||||
Store: func(t Transfer, held map[string][]byte) error {
|
||||
if err := h.keep(t.Shape.PublishRequest); err != nil {
|
||||
reason := err.Error()
|
||||
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
|
||||
}
|
||||
path, err := h.Store.Put(t.Shape.PublishRequest, held)
|
||||
ref := SeatReference(t.Shape.Seat, path)
|
||||
if err != nil {
|
||||
reason := "the store did not take it: " + err.Error()
|
||||
h.unkeep(t.Shape.PublishRequest)
|
||||
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
|
||||
}
|
||||
h.Finding("publish-refused", t.Shape.Name+"@"+t.Shape.Version, "", false)
|
||||
@@ -276,10 +317,9 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer,
|
||||
if err != nil {
|
||||
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
|
||||
} else if other != "" {
|
||||
// A second publish of a held version with another digest is refused before the reservation is asked, as the forge
|
||||
// holds the first (A-490j, H-A-393): while the reserved digest is still empty it would pass, and the store's Put
|
||||
// would move the version's tag.
|
||||
return h.refusePublish(seat, r, fmt.Sprintf("the store holds %s@%s at digest %s, not %s", r.Name, r.Version, other, r.Digest))
|
||||
// The version is held at another digest: answered with the held digest and the fingerprint kept for it, nothing
|
||||
// stored, no transfer opened (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)).
|
||||
return h.heldElsewhere(r, other)
|
||||
} else if ref != "" {
|
||||
return PublishAnswer{Transfer: r.Transfer, Ended: true}, h.timed("the published event on the seat", func() error {
|
||||
return h.Say(seat, EventPublished, h.eventOf(seat, r, SeatReference(seat, ref), ""))
|
||||
@@ -304,6 +344,60 @@ func (h *Holder) Publish(seat, caller string, r PublishRequest) (PublishAnswer,
|
||||
return answerOf(got), nil
|
||||
}
|
||||
|
||||
// keptFor is the fingerprint the holder keeps for name at version, empty when it keeps none; a key naming another digest
|
||||
// than the one the store holds speaks for nothing.
|
||||
func (h *Holder) keptFor(r PublishRequest, held string) (string, error) {
|
||||
k, found, err := h.Fingerprints.Get(FingerprintKey(r.Name, r.Version))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("publish: the fingerprint kept for %s@%s cannot be read: %w", r.Name, r.Version, err)
|
||||
}
|
||||
if !found || k.Digest != held {
|
||||
return "", nil
|
||||
}
|
||||
return k.Fingerprint, nil
|
||||
}
|
||||
|
||||
// heldElsewhere answers a publish of a version the store holds at the digest other, not the publish's: other-bytes, the held
|
||||
// digest and the fingerprint kept for it, the call not failing, nothing stored and no transfer opened. The reader compares the
|
||||
// kept fingerprint with the publish's own (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). The journal says both digests and both
|
||||
// fingerprints.
|
||||
func (h *Holder) heldElsewhere(r PublishRequest, other string) (PublishAnswer, error) {
|
||||
kept, err := h.keptFor(r, other)
|
||||
if err != nil {
|
||||
return PublishAnswer{}, err
|
||||
}
|
||||
h.logf("publish: %s@%s is held at digest %s with fingerprint %q; the offer is digest %s with fingerprint %q: answered other-bytes, nothing stored", r.Name, r.Version, other, kept, r.Digest, r.Fingerprint)
|
||||
return PublishAnswer{OtherBytes: &OtherBytes{Digest: other, Fingerprint: kept}}, nil
|
||||
}
|
||||
|
||||
// keep writes the key of a version about to be stored; a write the state refuses (at its cap) is the publish's refusal, so
|
||||
// nothing is stored. A publish with no version keeps none.
|
||||
func (h *Holder) keep(r PublishRequest) error {
|
||||
if r.Version == "" {
|
||||
return nil
|
||||
}
|
||||
if err := h.Fingerprints.Put(FingerprintKey(r.Name, r.Version), Kept{Digest: r.Digest, Fingerprint: r.Fingerprint}); err != nil {
|
||||
return fmt.Errorf("the state %s did not take the key of %s@%s (it refuses at its cap), so nothing is stored: %w", FingerprintsState, r.Name, r.Version, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// unkeep deletes the key keep wrote when the store did not take the version.
|
||||
func (h *Holder) unkeep(r PublishRequest) {
|
||||
if r.Version == "" {
|
||||
return
|
||||
}
|
||||
if err := h.Fingerprints.Delete(FingerprintKey(r.Name, r.Version)); err != nil {
|
||||
h.logf("publish: the key of %s@%s stays in the state %s: %v", r.Name, r.Version, FingerprintsState, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Holder) logf(format string, a ...any) {
|
||||
if h.Logf != nil {
|
||||
h.Logf(format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
// refusePublish ends a publish refused before anything is stored: its finding raised, refused said on the seat, the reason
|
||||
// answered.
|
||||
func (h *Holder) refusePublish(seat string, r PublishRequest, reason string) (PublishAnswer, error) {
|
||||
@@ -338,6 +432,9 @@ func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) {
|
||||
if !ok {
|
||||
return refuse("the builder did not reserve it: " + why)
|
||||
}
|
||||
if err := h.keep(r); err != nil {
|
||||
return refuse(err.Error())
|
||||
}
|
||||
tag := r
|
||||
tag.Parts = []Part{{Digest: r.Digest}}
|
||||
var path string
|
||||
@@ -345,6 +442,7 @@ func (h *Holder) tagHeld(seat string, r PublishRequest) (PublishAnswer, error) {
|
||||
path, err = h.Store.Put(tag, map[string][]byte{})
|
||||
return err
|
||||
}); err != nil {
|
||||
h.unkeep(r)
|
||||
return refuse("the store did not tag it: " + err.Error())
|
||||
}
|
||||
h.Finding("publish-refused", r.Name+"@"+r.Version, "", false)
|
||||
@@ -416,15 +514,18 @@ func (h *Holder) Repeat(seat, caller string, r PublishRequest) (PublishAnswer, e
|
||||
return PublishAnswer{}, err
|
||||
}
|
||||
if r.Version != "" {
|
||||
var ref string
|
||||
var ref, other string
|
||||
err := h.timed("the store's read of what it holds (the program's registry)", func() (err error) {
|
||||
ref, _, err = h.Store.Held(r)
|
||||
ref, other, err = h.Store.Held(r)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return PublishAnswer{}, fmt.Errorf("publish: the store cannot say whether it holds %s@%s: %w", r.Name, r.Version, err)
|
||||
} else if ref != "" {
|
||||
return PublishAnswer{Transfer: r.Transfer, Ended: true}, nil
|
||||
} else if other != "" {
|
||||
// The act's state as it stands: held at another digest, answered as the act answered it, saying nothing again.
|
||||
return h.heldElsewhere(r, other)
|
||||
}
|
||||
}
|
||||
t, found, err := h.Transfers.Get(r.Transfer)
|
||||
|
||||
@@ -201,6 +201,9 @@ func (v *Verbs) Remove(seat, caller string, r RemoveRequest) (Removal, error) {
|
||||
}
|
||||
}
|
||||
ev.Digest = d // a version already gone is said removed all the same, so the builder's retry ends
|
||||
if err := v.Fingerprints.Delete(FingerprintKey(r.Name, r.Version)); err != nil {
|
||||
return Removal{}, fmt.Errorf("remove: %s@%s is removed, but its key in the state %s is not deleted: %w", r.Name, r.Version, FingerprintsState, err)
|
||||
}
|
||||
}
|
||||
return Removal{Removed: true}, v.Say(seat, EventRemoved, ev)
|
||||
}
|
||||
@@ -450,3 +453,13 @@ func (v *Verbs) HeldNow() ([]Hold, error) {
|
||||
slices.SortFunc(all, func(a, b Hold) int { return strings.Compare(a.Key(), b.Key()) })
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// VersionFingerprint is the fingerprint kept for name at version when the key names the digest the store holds there, empty
|
||||
// where none is kept (`versions`, design 47 H2 H-A-589 (3)).
|
||||
func (v *Verbs) VersionFingerprint(name, version, digest string) (string, error) {
|
||||
k, found, err := v.Fingerprints.Get(FingerprintKey(name, version))
|
||||
if err != nil || !found || k.Digest != digest {
|
||||
return "", err
|
||||
}
|
||||
return k.Fingerprint, nil
|
||||
}
|
||||
|
||||
@@ -255,6 +255,10 @@
|
||||
"name": "transfers",
|
||||
"max-mib": 8
|
||||
},
|
||||
{
|
||||
"name": "fingerprints",
|
||||
"max-mib": 16
|
||||
},
|
||||
{
|
||||
"name": "idle",
|
||||
"key-ttl": true,
|
||||
|
||||
@@ -72,8 +72,9 @@ Approve names.
|
||||
|
||||
**A patch too large to type** (novox/hq issue 852: a feature's diff is megabytes) goes as `patch_file`, with
|
||||
`patch_sha256`. The caller writes the patch into the module's spool directory `forge-patches`
|
||||
(`/var/lib/mesh/forge-patches`, mode 0733 and owned by the machine's account, which the tools run as: anyone writes,
|
||||
nobody lists; the bundle is given its path as `MESH_GITEA_PATCH_DIR`) and names it: `patch_file` is the file's NAME,
|
||||
(`/var/lib/mesh/forge-patches`, mode 0733 and owned by the machine's account: anyone writes, nobody lists, and the
|
||||
tools, which run as the module's own account gitea, read and remove the named file as any other account may; the bundle
|
||||
is given its path as `MESH_GITEA_PATCH_DIR`) and names it: `patch_file` is the file's NAME,
|
||||
32 to 64 characters of `0-9a-f` that the caller chooses at random, never a path. The tool then reads that one file,
|
||||
applies it exactly as it applies `patch` (same size limit, same answer) and removes it once it has found it, whether
|
||||
the commit was made or not. A file refused before that (a bad name, a missing hash or spool directory, a name with no
|
||||
|
||||
@@ -79,7 +79,7 @@ export type Say = (subject: string, body: unknown, id?: string) => Promise<void>
|
||||
|
||||
/** The merge-called of a kept call (design 47 H §736, §767): its landed members, each with its base and merge commit, and its
|
||||
* refused ones; undefined for a call that landed no member, which says none. A member merged plainly, carrying the note
|
||||
* no delivery (its repository has no watched branch), starts no delivery and is left out, by the kept note (H2 H-A-471). */
|
||||
* no delivery (its base is no watched branch), starts no delivery and is left out, by the kept note (H2 H-A-471). */
|
||||
export function mergeCalledOf(c: KeptCall): MergeCalledEvent | undefined {
|
||||
const landed = c.members.filter((m) => m.state === "merged" && m.commit && !m.note);
|
||||
if (landed.length === 0) return undefined;
|
||||
|
||||
@@ -127,20 +127,7 @@ export class CatalogView {
|
||||
/** The kind of a finding of a first view unanswered past its bound (ADR 0615 §6), as mesh-sdk's Go views writes it. */
|
||||
export const UNANSWERED_KIND = "first-view-unanswered";
|
||||
|
||||
/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */
|
||||
export function findingKey(scope: string, id: string, kind: string): string {
|
||||
return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join(".");
|
||||
}
|
||||
|
||||
/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */
|
||||
export function findingValue(f: Finding): { key: string; value: Record<string, unknown> } {
|
||||
const key = findingKey("module", f.id, f.kind);
|
||||
return { key, value: {
|
||||
v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline,
|
||||
explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`,
|
||||
observer: f.observer, at: f.at,
|
||||
} };
|
||||
}
|
||||
export { findingKey, findingValue } from "./findings.js";
|
||||
|
||||
/** A part's finding of a first view unanswered past its bound, from the follower's status. */
|
||||
export function unansweredFinding(part: string, s: Status, at: Date): Finding {
|
||||
|
||||
@@ -694,13 +694,6 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
|
||||
"cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER"},
|
||||
"cmd/package-registry": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_PACKAGES_USER"},
|
||||
}
|
||||
// H-A-564: until gitea runs as its own account, each Go bundle is handed the token files gitea's TypeScript bundle
|
||||
// keeps under its state directory, read when the vault refuses the caller's account.
|
||||
files := map[string]map[string]string{
|
||||
"cmd/forge": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token"},
|
||||
"cmd/package-registry": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
||||
"MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token"},
|
||||
}
|
||||
for _, a := range m.Build.Artifacts {
|
||||
want, ok := wants[a.From]
|
||||
if !ok {
|
||||
@@ -720,9 +713,10 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
|
||||
t.Errorf("%s is given %s: it acts as an account of its own, not the administrator", a.From, k)
|
||||
}
|
||||
}
|
||||
// H-A-575: the vault alone hands a token; no bundle is given a token file.
|
||||
for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} {
|
||||
if a.Env[k] != files[a.From][k] {
|
||||
t.Errorf("%s is given %s %q, want %q (H-A-564)", a.From, k, a.Env[k], files[a.From][k])
|
||||
if a.Env[k] != "" {
|
||||
t.Errorf("%s is given %s %q: a token is read from the vault alone (H-A-575)", a.From, k, a.Env[k])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
|
||||
// A patch too large to type into a call is handed over as a file (novox/hq issue 852). The caller writes it into
|
||||
// one spool directory the module declares (mode 0733: anyone writes, nobody lists) and names it in patch_file,
|
||||
// with the file's SHA-256. The tool runs as the machine's account, so it reads nothing but that directory: the
|
||||
// with the file's SHA-256. The tool runs as the module's own account gitea, and reads nothing but that directory: the
|
||||
// name is 32 to 64 characters of [0-9a-f], so it holds no separator and no dot; the file must be a regular file
|
||||
// (never a symlink); and its hash must be the caller's, because without the sticky bit another writer could have
|
||||
// replaced it. The file is removed once taken, whether the commit was made or not.
|
||||
|
||||
@@ -452,6 +452,10 @@ func retention(ctx context.Context, f *Forge, only string, keep int, dryRun bool
|
||||
} else {
|
||||
o.Module = c.Package
|
||||
}
|
||||
// The key kept for the version goes with it (design 47 H2 H-A-589 (2)).
|
||||
if err := unkept(c.Package, o.Version); err != nil {
|
||||
s.Said = append(s.Said, fmt.Sprintf("%s@%s is deleted but its key in the state %s is not: %v", c.Package, c.Version, packageseats.FingerprintsState, err))
|
||||
}
|
||||
if err := say(seat, packageseats.EventRemoved, o); err != nil {
|
||||
s.Said = append(s.Said, fmt.Sprintf("%s@%s is deleted but its removed could not be said: %v", c.Package, c.Version, err))
|
||||
}
|
||||
|
||||
@@ -281,8 +281,18 @@ func TestARealRunWithoutWhyIsRefusedBeforeAnythingIsRead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// init: no test of retention reaches the runtime's state `fingerprints`, whose call waits for a runtime a test has none of; a
|
||||
// test that reads what retention deletes there sets its own hook.
|
||||
func init() { unkept = func(string, string) error { return nil } }
|
||||
|
||||
func TestARealRunDeletesOnlyWhatNothingKeeps(t *testing.T) {
|
||||
f := aRegistry(t)
|
||||
// the key kept for each version goes with it (design 47 H2 H-A-589 (2))
|
||||
var unkeys []string
|
||||
unkept = func(name, version string) error {
|
||||
unkeys = append(unkeys, packageseats.FingerprintKey(name, version))
|
||||
return nil
|
||||
}
|
||||
var removed []string
|
||||
say = func(seat, event string, o packageseats.Outcome) error {
|
||||
removed = append(removed, seat+" "+event+" "+o.Name+"@"+o.Version+" "+o.Reason)
|
||||
@@ -303,6 +313,9 @@ func TestARealRunDeletesOnlyWhatNothingKeeps(t *testing.T) {
|
||||
if len(p.Deleted) != 4 || len(p.Refused) != 0 {
|
||||
t.Fatalf("answered %v / %v", p.Deleted, p.Refused)
|
||||
}
|
||||
if sort.Strings(unkeys); len(unkeys) != 4 || unkeys[0] != packageseats.FingerprintKey("@acme/sdk", "0.1.1") {
|
||||
t.Errorf("keys deleted %v, want one per deleted version", unkeys)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAVersionAGoModRequiresSurvivesGoRetention: the Go seat keeps what the npm seat keeps (design 51 *Retention*): a
|
||||
@@ -480,8 +493,8 @@ func TestToolsAreTheOnesTheReadmeNamesAndSayWhatTheyDo(t *testing.T) {
|
||||
Objects any `json:"objects"`
|
||||
State any `json:"state"`
|
||||
}{m.Objects, m.State})
|
||||
// Each with its cap (design 47 H2 §812, H-A-411 (2)).
|
||||
for _, want := range []string{`"name":"incoming"`, `"name":"transfers"`, `"key-ttl":true,"max-mib":8,"name":"idle"`} {
|
||||
// Each with its cap (design 47 H2 §812, H-A-411 (2)); the state fingerprints names its own, 16 MiB (H-A-589 (2)).
|
||||
for _, want := range []string{`"name":"incoming"`, `"name":"transfers"`, `"key-ttl":true,"max-mib":8,"name":"idle"`, `"max-mib":16,"name":"fingerprints"`} {
|
||||
if !strings.Contains(string(req), want) {
|
||||
t.Errorf("the manifest does not keep %s in its old sections (%s)", want, req)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
@@ -227,6 +228,30 @@ func outcomeBody(o packageseats.Outcome) map[string]any {
|
||||
"reference": o.Reference, "reason": o.Reason, "module": o.Module}
|
||||
}
|
||||
|
||||
// fingerprintsState is the state fingerprints through the runtime; a write at its cap fails (design 47 H2 H-A-589 (2)).
|
||||
type fingerprintsState struct{}
|
||||
|
||||
func (fingerprintsState) Get(key string) (packageseats.Kept, bool, error) {
|
||||
var k packageseats.Kept
|
||||
e, err := stdio.State(packageseats.FingerprintsState).Get(key)
|
||||
if err != nil || e == nil {
|
||||
return k, false, err
|
||||
}
|
||||
return k, true, json.Unmarshal(e.Value, &k)
|
||||
}
|
||||
func (fingerprintsState) Put(key string, k packageseats.Kept) error {
|
||||
_, err := stdio.State(packageseats.FingerprintsState).Put(key, k)
|
||||
return err
|
||||
}
|
||||
func (fingerprintsState) Delete(key string) error {
|
||||
return stdio.State(packageseats.FingerprintsState).Delete(key)
|
||||
}
|
||||
|
||||
// unkept deletes the key kept for name at version, as retention removes the version itself; a test replaces it.
|
||||
var unkept = func(name, version string) error {
|
||||
return fingerprintsState{}.Delete(packageseats.FingerprintKey(name, version))
|
||||
}
|
||||
|
||||
// say says a seat's event; a test hears it instead.
|
||||
var say = sayOn
|
||||
|
||||
@@ -257,8 +282,9 @@ var boundCap = parts.BusCap(packageseats.IncomingObjects)
|
||||
// busHolder is the holder over the runtime's bus state, the builder's reservation and the forge.
|
||||
func busHolder(forge func() (*Forge, error)) (*packageseats.Holder, error) {
|
||||
return &packageseats.Holder{Objects: parts.BusObjects(packageseats.IncomingObjects),
|
||||
Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState),
|
||||
Builder: packageseats.Reserved{Ask: stdio.Ask}, Store: seatStore{forge}, Say: say, Finding: findings.Say,
|
||||
Transfers: parts.BusTransfers[packageseats.Opening](packageseats.TransfersState),
|
||||
Fingerprints: fingerprintsState{}, Logf: func(f string, a ...any) { fmt.Fprintf(os.Stderr, f+"\n", a...) },
|
||||
Builder: packageseats.Reserved{Ask: stdio.Ask}, Store: seatStore{forge}, Say: say, Finding: findings.Say,
|
||||
Cap: boundCap, Record: recordAct, Idle: parts.BusArm(packageseats.IdleState)}, nil
|
||||
}
|
||||
|
||||
@@ -302,6 +328,15 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func()
|
||||
return nil, err
|
||||
}
|
||||
a, err := h.Publish(seat, stdio.CallerOf(args), p)
|
||||
if a.OtherBytes != nil {
|
||||
// No transfer is opened, so none is named (design 47 H2 H-A-732).
|
||||
other := map[string]any{"digest": a.OtherBytes.Digest}
|
||||
if a.OtherBytes.Fingerprint != "" {
|
||||
other["fingerprint"] = a.OtherBytes.Fingerprint
|
||||
}
|
||||
out, _ := as[PA](map[string]any{"other-bytes": other})
|
||||
return out, err
|
||||
}
|
||||
out, _ := as[PA](map[string]any{"transfer": a.Transfer, "lacks": a.Lacks, "held": a.Ended && len(a.Lacks) == 0})
|
||||
return out, err
|
||||
})},
|
||||
@@ -325,7 +360,7 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func()
|
||||
return out, err
|
||||
})},
|
||||
{Name: seat + "." + packageseats.VerbVersions, Input: obj,
|
||||
Description: "The versions the seat holds of one package, newest first, each with its digest.",
|
||||
Description: "The versions the seat holds of one package, newest first, each with its digest and the fingerprint kept for it where one is kept.",
|
||||
Run: run(func(h *packageseats.Holder, args map[string]any) (any, error) {
|
||||
in, err := as[VI](args)
|
||||
if err != nil {
|
||||
@@ -338,7 +373,11 @@ func verbTools[PI, PA, PPI, PPA, VI, VA, RI, RA any](seat string, holder func()
|
||||
}
|
||||
list := []map[string]any{}
|
||||
for _, v := range got {
|
||||
list = append(list, map[string]any{"name": q.Name, "version": v.Version, "digest": v.Digest, "kind": packageseats.KindPackage})
|
||||
entry := map[string]any{"name": q.Name, "version": v.Version, "digest": v.Digest, "kind": packageseats.KindPackage}
|
||||
if v.Fingerprint != "" {
|
||||
entry["fingerprint"] = v.Fingerprint
|
||||
}
|
||||
list = append(list, entry)
|
||||
}
|
||||
return as[VA](map[string]any{"name": q.Name, "versions": list})
|
||||
})},
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -229,3 +230,44 @@ func vaultHolding(t *testing.T, account string, held map[string]string) *forgeht
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// otherStore is a forge registry holding name@version at one digest.
|
||||
type otherStore struct{ digest string }
|
||||
|
||||
func (s otherStore) Held(string, string, string) (string, bool, error) { return s.digest, true, nil }
|
||||
func (otherStore) Put(string, packageseats.Publish, []byte) (string, error) {
|
||||
return "", errors.New("stored")
|
||||
}
|
||||
func (otherStore) Versions(string, string) ([]packageseats.Version, error) { return nil, nil }
|
||||
func (otherStore) Remove(string, string, string) error { return nil }
|
||||
|
||||
type keptState map[string]packageseats.Kept
|
||||
|
||||
func (k keptState) Get(key string) (packageseats.Kept, bool, error) {
|
||||
v, ok := k[key]
|
||||
return v, ok, nil
|
||||
}
|
||||
func (k keptState) Put(key string, v packageseats.Kept) error { k[key] = v; return nil }
|
||||
func (k keptState) Delete(key string) error { delete(k, key); return nil }
|
||||
|
||||
// A publish of a version the forge holds at another digest is answered with other-bytes, the held digest and the fingerprint
|
||||
// kept, in each seat's contract, and the answer names no transfer, as no transfer is opened (design 47 H2 H-A-729, H-A-732).
|
||||
func TestAPublishOfAHeldVersionIsAnsweredOtherBytesWithNoTransfer(t *testing.T) {
|
||||
h := &packageseats.Holder{Store: otherStore{digest: "sha256:aa"}, Fingerprints: keptState{
|
||||
packageseats.FingerprintKey("sdk", "0.1.15"): {Digest: "sha256:aa", Fingerprint: "f1"}}}
|
||||
for _, seat := range []string{packageseats.NpmSeat, packageseats.GoSeat} {
|
||||
for _, tool := range SeatTools(func() (*packageseats.Holder, error) { return h, nil }) {
|
||||
if tool.Name != seat+".publish" {
|
||||
continue
|
||||
}
|
||||
got, err := tool.Run(map[string]any{"name": "sdk", "version": "0.1.15", "kind": "package", "digest": "sha256:bb", "transfer": "t1"})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", seat, err)
|
||||
}
|
||||
raw, _ := json.Marshal(got)
|
||||
if !strings.Contains(string(raw), `"other-bytes":{"digest":"sha256:aa","fingerprint":"f1"}`) || strings.Contains(string(raw), `"transfer"`) {
|
||||
t.Errorf("%s: publish answered %s, want other-bytes with the held digest and kept fingerprint and no transfer", seat, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,7 +367,7 @@ func TestThePackageSeatsWhole(t *testing.T) {
|
||||
}
|
||||
t.Cleanup(nc.Close)
|
||||
js, _ := jetstream.New(nc)
|
||||
for _, b := range []string{"gitea_" + packageseats.TransfersState, "gitea_findings"} {
|
||||
for _, b := range []string{"gitea_" + packageseats.TransfersState, "gitea_findings", "gitea_" + packageseats.FingerprintsState} {
|
||||
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -482,6 +482,11 @@ func TestThePackageSeatsWhole(t *testing.T) {
|
||||
if !bytes.Equal(up, zipped) {
|
||||
t.Errorf("the forge took %d bytes, not the %d published", len(up), len(zipped))
|
||||
}
|
||||
// The key of the stored version is kept in the state fingerprints (design 47 H2 H-A-589 (2)).
|
||||
fingerprints, _ := js.KeyValue(ctx, "gitea_"+packageseats.FingerprintsState)
|
||||
if e, err := fingerprints.Get(ctx, packageseats.FingerprintKey("git.example/acme/sdk", "0.1.15")); err != nil || !strings.Contains(string(e.Value()), digest) {
|
||||
t.Errorf("the stored version's key in the state fingerprints: %v", err)
|
||||
}
|
||||
transfers, _ := js.KeyValue(ctx, "gitea_"+packageseats.TransfersState)
|
||||
if keys, _ := transfers.Keys(ctx); len(keys) != 0 {
|
||||
t.Errorf("an ended transfer is still kept: %v", keys)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// The key and the value of a finding a part writes into its own state `findings`, as the condition keeper reads it
|
||||
// (kept apart from catalog.ts, which loads the catalog seat's contract, so a part that only writes a finding loads nothing else).
|
||||
|
||||
import type { Finding } from "@novox/mesh-sdk/views";
|
||||
|
||||
/** The key of a finding about a module: scope, the id's dotted parts, and the kind, each part made safe (mesh-sdk health.Key). */
|
||||
export function findingKey(scope: string, id: string, kind: string): string {
|
||||
return [scope, ...id.split("."), kind].map((p) => p.trim().replace(/[^A-Za-z0-9_=/-]/g, "_") || "_").join(".");
|
||||
}
|
||||
|
||||
/** A finding as the condition keeper reads it from the module's state `findings`: its key and its value. */
|
||||
export function findingValue(f: Finding): { key: string; value: Record<string, unknown> } {
|
||||
const key = findingKey("module", f.id, f.kind);
|
||||
return { key, value: {
|
||||
v: 1, key, kind: f.kind, subject: { scope: "module", id: f.id }, severity: "warning", summary: f.summary, headline: f.headline,
|
||||
explanation: f.explanation, resolved: "", evidence: [{ at: f.at, said: f.summary }], source: `${f.observer}.${f.kind}`,
|
||||
observer: f.observer, at: f.at,
|
||||
} };
|
||||
}
|
||||
@@ -5,18 +5,13 @@ package forgehttp
|
||||
// through the seat `mesh-vault`'s `get`, sealed to this process's own key (the Go SDK's seal opens it), at start and at
|
||||
// each `secret-changed` that names it. The bundle holds the token in memory only, and says nothing of it.
|
||||
//
|
||||
// Until gitea runs as its own account (H-A-543), the vault refuses the tool runner's account these bundles are called
|
||||
// under, so (H-A-564) when the vault refuses the caller's account, the token is read from the file gitea's TypeScript
|
||||
// bundle keeps it in under its state directory (MESH_GITEA_TOKEN_FILE for the tools' account,
|
||||
// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, each with its scopes line beside it), and Follow says once
|
||||
// at start which source each token came from. The fallback ends with H-A-543's delivery.
|
||||
// Gitea runs as its own account, so the vault hands these bundles its own secrets; no file stands in for the vault
|
||||
// (H-A-575: the stand-in of H-A-564 ended with H-A-543's delivery).
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -36,41 +31,15 @@ func VaultName(account string) string { return "module/gitea/" + account }
|
||||
// Ask asks one seat verb and answers its reply (stdio.Ask).
|
||||
type Ask func(address string, args any) (json.RawMessage, error)
|
||||
|
||||
// Refusals are what the vault answers when it refuses the caller's account a module's own secret (mesh-vault's
|
||||
// callerModule and its own-secret judgement): the only answers the token file is read after (H-A-564).
|
||||
var Refusals = []string{"is no module's account", "handed only to an account of"}
|
||||
|
||||
// refused is whether err is the vault refusing the caller's account.
|
||||
func refused(err error) bool {
|
||||
for _, r := range Refusals {
|
||||
if strings.Contains(err.Error(), r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Sources of a token: the vault, or the file gitea's TypeScript bundle keeps (H-A-564).
|
||||
const (
|
||||
SourceVault = "the vault"
|
||||
SourceFile = "the file gitea keeps"
|
||||
)
|
||||
|
||||
// VaultToken is one account's token as this process holds it, read from the vault, or from File when the vault
|
||||
// refuses the caller's account (H-A-564).
|
||||
// VaultToken is one account's token as this process holds it, read from the vault alone.
|
||||
type VaultToken struct {
|
||||
Account string
|
||||
// File is the token file gitea's TypeScript bundle keeps for Account, "" when the manifest names none.
|
||||
File string
|
||||
// FileByDefault says File is DefaultStateDir's, the manifest naming none.
|
||||
FileByDefault bool
|
||||
ask Ask
|
||||
keys seal.KeyPair
|
||||
ask Ask
|
||||
keys seal.KeyPair
|
||||
|
||||
mu sync.Mutex
|
||||
token string
|
||||
generation int
|
||||
source string
|
||||
}
|
||||
|
||||
// NewVaultToken is an account's token read through ask, sealed to a key made for this process.
|
||||
@@ -82,20 +51,10 @@ func NewVaultToken(account string, ask Ask) (*VaultToken, error) {
|
||||
return &VaultToken{Account: account, ask: ask, keys: keys}, nil
|
||||
}
|
||||
|
||||
// Load reads the account's token from the vault again; from File when the vault refuses the caller's account.
|
||||
// Load reads the account's token from the vault again.
|
||||
func (t *VaultToken) Load() error {
|
||||
raw, err := t.ask(VaultGet, map[string]any{"name": VaultName(t.Account), "public_key": t.keys.PublicKey})
|
||||
if err != nil {
|
||||
if t.File != "" && refused(err) {
|
||||
token, ferr := t.fromFile()
|
||||
if ferr != nil {
|
||||
return fmt.Errorf("the vault did not hand %s (%v), and %w", VaultName(t.Account), err, ferr)
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.token, t.generation, t.source = token, 0, SourceFile
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("the vault did not hand %s: %w", VaultName(t.Account), err)
|
||||
}
|
||||
var got struct {
|
||||
@@ -121,45 +80,16 @@ func (t *VaultToken) Load() error {
|
||||
return fmt.Errorf("the vault's %s is empty", VaultName(t.Account))
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.token, t.generation, t.source = token, got.Generation, SourceVault
|
||||
t.token, t.generation = token, got.Generation
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// fromFile is the token gitea's TypeScript bundle keeps in File, refused unless its scopes line names Account (as the
|
||||
// bundle writes it: "<scopes> for <account>").
|
||||
func (t *VaultToken) fromFile() (string, error) {
|
||||
raw, err := os.ReadFile(t.File)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the token file gitea keeps for %s cannot be read: %w", t.Account, err)
|
||||
}
|
||||
line, err := os.ReadFile(t.File + ".scopes")
|
||||
if err != nil || !strings.HasSuffix(strings.TrimSpace(string(line)), " for "+t.Account) {
|
||||
return "", fmt.Errorf("the token kept at %s is not %s's (its scopes line does not name it); nothing is sent", t.File, t.Account)
|
||||
}
|
||||
token := strings.TrimSpace(string(raw))
|
||||
if token == "" {
|
||||
return "", fmt.Errorf("the token kept at %s is empty; nothing is sent", t.File)
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// Source is where the token held came from, SourceVault or SourceFile; "" when none is held.
|
||||
func (t *VaultToken) Source() string {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.source
|
||||
}
|
||||
|
||||
// Token is the token held; read from the vault when none is yet (the module mints it first).
|
||||
func (t *VaultToken) Token() (string, error) {
|
||||
t.mu.Lock()
|
||||
token, source := t.token, t.source
|
||||
token := t.token
|
||||
t.mu.Unlock()
|
||||
if source == SourceFile {
|
||||
// gitea's TypeScript bundle mints into its file again on a refusal: the file is read at each call, as before C4.
|
||||
return t.fromFile()
|
||||
}
|
||||
if token != "" {
|
||||
return token, nil
|
||||
}
|
||||
@@ -208,45 +138,12 @@ func TokenOf(account string) (*VaultToken, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.File, t.FileByDefault = TokenFile(account)
|
||||
processTokens[account] = t
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// DefaultStateDir is gitea's runtime-state directory (the manifest's `${dir:mesh-state}/state`), where its TypeScript
|
||||
// bundle keeps the token files, for a composition that hands the Go bundles no token file (gitea 0.1.316 hands them
|
||||
// no variable naming that directory either; H-A-564).
|
||||
const DefaultStateDir = "/var/lib/mesh/gitea/state"
|
||||
|
||||
// TokenFile is the file the manifest names for account's token as gitea's TypeScript bundle keeps it (H-A-564):
|
||||
// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, MESH_GITEA_TOKEN_FILE for the tools' account; when the
|
||||
// variable is not handed, the file in DefaultStateDir, and byDefault says so. "" for any other account.
|
||||
func TokenFile(account string) (file string, byDefault bool) {
|
||||
packages := os.Getenv("MESH_GITEA_PACKAGES_USER")
|
||||
if packages == "" {
|
||||
packages = PackagesAccount
|
||||
}
|
||||
tools := os.Getenv("MESH_GITEA_TOOLS_USER")
|
||||
if tools == "" {
|
||||
tools = ToolsAccount
|
||||
}
|
||||
variable, name := "", ""
|
||||
switch account {
|
||||
case packages:
|
||||
variable, name = "MESH_GITEA_PACKAGES_TOKEN_FILE", "packages-token"
|
||||
case tools:
|
||||
variable, name = "MESH_GITEA_TOKEN_FILE", "token"
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
if f := os.Getenv(variable); f != "" {
|
||||
return f, false
|
||||
}
|
||||
return filepath.Join(DefaultStateDir, name), true
|
||||
}
|
||||
|
||||
// Follow reads each account's token once the runtime serves, and again at each `secret-changed` naming it, saying
|
||||
// through logf what it read and, once at start, from which source (never the token). It returns when the
|
||||
// through logf what it read (never the token). It returns when the
|
||||
// subscription ends.
|
||||
func Follow(logf func(format string, args ...any), accounts ...string) error {
|
||||
var held []*VaultToken
|
||||
@@ -273,21 +170,13 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
|
||||
})
|
||||
}
|
||||
|
||||
// Start reads each token once and says, through logf, from which source it came (H-A-564), never the token.
|
||||
// Start reads each token once and says, through logf, that it did (never the token).
|
||||
func Start(logf func(format string, args ...any), held ...*VaultToken) {
|
||||
for _, t := range held {
|
||||
switch err := t.Load(); {
|
||||
case err != nil:
|
||||
if err := t.Load(); err != nil {
|
||||
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
|
||||
case t.Source() == SourceFile:
|
||||
how := "named by the manifest"
|
||||
if t.FileByDefault {
|
||||
how = "the default path, the manifest naming none"
|
||||
}
|
||||
logf("the vault refuses %s to this process's account, so %s's token is read from %s, %s (%s; H-A-564)",
|
||||
VaultName(t.Account), t.Account, SourceFile, t.File, how)
|
||||
default:
|
||||
logf("read %s at generation %d from %s", VaultName(t.Account), t.Generation(), SourceVault)
|
||||
continue
|
||||
}
|
||||
logf("read %s at generation %d", VaultName(t.Account), t.Generation())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,33 +4,15 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/seal"
|
||||
)
|
||||
|
||||
// H-A-564: until gitea runs as its own account, a Go bundle the vault refuses reads the token gitea's TypeScript
|
||||
// bundle keeps in its state directory, and says once at start which source it used; any other refusal reads no file.
|
||||
func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFileGiteaKeeps(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
keep := func(name, token, scopes string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(token+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if scopes != "" {
|
||||
if err := os.WriteFile(p+".scopes", []byte(scopes+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
tools := keep("token", "file-tools", "read:package,read:user,write:issue,write:repository for mesh-tools")
|
||||
packages := keep("packages-token", "file-packages", "write:package for mesh-packages")
|
||||
admins := keep("admins-token", "file-admin", "write:admin")
|
||||
// H-A-575: a Go bundle reads its token from the vault alone and says it did at start; whatever the vault refuses, no
|
||||
// token file stands in (the stand-in of H-A-564 is gone).
|
||||
func TestATokenComesFromTheVaultAloneAndNoFileStandsInWhenTheVaultRefuses(t *testing.T) {
|
||||
vaultHolds := func(token string) Ask {
|
||||
return func(address string, args any) (json.RawMessage, error) {
|
||||
a := args.(map[string]any)
|
||||
@@ -45,27 +27,23 @@ func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFil
|
||||
vaultSays := func(said string) Ask {
|
||||
return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) }
|
||||
}
|
||||
notModule := vaultSays("novox.node-tools is no module's account (<machine>.<module>), so it has no own secret here")
|
||||
for _, c := range []struct {
|
||||
name, account, file string
|
||||
ask Ask
|
||||
token, source, err string
|
||||
name, account string
|
||||
ask Ask
|
||||
token, err string
|
||||
}{
|
||||
{"the vault hands it", "mesh-tools", tools, vaultHolds("vault-tools"), "vault-tools", SourceVault, ""},
|
||||
{"the vault refuses the tool runner: the tools' file", "mesh-tools", tools, notModule, "file-tools", SourceFile, ""},
|
||||
{"the vault refuses the tool runner: the packages file", "mesh-packages", packages, notModule, "file-packages", SourceFile, ""},
|
||||
{"another module's account: the file", "mesh-tools", tools,
|
||||
vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "file-tools", SourceFile, ""},
|
||||
{"the vault holds none: no file is read", "mesh-tools", tools, vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "", "holds no secret"},
|
||||
{"no file named: the refusal stands", "mesh-tools", "", notModule, "", "", "no module's account"},
|
||||
{"a file whose scopes line names another account is not sent", "mesh-tools", admins, notModule, "", "", "is not mesh-tools's"},
|
||||
{"the vault hands it", "mesh-tools", vaultHolds("vault-tools"), "vault-tools", ""},
|
||||
{"the vault refuses the tool runner: no file is read", "mesh-packages",
|
||||
vaultSays("novox.node-tools is no module's account (<machine>.<module>), so it has no own secret here"), "", "no module's account"},
|
||||
{"another module's account: no file is read", "mesh-tools",
|
||||
vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "", "handed only to an account of gitea"},
|
||||
{"the vault holds none", "mesh-tools", vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "holds no secret"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
v, err := NewVaultToken(c.account, c.ask)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.File = c.file
|
||||
var said []string
|
||||
Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v)
|
||||
got, err := v.Token()
|
||||
@@ -75,64 +53,12 @@ func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFil
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || got != c.token || v.Source() != c.source {
|
||||
t.Fatalf("token %q from %q (%v); want %q from %q", got, v.Source(), err, c.token, c.source)
|
||||
if err != nil || got != c.token {
|
||||
t.Fatalf("token %q (%v); want %q", got, err, c.token)
|
||||
}
|
||||
if len(said) != 1 || !strings.Contains(said[0], c.source) || strings.Contains(said[0], c.token) {
|
||||
t.Fatalf("said %q: one line naming %q, never the token", said, c.source)
|
||||
if len(said) != 1 || strings.Contains(said[0], c.token) || strings.Contains(said[0], "file") {
|
||||
t.Fatalf("said %q: one line, never the token and naming no file", said)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A token gitea mints into its file again is the one sent next.
|
||||
v, _ := NewVaultToken("mesh-tools", notModule)
|
||||
v.File = tools
|
||||
Start(func(string, ...any) {}, v)
|
||||
keep("token", "file-tools-2", "read:package for mesh-tools")
|
||||
if got, _ := v.Token(); got != "file-tools-2" {
|
||||
t.Fatalf("after gitea minted again, %q is sent", got)
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-564: the manifest's file for each account wins; without it, the file in gitea's runtime-state directory, said
|
||||
// as the default.
|
||||
func TestTheTokenFileOfAnAccountIsTheOneTheManifestNamesForItElseTheDefault(t *testing.T) {
|
||||
type file struct {
|
||||
path string
|
||||
byDefault bool
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
tools, packs string
|
||||
want map[string]file
|
||||
}{
|
||||
{"named by the manifest", "/s/token", "/s/packages-token", map[string]file{
|
||||
"mesh-tools": {"/s/token", false}, "mesh-packages": {"/s/packages-token", false}, "other": {"", false}}},
|
||||
{"named by none: the default", "", "", map[string]file{
|
||||
"mesh-tools": {"/var/lib/mesh/gitea/state/token", true},
|
||||
"mesh-packages": {"/var/lib/mesh/gitea/state/packages-token", true}, "other": {"", false}}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
t.Setenv("MESH_GITEA_TOKEN_FILE", c.tools)
|
||||
t.Setenv("MESH_GITEA_PACKAGES_TOKEN_FILE", c.packs)
|
||||
for account, want := range c.want {
|
||||
if p, d := TokenFile(account); (file{p, d}) != want {
|
||||
t.Errorf("TokenFile(%s) = %q, %v; want %q, %v", account, p, d, want.path, want.byDefault)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// The start line says the default as such.
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "token")
|
||||
_ = os.WriteFile(p, []byte("t\n"), 0o600)
|
||||
_ = os.WriteFile(p+".scopes", []byte("read:user for mesh-tools\n"), 0o600)
|
||||
v, _ := NewVaultToken("mesh-tools", func(string, any) (json.RawMessage, error) {
|
||||
return nil, errors.New("novox.node-tools is no module's account")
|
||||
})
|
||||
v.File, v.FileByDefault = p, true
|
||||
var said string
|
||||
Start(func(f string, a ...any) { said = fmt.Sprintf(f, a...) }, v)
|
||||
if !strings.Contains(said, "the default path") {
|
||||
t.Fatalf("said %q, not that the file is the default", said)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/parts"
|
||||
keyparts "git.novox.be/novox/mesh-sdk/go/keys"
|
||||
)
|
||||
|
||||
// The seats the forge module holds.
|
||||
@@ -56,6 +57,9 @@ const (
|
||||
// IdleState is the state of one key per open transfer with its own time to live (a state declared key-ttl): its
|
||||
// end is the event that drops a transfer left with no chunk for TransferIdle, never a timer.
|
||||
IdleState = "idle"
|
||||
// FingerprintsState is the state fingerprints: the digest and fingerprint each version this holder stored was published
|
||||
// with (design 47 H2 H-A-589 (2)).
|
||||
FingerprintsState = "fingerprints"
|
||||
// KindPackage is the one kind a package seat holds.
|
||||
KindPackage = "package"
|
||||
// Self is the forge module, the holder every outcome names.
|
||||
@@ -99,6 +103,36 @@ type Answer struct {
|
||||
Transfer string
|
||||
Lacks []string
|
||||
Ended bool
|
||||
// OtherBytes is set when the forge holds the publish's name and version with another digest and keeps another
|
||||
// fingerprint for it, or none: the call does not fail and no transfer is opened (design 47 H2 H-A-729, H-A-732).
|
||||
OtherBytes *OtherBytes
|
||||
}
|
||||
|
||||
// OtherBytes is the digest the forge holds for a name and version, and the fingerprint it keeps for them, empty where it
|
||||
// keeps none.
|
||||
type OtherBytes struct {
|
||||
Digest string
|
||||
Fingerprint string
|
||||
}
|
||||
|
||||
// Kept is one key of the state fingerprints: the digest and the fingerprint the publish of a version named.
|
||||
type Kept struct {
|
||||
Digest string `json:"digest"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
}
|
||||
|
||||
// FingerprintKey is the key of name at version in the state fingerprints: `<name>.<version>`, each token escaped as a key's
|
||||
// name is (design 47 H2 H-A-589 (2)).
|
||||
func FingerprintKey(name, version string) string {
|
||||
return keyparts.EscapeName(name) + "." + keyparts.EscapeName(version)
|
||||
}
|
||||
|
||||
// FingerprintState is the holder's own state fingerprints (bus state, template state; ADR 0595), reached by the holder
|
||||
// alone; a write at its cap fails.
|
||||
type FingerprintState interface {
|
||||
Get(key string) (Kept, bool, error)
|
||||
Put(key string, k Kept) error
|
||||
Delete(key string) error
|
||||
}
|
||||
|
||||
// Version is one version a seat holds of a name.
|
||||
@@ -106,6 +140,8 @@ type Version struct {
|
||||
Version string
|
||||
Digest string
|
||||
Published time.Time
|
||||
// Fingerprint is the one kept for the version, empty where none is kept (H-A-589 (3)).
|
||||
Fingerprint string
|
||||
}
|
||||
|
||||
// Builder answers whether the builder reserved a version with a digest (Reserved).
|
||||
@@ -129,8 +165,10 @@ type Store interface {
|
||||
type Holder struct {
|
||||
Objects parts.Objects
|
||||
Transfers parts.Transfers[Opening]
|
||||
Builder Builder
|
||||
Store Store
|
||||
// Fingerprints keeps the fingerprint of each version the holder stored (H-A-589 (2)).
|
||||
Fingerprints FingerprintState
|
||||
Builder Builder
|
||||
Store Store
|
||||
// Say says an event on a seat's family.
|
||||
Say func(seat, event string, o Outcome) error
|
||||
// Finding writes (raised) or clears the module's finding of a kind for a subject.
|
||||
@@ -144,6 +182,8 @@ type Holder struct {
|
||||
// Idle writes a transfer's idle key with its own time to live, once (parts.BusArm over IdleState); the receiver
|
||||
// arms it on each open that leaves a transfer open. Nil arms nothing.
|
||||
Idle func(key string, ttl time.Duration) error
|
||||
// Logf is the journal; nil says nothing.
|
||||
Logf func(string, ...any)
|
||||
}
|
||||
|
||||
// CapNow is incoming's cap as its binding carries it.
|
||||
@@ -178,8 +218,16 @@ func (h *Holder) receiver() *parts.Receiver[Opening] {
|
||||
},
|
||||
Store: func(t Transfer, held map[string][]byte) error {
|
||||
file := held[t.Shape.Digest]
|
||||
// The key is written before the forge takes the version: a write the state refuses at its cap refuses the publish.
|
||||
if err := h.Fingerprints.Put(FingerprintKey(t.Shape.Name, t.Shape.Version), Kept{Digest: t.Shape.Digest, Fingerprint: t.Shape.Fingerprint}); err != nil {
|
||||
reason := fmt.Sprintf("the state %s did not take the key of %s@%s (it refuses at its cap), so nothing is stored: %v", FingerprintsState, t.Shape.Name, t.Shape.Version, err)
|
||||
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
|
||||
}
|
||||
module, err := h.Store.Put(t.Shape.Seat, t.Shape.Publish, file)
|
||||
if err != nil {
|
||||
if derr := h.Fingerprints.Delete(FingerprintKey(t.Shape.Name, t.Shape.Version)); derr != nil {
|
||||
h.logf("publish: the key of %s@%s stays in the state %s: %v", t.Shape.Name, t.Shape.Version, FingerprintsState, derr)
|
||||
}
|
||||
reason := "the forge did not take it: " + err.Error()
|
||||
return errors.Join(errors.New("refused: "+reason), h.refused(t, reason))
|
||||
}
|
||||
@@ -220,21 +268,13 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) {
|
||||
if err := checkPublish(seat, p); err != nil {
|
||||
return Answer{}, err
|
||||
}
|
||||
// A rebuild of a published version answers it held and uploads nothing; the same version with other content is
|
||||
// refused, as the registry would refuse it.
|
||||
// A rebuild of a published version answers it held and uploads nothing. The same version with other content is answered
|
||||
// other-bytes with the fingerprint the holder keeps for it (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)).
|
||||
if d, ok, err := h.Store.Held(seat, p.Name, p.Version); err != nil {
|
||||
return Answer{}, fmt.Errorf("publish: the forge cannot say whether it holds %s@%s: %w", p.Name, p.Version, err)
|
||||
} else if ok {
|
||||
if d != p.Digest {
|
||||
reason := fmt.Sprintf("%s@%s is published with %s, not %s", p.Name, p.Version, d, p.Digest)
|
||||
if len(p.Parts) == 0 {
|
||||
// The builder's publish again names nothing the forge holds under that digest: refused as not stored (A-490,
|
||||
// A-490a), the words its republish recognises.
|
||||
reason = "not stored: " + reason
|
||||
return Answer{Transfer: p.Transfer, Ended: true}, errors.Join(errors.New("publish: "+reason), h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason))
|
||||
}
|
||||
// A one-part publish of a taken version is refused with an event only, as the registry would (the builder's "version taken").
|
||||
return Answer{Transfer: p.Transfer, Ended: true}, h.refused(Transfer{Shape: Opening{Publish: p, Seat: seat}}, reason)
|
||||
return h.heldElsewhere(p, d)
|
||||
}
|
||||
o := outcomeOf(p, "")
|
||||
o.Reference = Reference(p.Name, p.Version)
|
||||
@@ -258,6 +298,29 @@ func (h *Holder) Publish(seat, caller string, p Publish) (Answer, error) {
|
||||
return h.answer(p.Transfer, got), nil
|
||||
}
|
||||
|
||||
// heldElsewhere answers a publish of a version the forge holds at the digest other, not the publish's: other-bytes, the held
|
||||
// digest and the fingerprint kept for it (empty where none, a key naming another digest than the forge holds speaks for
|
||||
// nothing), the call not failing, nothing stored and no transfer opened. The reader compares the kept fingerprint with the
|
||||
// publish's own (H-A-589 (1), H-A-729, H-A-732, H-A-738 (1)). The journal says both digests and both fingerprints.
|
||||
func (h *Holder) heldElsewhere(p Publish, other string) (Answer, error) {
|
||||
k, found, err := h.Fingerprints.Get(FingerprintKey(p.Name, p.Version))
|
||||
if err != nil {
|
||||
return Answer{}, fmt.Errorf("publish: the fingerprint kept for %s@%s cannot be read: %w", p.Name, p.Version, err)
|
||||
}
|
||||
kept := ""
|
||||
if found && k.Digest == other {
|
||||
kept = k.Fingerprint
|
||||
}
|
||||
h.logf("publish: %s@%s is held at digest %s with fingerprint %q; the offer is digest %s with fingerprint %q: answered other-bytes, nothing stored", p.Name, p.Version, other, kept, p.Digest, p.Fingerprint)
|
||||
return Answer{OtherBytes: &OtherBytes{Digest: other, Fingerprint: kept}}, nil
|
||||
}
|
||||
|
||||
func (h *Holder) logf(format string, a ...any) {
|
||||
if h.Logf != nil {
|
||||
h.Logf(format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
// PublishPart is `publish-part`: one chunk, from the caller that opened the transfer alone.
|
||||
func (h *Holder) PublishPart(seat, caller, transfer, part string, sequence int, last bool, data []byte) (Answer, error) {
|
||||
got, err := h.receiver().Take(key(seat, transfer), caller, part, sequence, last, data, func(t Transfer) error {
|
||||
@@ -284,6 +347,15 @@ func (h *Holder) Versions(seat, caller, name string) ([]Version, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("versions: the forge cannot list %s: %w", name, err)
|
||||
}
|
||||
for i := range v {
|
||||
k, found, err := h.Fingerprints.Get(FingerprintKey(name, v[i].Version))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("versions: the fingerprint kept for %s@%s cannot be read: %w", name, v[i].Version, err)
|
||||
}
|
||||
if found && k.Digest == v[i].Digest {
|
||||
v[i].Fingerprint = k.Fingerprint
|
||||
}
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
@@ -308,12 +380,18 @@ func (h *Holder) Remove(seat, caller, name, version, reason string) (Outcome, er
|
||||
return Outcome{}, fmt.Errorf("remove: the forge did not remove %s@%s: %w", name, version, err)
|
||||
}
|
||||
}
|
||||
if err := h.Fingerprints.Delete(FingerprintKey(name, version)); err != nil {
|
||||
return Outcome{}, fmt.Errorf("remove: %s@%s is removed, but its key in the state %s is not deleted: %w", name, version, FingerprintsState, err)
|
||||
}
|
||||
o := Outcome{Name: name, Version: version, Kind: KindPackage, Digest: d, Reason: reason}
|
||||
return o, h.Say(seat, EventRemoved, o)
|
||||
}
|
||||
|
||||
// Retained says `removed` for a version the forge's own retention deleted (design 51 *Retention*).
|
||||
func (h *Holder) Retained(seat, name, version, digest string) error {
|
||||
if err := h.Fingerprints.Delete(FingerprintKey(name, version)); err != nil {
|
||||
return fmt.Errorf("retained: %s@%s is removed, but its key in the state %s is not deleted: %w", name, version, FingerprintsState, err)
|
||||
}
|
||||
return h.Say(seat, EventRemoved, Outcome{Name: name, Version: version, Kind: KindPackage, Digest: digest, Reason: ReasonRetention})
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -112,9 +113,25 @@ type bed struct {
|
||||
findings map[string]bool
|
||||
}
|
||||
|
||||
// memFingerprints is the state fingerprints in memory; full makes a write fail as the state does at its cap.
|
||||
type memFingerprints struct {
|
||||
m map[string]Kept
|
||||
full bool
|
||||
}
|
||||
|
||||
func (f *memFingerprints) Get(k string) (Kept, bool, error) { v, ok := f.m[k]; return v, ok, nil }
|
||||
func (f *memFingerprints) Put(k string, v Kept) error {
|
||||
if f.full {
|
||||
return errors.New("the bucket is at its cap")
|
||||
}
|
||||
f.m[k] = v
|
||||
return nil
|
||||
}
|
||||
func (f *memFingerprints) Delete(k string) error { delete(f.m, k); return nil }
|
||||
|
||||
func newBed(numbered bool) *bed {
|
||||
b := &bed{forge: &forge{files: map[string]map[string][]byte{}}, findings: map[string]bool{}}
|
||||
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Builder: builder{ok: numbered},
|
||||
b.h = &Holder{Objects: memObjects{}, Transfers: memTransfers{}, Fingerprints: &memFingerprints{m: map[string]Kept{}}, Builder: builder{ok: numbered},
|
||||
Store: b.forge, Now: func() time.Time { return time.Unix(1e9, 0) },
|
||||
Say: func(seat, event string, o Outcome) error { b.said = append(b.said, said{seat, event, o}); return nil },
|
||||
Finding: func(kind, subject, _ string, raised bool) { b.findings[kind+" "+subject] = raised }}
|
||||
@@ -168,17 +185,40 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
|
||||
t.Run("the publish conformance cases on "+seat, func(t *testing.T) {
|
||||
publishconformance.Run(t, func(t *testing.T) publishconformance.Bed {
|
||||
b := newBed(true)
|
||||
publish := func(name, version, digest, fingerprint string) publishconformance.Outcome {
|
||||
a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest, Fingerprint: fingerprint})
|
||||
o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err}
|
||||
if a.OtherBytes != nil {
|
||||
o.Other = &publishconformance.OtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}
|
||||
}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
|
||||
}
|
||||
return o
|
||||
}
|
||||
return publishconformance.Bed{
|
||||
Hold: func(d string) {
|
||||
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
|
||||
},
|
||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
||||
a, err := b.h.Publish(seat, goBuild, Publish{Transfer: "t", Name: name, Version: version, Kind: KindPackage, Digest: digest})
|
||||
o := publishconformance.Outcome{Ended: a.Ended, Lacks: len(a.Lacks), Err: err}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
|
||||
HoldWith: func(d, fp string) {
|
||||
b.forge.holdDigest(seat, publishconformance.Name, publishconformance.Version, d)
|
||||
if fp != "" {
|
||||
_ = b.h.Fingerprints.Put(FingerprintKey(publishconformance.Name, publishconformance.Version), Kept{Digest: d, Fingerprint: fp})
|
||||
}
|
||||
return o
|
||||
},
|
||||
Held: func(name, version string) (string, string) {
|
||||
d, _, _ := b.forge.Held(seat, name, version)
|
||||
k, found, _ := b.h.Fingerprints.Get(FingerprintKey(name, version))
|
||||
if !found || k.Digest != d {
|
||||
return d, ""
|
||||
}
|
||||
return d, k.Fingerprint
|
||||
},
|
||||
Publish: func(name, version, digest string) publishconformance.Outcome {
|
||||
return publish(name, version, digest, "")
|
||||
},
|
||||
PublishWith: func(name, version, digest, fingerprint string) publishconformance.Outcome {
|
||||
return publish(name, version, digest, fingerprint)
|
||||
}}
|
||||
})
|
||||
})
|
||||
@@ -206,10 +246,13 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
|
||||
Hold: func() { b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first"))) },
|
||||
PublishWhole: func() publishconformance.Outcome {
|
||||
a, err := b.h.Publish(seat, goBuild, pub("mesh-sdk", "0.1.19", whole))
|
||||
if err == nil && !a.Ended {
|
||||
if err == nil && !a.Ended && a.OtherBytes == nil {
|
||||
_, err = b.h.PublishPart(seat, goBuild, "t-mesh-sdk", digest(whole), 0, true, whole)
|
||||
}
|
||||
o := publishconformance.Outcome{Err: err}
|
||||
if a.OtherBytes != nil {
|
||||
o.Other = &publishconformance.OtherBytes{Digest: a.OtherBytes.Digest, Fingerprint: a.OtherBytes.Fingerprint}
|
||||
}
|
||||
if len(b.said) > 0 {
|
||||
o.Event, o.Reason = b.said[len(b.said)-1].event, b.said[len(b.said)-1].o.Reason
|
||||
}
|
||||
@@ -218,6 +261,72 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
|
||||
})
|
||||
})
|
||||
}
|
||||
// H-A-589, H-A-729, H-A-732, H-A-738 (1): a held version offered again is answered other-bytes with the fingerprint the holder keeps, per seat.
|
||||
t.Run("a held version is answered by its kept fingerprint", func(t *testing.T) {
|
||||
for _, seat := range []string{NpmSeat, GoSeat} {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
kept, offer string
|
||||
noKey bool
|
||||
wantOther *OtherBytes
|
||||
noParts bool
|
||||
}{
|
||||
{name: "the offered fingerprint is the kept one: other-bytes carrying it", kept: "f1", offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}},
|
||||
{name: "the same, with no parts", kept: "f1", offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}, noParts: true},
|
||||
{name: "another fingerprint is other-bytes with the kept one", kept: "f1", offer: "f2", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}},
|
||||
{name: "no fingerprint kept is other-bytes with none", noKey: true, offer: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first"))}},
|
||||
{name: "no fingerprint offered is other-bytes", kept: "f1", wantOther: &OtherBytes{Digest: digest([]byte("first")), Fingerprint: "f1"}, noParts: true},
|
||||
} {
|
||||
b := newBed(true)
|
||||
b.forge.holdDigest(seat, "mesh-sdk", "0.1.19", digest([]byte("first")))
|
||||
if !c.noKey {
|
||||
_ = b.h.Fingerprints.Put(FingerprintKey("mesh-sdk", "0.1.19"), Kept{Digest: digest([]byte("first")), Fingerprint: c.kept})
|
||||
}
|
||||
p := pub("mesh-sdk", "0.1.19", file)
|
||||
p.Fingerprint = c.offer
|
||||
if c.noParts {
|
||||
p.Parts = nil
|
||||
}
|
||||
a, err := b.h.Publish(seat, goBuild, p)
|
||||
if err != nil || !reflect.DeepEqual(a.OtherBytes, c.wantOther) || len(b.forge.files[seat]) != 0 || len(a.Lacks) != 0 || len(b.h.Transfers.(memTransfers)) != 0 {
|
||||
t.Errorf("%s, %s: answered %+v, %v; stored %v", seat, c.name, a, err, b.forge.files[seat])
|
||||
}
|
||||
if a.Ended || a.Transfer != "" || len(b.said) != 0 {
|
||||
t.Errorf("%s, %s: answered %+v, said %+v; want no transfer, not ended, nothing said", seat, c.name, a, b.said)
|
||||
}
|
||||
}
|
||||
// the key is written when a version is stored, read by versions, deleted at removed
|
||||
b := newBed(true)
|
||||
p := pub("mesh-sdk", "0.1.19-b", file)
|
||||
p.Fingerprint = "f9"
|
||||
if _, err := b.h.Publish(seat, goBuild, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.h.PublishPart(seat, goBuild, p.Transfer, digest(file), 0, true, file); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if k, ok, _ := b.h.Fingerprints.Get(FingerprintKey("mesh-sdk", "0.1.19-b")); !ok || k != (Kept{Digest: digest(file), Fingerprint: "f9"}) {
|
||||
t.Errorf("%s: the key after the store = %+v, %v", seat, k, ok)
|
||||
}
|
||||
if v, _ := b.h.Versions(seat, "g14.anyone", "mesh-sdk"); len(v) != 1 || v[0].Fingerprint != "f9" {
|
||||
t.Errorf("%s: versions answered %+v, want fingerprint f9", seat, v)
|
||||
}
|
||||
if _, err := b.h.Remove(seat, "novox.mesh-delivery-builder", "mesh-sdk", "0.1.19-b", "tag-gone"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok, _ := b.h.Fingerprints.Get(FingerprintKey("mesh-sdk", "0.1.19-b")); ok {
|
||||
t.Errorf("%s: the key stayed after removed", seat)
|
||||
}
|
||||
// a version stored while the state is at its cap is refused and nothing is stored
|
||||
b = newBed(true)
|
||||
b.h.Fingerprints.(*memFingerprints).full = true
|
||||
p = pub("mesh-sdk", "0.1.20", file)
|
||||
_, _ = b.h.Publish(seat, goBuild, p)
|
||||
if _, err := b.h.PublishPart(seat, goBuild, p.Transfer, digest(file), 0, true, file); err == nil || !strings.Contains(err.Error(), "fingerprints did not take the key") || len(b.forge.files[seat]) != 0 || len(b.said) != 1 || b.said[0].event != EventRefused {
|
||||
t.Errorf("%s: a version at the state's cap = %v; said %+v; stored %v", seat, err, b.said, b.forge.files[seat])
|
||||
}
|
||||
}
|
||||
})
|
||||
// Design 47 G A-73, A-417: the builder's publish again names the version and the digest and no parts.
|
||||
t.Run("a publish with a digest and no parts is published when held, refused as not stored when not", func(t *testing.T) {
|
||||
for _, seat := range []string{NpmSeat, GoSeat} {
|
||||
@@ -367,11 +476,11 @@ func TestTheForgeHoldsBothPackageSeats(t *testing.T) {
|
||||
!strings.Contains(err.Error(), "send the part again") || len(b.said) != 0 || len(b.forge.files[NpmSeat]) != 0 {
|
||||
t.Errorf("a part with other bytes: %v, said %+v", err, b.said)
|
||||
}
|
||||
// The same version published with other content is refused, never uploaded over.
|
||||
// The same version published with other content is answered other-bytes, never uploaded over (H-A-729).
|
||||
b = newBed(true)
|
||||
b.forge.files[NpmSeat] = map[string][]byte{"x@0.1.0": []byte("first")}
|
||||
if _, err := b.h.Publish(NpmSeat, nodeBuild, pub("x", "0.1.0", file)); err != nil || len(b.said) != 1 || b.said[0].event != EventRefused {
|
||||
t.Errorf("a published version with other content: %v, said %+v", err, b.said)
|
||||
if a, err := b.h.Publish(NpmSeat, nodeBuild, pub("x", "0.1.0", file)); err != nil || a.OtherBytes == nil || a.OtherBytes.Digest != digest([]byte("first")) || len(b.said) != 0 || string(b.forge.files[NpmSeat]["x@0.1.0"]) != "first" {
|
||||
t.Errorf("a published version with other content: %+v, %v, said %+v", a, err, b.said)
|
||||
}
|
||||
})
|
||||
t.Run("the builder removes a tagged version; one already gone is said removed all the same", func(t *testing.T) {
|
||||
|
||||
+12
-12
@@ -5,11 +5,11 @@
|
||||
// `already-merged` with its commit), and no run at the head's build-input fingerprint failed a `required` step (the
|
||||
// module's own `failed-steps`). No branch protection is judged (ADR 0682 §13). When one member is refused, none is merged
|
||||
// and the answer names every refused member and why; else the members are merged in the order the call names them. The
|
||||
// verb answers once, at the call's end: `call` and each member's outcome. A member whose repository has no watched branch
|
||||
// (no entry, or an empty set, in the registrations' watched branches) is the forge's business alone (H2 H-A-471 and its
|
||||
// addendum): judged against nothing of the module graph, merged plainly in the order named, answered and kept merged with
|
||||
// the note no delivery, and left out of merge-called, so it starts no delivery. A watched repository whose base is no
|
||||
// watched branch stays refused. A member is merged plainly only from a view of the watched branches read since the last
|
||||
// verb answers once, at the call's end: `call` and each member's outcome. A member whose base is no watched branch,
|
||||
// whatever its repository (no entry, or an empty set, in the registrations' watched branches, or a set that does not
|
||||
// hold the base), is the forge's business alone (H2 H-A-471 and its addendum, H-A-704): judged against nothing of the
|
||||
// module graph, merged plainly in the order named, answered and kept merged with the note no delivery, and left out of
|
||||
// merge-called, so it starts no delivery. A member is merged plainly only from a view of the watched branches read since the last
|
||||
// registration-changed heard (the second addendum): while the view is unread or stale, every member is refused, never
|
||||
// merged with the note.
|
||||
|
||||
@@ -57,14 +57,14 @@ export interface Member {
|
||||
state: MemberOutcome["state"];
|
||||
commit?: string;
|
||||
why?: string;
|
||||
/** Set on a member merged plainly, its repository having no watched branch (H-A-471). */
|
||||
/** Set on a member merged plainly, its base being no watched branch (H-A-471, H-A-704). */
|
||||
note?: string;
|
||||
/** Its repository has no watched branch: judged against nothing of the module graph (H-A-471). */
|
||||
/** Its base is no watched branch: judged against nothing of the module graph (H-A-471, H-A-704). */
|
||||
plain?: boolean;
|
||||
}
|
||||
|
||||
/** The note of a member merged plainly: it starts no delivery (H-A-471). */
|
||||
export const NO_DELIVERY = "no delivery: the repository has no watched branch";
|
||||
/** The note of a member merged plainly: it starts no delivery (H-A-471, H-A-704; its words H-A-717, DQ-49). */
|
||||
export const NO_DELIVERY = "no delivery: its base is no watched branch";
|
||||
|
||||
/** Why every member is refused while the watched branches are unread or stale (H-A-471, second addendum). */
|
||||
export const NOT_READ = "the watched branches are not read yet";
|
||||
@@ -107,12 +107,12 @@ async function judgeMember(forge: CallForge, deps: CallDeps, watched: ReadonlyMa
|
||||
return `head-moved: its head is ${String(pull.head_sha).slice(0, 12)}, not the ${m.head.slice(0, 12)} the caller names`;
|
||||
}
|
||||
const branches = watched.get(m.repository);
|
||||
// A repository of no module: no build-input fingerprint and no required step judge it (H-A-471).
|
||||
if (!branches || branches.size === 0) {
|
||||
// A base no registration watches, whatever the repository: no build-input fingerprint and no required step judge it
|
||||
// (H-A-471, H-A-704).
|
||||
if (!branches || !branches.has(m.branch)) {
|
||||
m.plain = true;
|
||||
return "";
|
||||
}
|
||||
if (!branches.has(m.branch)) return `its base ${m.branch} is no watched branch`;
|
||||
const failed = await deps.judge(m.head);
|
||||
if (failed) {
|
||||
return `the ${failed.step} step of ${failed.module} failed in run ${failed.run} at its build-input fingerprint ${failed.fingerprint}`;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"check-needs": [
|
||||
"node-build-node"
|
||||
],
|
||||
"runs-as": "gitea",
|
||||
"requires": [
|
||||
"postgres-database",
|
||||
"route",
|
||||
@@ -39,6 +40,10 @@
|
||||
"admin": "${dir:state}/admin.secret"
|
||||
}
|
||||
},
|
||||
"own-secrets": {
|
||||
"broker": "${dir:state}/broker"
|
||||
},
|
||||
"secrets-owner": "gitea",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
@@ -271,6 +276,16 @@
|
||||
}
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "account",
|
||||
"type": "user",
|
||||
"name": "gitea",
|
||||
"shell": "/usr/bin/nologin",
|
||||
"home": "/var/lib/gitea",
|
||||
"groups": [
|
||||
"docker"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
@@ -544,9 +559,7 @@
|
||||
"env": {
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
||||
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
||||
"MESH_GITEA_PACKAGES_USER": "mesh-packages",
|
||||
"MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token",
|
||||
"MESH_NPM_OWNER": "novox"
|
||||
}
|
||||
},
|
||||
@@ -563,7 +576,6 @@
|
||||
"env": {
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
||||
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
||||
"MESH_GITEA_PATCH_DIR": "${dir:forge-patches}"
|
||||
}
|
||||
},
|
||||
@@ -662,6 +674,10 @@
|
||||
"name": "transfers",
|
||||
"max-mib": 8
|
||||
},
|
||||
{
|
||||
"name": "fingerprints",
|
||||
"max-mib": 16
|
||||
},
|
||||
{
|
||||
"name": "idle",
|
||||
"key-ttl": true,
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { adminFromEnv, MintedToken } from "./token.js";
|
||||
import { TOOLS_ORG, type ToolsForge } from "./tools-account.js";
|
||||
import { TOOLS_ACCOUNT, TOOLS_ORG, type ToolsForge } from "./tools-account.js";
|
||||
|
||||
/** The account the package seats write as (internal/forgehttp PackagesAccount). */
|
||||
export const PACKAGES_ACCOUNT = "mesh-packages";
|
||||
@@ -52,6 +52,7 @@ export function packagesToken(url: string, env: NodeJS.ProcessEnv = process.env,
|
||||
const base = over.vault && over.lease ? {} : MintedToken.settingsFromEnv(env);
|
||||
return new MintedToken({
|
||||
...base, ...over, url, admin, passwordFile, account, oldName: PACKAGES_TOKEN_NAME, scopes: PACKAGES_TOKEN_SCOPES, log,
|
||||
tokenFile: "packages-token", listAccounts: async () => [account, env.MESH_GITEA_TOOLS_USER || TOOLS_ACCOUNT],
|
||||
setUp: async (password) => {
|
||||
const { GiteaAdmin } = await import("./client.js");
|
||||
await setUpPackagesAccount(new GiteaAdmin(url, admin, password), account, () => randomBytes(24).toString("base64url"));
|
||||
|
||||
@@ -91,9 +91,9 @@ test("a call says one merge-called of what landed; none for a call that landed n
|
||||
assert.deepEqual(said.map((s) => s.body.members.map((x: any) => x.number)), [[1, 2]]);
|
||||
assert.equal(said[0].body.refused, undefined, "a member not merged after a stop is no refused member");
|
||||
assert.deepEqual(await sayUnsaid(calls, say), [], "said once");
|
||||
// A member merged plainly, its repository having no watched branch, starts no delivery: the start's re-say leaves it
|
||||
// A member merged plainly, its base being no watched branch, starts no delivery: the start's re-say leaves it
|
||||
// out by the kept note (design 47 H2 H-A-471 addendum (2)), and a call of such members alone says none.
|
||||
const noted = { ...m(4, "merged"), repository: "novox/hq", note: "no delivery: the repository has no watched branch" };
|
||||
const noted = { ...m(4, "merged"), repository: "novox/hq", note: "no delivery: its base is no watched branch" };
|
||||
await calls.put("00000000000000dd", { by: "lead@shanks", account: "x", at: "2026-11-20T03:02:00Z", members: [noted, m(5, "merged")], said: false } as any);
|
||||
await calls.put("00000000000000ee", { by: "lead@shanks", account: "x", at: "2026-11-20T03:03:00Z", members: [noted], said: false } as any);
|
||||
said.length = 0;
|
||||
|
||||
@@ -28,6 +28,11 @@ test("a note line is appended once, as the forge's user, in its own repository",
|
||||
{ added: true, lines: 2 });
|
||||
const append = calls.find((c) => c.includes("append"))!;
|
||||
assert.deepEqual(append.slice(0, 7), ["docker", "exec", "-u", "git", "gitea", "git", "--git-dir"]);
|
||||
// The note is run by docker, so the account the module runs as is in the group docker (H-A-543, H-A-545).
|
||||
const { readFileSync } = await import("node:fs");
|
||||
const manifest = JSON.parse(readFileSync(new URL("../module.json", import.meta.url), "utf8"));
|
||||
const account = manifest.resources.find((r: { type: string; name: string }) => r.type === "user" && r.name === manifest["runs-as"]);
|
||||
assert.ok(account?.groups?.includes("docker"), `the account ${manifest["runs-as"]} the module runs as is not in the group docker`);
|
||||
assert.equal(append[7], "/data/git/repositories/novox/mesh-catalog.git");
|
||||
assert.ok(append.includes("--ref=mesh-plan"));
|
||||
assert.throws(() => noteArgs("gitea", "novox", "x; rm -rf /", sha, "mesh-plan"), /not a repository/);
|
||||
|
||||
@@ -66,7 +66,6 @@ test("a member refused at judging merges none and names every refused member and
|
||||
{ name: "the second member's head moved", set: (p) => { p["novox/lib#9"].head = MOVED; }, why: /head-moved: its head is cccccccccccc, not the bbbbbbbbbbbb/ },
|
||||
{ name: "already merged", set: (p) => { Object.assign(p["novox/lib#9"], { merged: true, merge: "e".repeat(40) }); }, why: /already-merged: .* as e{40}/ },
|
||||
{ name: "closed", set: (p) => { p["novox/lib#9"].state = "closed"; }, why: /is closed/ },
|
||||
{ name: "a base no registration watches", set: (p) => { p["novox/lib#9"].base = "feat/x"; }, why: /its base feat\/x is no watched branch/ },
|
||||
{ name: "a required step failed at its head's fingerprint",
|
||||
set: () => {}, over: { judge: async (h: string) => (h === B ? { run: "main.7", module: "lib", step: "unit", fingerprint: "fp" } : null) },
|
||||
why: /the unit step of lib failed in run main\.7 at its build-input fingerprint fp/ },
|
||||
@@ -83,20 +82,22 @@ test("a member refused at judging merges none and names every refused member and
|
||||
}
|
||||
});
|
||||
|
||||
// **A repository of no module is merged plainly** (design 47 H2 H-A-471 and its addendum): a member whose repository has
|
||||
// no watched branch (no entry, or an empty set, in the registrations' watched branches) is judged against nothing of the
|
||||
// **A base no registration watches is merged plainly** (design 47 H2 H-A-471 and its addendum, H-A-704): a member whose base
|
||||
// is no watched branch, whatever its repository (no entry, an empty set, or a set that does not hold the base, in the
|
||||
// registrations' watched branches), is judged against nothing of the
|
||||
// module graph (no failed required step), merged in the order named, answered merged with the note no delivery, and left
|
||||
// out of merge-called; the watched members of the same call are judged and delivered as any call's. A watched
|
||||
// repository whose base is unwatched stays refused (the row above).
|
||||
test("a member of a repository with no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => {
|
||||
const NOTE = "no delivery: the repository has no watched branch";
|
||||
const rows: { name: string; watched: Map<string, Set<string>> }[] = [
|
||||
{ name: "no entry", watched: new Map([["novox/app", new Set(["main"])]]) },
|
||||
{ name: "an empty set", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set<string>()]]) },
|
||||
// out of merge-called; the watched members of the same call are judged and delivered as any call's.
|
||||
test("a member whose base is no watched branch is merged plainly, noted no delivery, and left out of merge-called", async () => {
|
||||
const NOTE = "no delivery: its base is no watched branch";
|
||||
const rows: { name: string; base: string; watched: Map<string, Set<string>> }[] = [
|
||||
{ name: "no entry", base: "main", watched: new Map([["novox/app", new Set(["main"])]]) },
|
||||
{ name: "an empty set", base: "main", watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set<string>()]]) },
|
||||
{ name: "a watched repository's pull request into a branch it does not watch", base: "feat/x",
|
||||
watched: new Map([["novox/app", new Set(["main"])], ["novox/hq", new Set(["main"])]]) },
|
||||
];
|
||||
for (const r of rows) {
|
||||
const pulls = open();
|
||||
pulls["novox/hq#799"] = { base: "main", head: B, state: "open", merged: false };
|
||||
pulls["novox/hq#799"] = { base: r.base, head: B, state: "open", merged: false };
|
||||
const f = forge(pulls);
|
||||
const judged: string[] = [];
|
||||
const said: any[] = [];
|
||||
@@ -109,7 +110,7 @@ test("a member of a repository with no watched branch is merged plainly, noted n
|
||||
assert.equal(got.members[0].state, "judged", r.name);
|
||||
assert.equal(got.members[1].state, "refused", r.name);
|
||||
// Without the failed step the call lands both: the unwatched noted, merge-called naming only the watched.
|
||||
const f2 = forge(Object.assign(open(), { "novox/hq#799": { base: "main", head: B, state: "open", merged: false } }));
|
||||
const f2 = forge(Object.assign(open(), { "novox/hq#799": { base: r.base, head: B, state: "open", merged: false } }));
|
||||
said.length = 0;
|
||||
const landed = await call(f2, mixed, { watched: () => r.watched, say: async (_s: string, body: unknown) => { said.push(body); } });
|
||||
assert.deepEqual(f2.merges, ["novox/hq#799", "novox/app#5"], `${r.name}: merged in the order named`);
|
||||
@@ -117,7 +118,7 @@ test("a member of a repository with no watched branch is merged plainly, noted n
|
||||
[["novox/hq", "merged", NOTE, undefined], ["novox/app", "merged", undefined, undefined]], r.name);
|
||||
assert.deepEqual(said.map((b) => b.members.map((m: any) => m.repository)), [["novox/app"]], `${r.name}: merge-called leaves it out`);
|
||||
// A call of unwatched members alone merges and starts no delivery: no merge-called.
|
||||
const f3 = forge({ "novox/hq#799": { base: "main", head: B, state: "open", merged: false } });
|
||||
const f3 = forge({ "novox/hq#799": { base: r.base, head: B, state: "open", merged: false } });
|
||||
said.length = 0;
|
||||
const alone = await call(f3, { by: "lead@shanks", pulls: [mixed.pulls[0]] }, { watched: () => r.watched,
|
||||
say: async (_s: string, body: unknown) => { said.push(body); } });
|
||||
@@ -170,7 +171,7 @@ test("a member is merged plainly only from a watched-branches view read since th
|
||||
const f3 = forge(pulls());
|
||||
const landed = await call(f3, hq, { watched: view });
|
||||
assert.deepEqual([f3.merges, landed.members.map((m: any) => [m.state, m.note])],
|
||||
[["novox/hq#799", "novox/app#5"], [["merged", "no delivery: the repository has no watched branch"], ["merged", undefined]]]);
|
||||
[["novox/hq#799", "novox/app#5"], [["merged", "no delivery: its base is no watched branch"], ["merged", undefined]]]);
|
||||
});
|
||||
|
||||
test("a call is refused whole with no proved caller, no by, no registration or no pull request", async () => {
|
||||
|
||||
@@ -10,12 +10,13 @@
|
||||
import { test, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { mkdtemp, stat, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readdir, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { collectTools } from "@novox/mesh-sdk/tools";
|
||||
import { AdminRefused, MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus, vaultValue, type MintedTokenOptions } from "../dist/token.js";
|
||||
import { TOKEN_FILE_UNREVOKED, passOver, type ForgeTokens, type ListedToken } from "../dist/tokenfiles.js";
|
||||
import { tokenLeaseTool } from "../dist/tools/tokenlease.js";
|
||||
import { fakeBus } from "./fakebus.ts";
|
||||
import { GiteaClient } from "../dist/client.js";
|
||||
@@ -38,7 +39,7 @@ interface Forge {
|
||||
/** How each DELETE named its token: "id" or "name". */
|
||||
deletedBy: string[];
|
||||
/** Plant a token by name, beside any other of the same name, as a raced mint would. */
|
||||
plant(name: string): void;
|
||||
plant(name: string, sha1?: string, scopes?: string[]): void;
|
||||
scopesOf: Map<string, string[]>;
|
||||
admins: Map<string, string>;
|
||||
pullState: string;
|
||||
@@ -119,7 +120,7 @@ function fakeForge(): Promise<Forge> {
|
||||
const all = listed();
|
||||
res.setHeader("X-Total-Count", String(all.length));
|
||||
return json(res, 200, all.slice((page - 1) * limit, page * limit)
|
||||
.map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: [] })));
|
||||
.map((t) => ({ id: t.id, name: t.name, sha1: "", token_last_eight: t.sha1.slice(-8), scopes: forge.scopesOf.get(t.sha1) ?? [] })));
|
||||
}
|
||||
if (req.method === "DELETE" && tokens[2]) {
|
||||
// gitea: "identified by ID and if not available by name" — and a name held twice is refused.
|
||||
@@ -242,8 +243,10 @@ function fakeForge(): Promise<Forge> {
|
||||
tokens: forge.tokens,
|
||||
twins: forge.twins,
|
||||
deletedBy: forge.deletedBy,
|
||||
plant: (name: string) => {
|
||||
const sha1 = `planted-${++forge.nextId}`;
|
||||
plant: (name: string, value?: string, scopes?: string[]) => {
|
||||
const sha1 = value ?? `planted-${++forge.nextId}`;
|
||||
if (value) ++forge.nextId;
|
||||
if (scopes) forge.scopesOf.set(sha1, scopes);
|
||||
forge.ids.set(sha1, forge.nextId);
|
||||
if (forge.tokens.has(name)) forge.twins.push({ id: forge.nextId, name, sha1 });
|
||||
else forge.tokens.set(name, sha1);
|
||||
@@ -665,3 +668,95 @@ test("a pull request can be closed, read and cleaned up through the tools", asyn
|
||||
await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" });
|
||||
assert.equal(forge.branchDeleted, true);
|
||||
});
|
||||
|
||||
// ---- The token files an earlier build kept (H-A-575, H-A-602, H-A-642, H-A-699): ended at a start, never read. ----
|
||||
|
||||
const HEX = "0123456789abcdef0123456789abcdef01234567";
|
||||
const SCOPES = ["write:repository", "read:user"];
|
||||
const SCOPES_LINE = "read:user,write:repository for mesh-tools";
|
||||
|
||||
/** The state directory of a start, with the files an earlier build left: the token, its scopes, and what `extra` adds. */
|
||||
async function leftFiles(env: NodeJS.ProcessEnv, files: Record<string, string>): Promise<void> {
|
||||
const dir = env.MESH_GITEA_STATE_DIR!;
|
||||
await mkdir(dir, { recursive: true });
|
||||
for (const [name, text] of Object.entries(files)) await writeFile(join(dir, name), text);
|
||||
|
||||
}
|
||||
const left = async (env: NodeJS.ProcessEnv) => (await readdir(env.MESH_GITEA_STATE_DIR!).catch(() => [] as string[])).filter((f) => f.includes("token")).sort();
|
||||
/** The findings a start wrote, by key. */
|
||||
const sink = () => { const held = new Map<string, any>(); return { held, put: async (k: string, v: unknown) => { held.set(k, v); }, delete: async (k: string) => { held.delete(k); } }; };
|
||||
|
||||
test("a start ends the token files: the lists are read before the first mint drops the old name, the pair is revoked by its id and deleted, and a cut .tmp goes unrevoked (H-A-575, H-A-699)", async () => {
|
||||
const { env, bus, logs } = await delivered(forge);
|
||||
forge.tokens.clear();
|
||||
forge.plant(TOKEN_NAME, HEX, SCOPES);
|
||||
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n", "token.tmp": "cut-off", "token.scopes.tmp": SCOPES_LINE + "\n" });
|
||||
const findings = sink();
|
||||
ORDER.length = 0;
|
||||
forge.deletedBy.length = 0;
|
||||
|
||||
await new GiteaClient(env.MESH_GITEA_URL!, source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", findings,
|
||||
listAccounts: async () => ["mesh-tools", "mesh-packages"] })).listRepos();
|
||||
|
||||
// The planted token was listed before the first mint's drop deleted it, so the file's token matched and its revocation found it gone.
|
||||
assert.deepEqual(await left(env), [], logs.join("\n"));
|
||||
assert.equal(findings.held.size, 0);
|
||||
assert.deepEqual(ORDER, [`own-put ${VAULT} 1`, `delete ${TOKEN_NAME}`], "the own-put, then the drop of the old name");
|
||||
assert.ok(logs.some((l) => l.includes("token.tmp") && l.includes("no whole token")), logs.join("\n"));
|
||||
assert.ok(logs.every((l) => !l.includes(HEX) && !l.includes(vaulted(bus))), "no line names a token");
|
||||
});
|
||||
|
||||
test("a token file stays when the vault refuses the own-put, and when the forge refuses the revocation or matches nothing: said, written as a finding, cleared once the pair goes", async () => {
|
||||
const { env, logs } = await delivered(forge);
|
||||
forge.tokens.clear();
|
||||
forge.plant(TOKEN_NAME, HEX, SCOPES);
|
||||
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" });
|
||||
const refusing = source(env, logs, { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token",
|
||||
vault: { get: vaultOverBus().get, put: async () => { throw new Error("the vault is away"); } } });
|
||||
await assert.rejects(new GiteaClient(env.MESH_GITEA_URL!, refusing).listRepos(), /the vault is away/);
|
||||
assert.deepEqual(await left(env), ["token", "token.scopes"], "an own-put refused leaves the files and their token");
|
||||
|
||||
// The forge refuses the revocation: the pair stays and the finding names the answer; the next start's success clears it.
|
||||
const findings = sink();
|
||||
const listed: ListedToken[] = [{ id: 7, token_last_eight: HEX.slice(-8), scopes: SCOPES }];
|
||||
let answer: string | null = "403 forbidden";
|
||||
const forgeTokens: ForgeTokens = { list: async () => listed, revoke: async () => answer };
|
||||
const run = (lists: Map<string, readonly ListedToken[]>) =>
|
||||
passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "token", lists, forge: forgeTokens, findings, log: (l) => logs.push(l) });
|
||||
await run(new Map([["mesh-tools", listed]]));
|
||||
const key = [...findings.held.keys()];
|
||||
assert.equal(key.length, 1);
|
||||
assert.match(key[0], new RegExp(`token\\.${TOKEN_FILE_UNREVOKED}$`));
|
||||
assert.match(findings.held.get(key[0]).summary, /403 forbidden/);
|
||||
assert.deepEqual(await left(env), ["token", "token.scopes"]);
|
||||
answer = null;
|
||||
await run(new Map([["mesh-tools", listed]]));
|
||||
assert.deepEqual([await left(env), findings.held.size], [[], 0]);
|
||||
|
||||
// No token at the forge matches the last eight characters and the scopes: the pair stays and says so.
|
||||
await leftFiles(env, { "packages-token": HEX + "\n", "packages-token.scopes": "write:package for mesh-packages\n" });
|
||||
await passOver({ dir: env.MESH_GITEA_STATE_DIR!, base: "packages-token", lists: new Map([["mesh-packages", listed]]), forge: forgeTokens,
|
||||
findings, log: (l) => logs.push(l) });
|
||||
assert.deepEqual(await left(env), ["packages-token", "packages-token.scopes"]);
|
||||
assert.equal(findings.held.size, 1);
|
||||
});
|
||||
|
||||
test("a start with the vault holding a token and a file left runs the pass; with no file it lists nothing at the forge", async () => {
|
||||
const { env, logs } = await delivered(forge);
|
||||
forge.tokens.clear();
|
||||
await minted(env, logs).listRepos();
|
||||
forge.plant("kept-by-the-earlier-build", HEX, SCOPES);
|
||||
await leftFiles(env, { token: HEX + "\n", "token.scopes": SCOPES_LINE + "\n" });
|
||||
const again: string[] = [];
|
||||
const options = { stateDir: env.MESH_GITEA_STATE_DIR, tokenFile: "token", listAccounts: async () => ["mesh-tools"] };
|
||||
|
||||
await new GiteaClient(env.MESH_GITEA_URL!, source(env, again, options)).listRepos();
|
||||
|
||||
assert.ok(again.some((l) => l.startsWith("reusing the token the vault keeps")), again.join("\n"));
|
||||
assert.deepEqual(await left(env), []);
|
||||
assert.equal(forge.tokens.has("kept-by-the-earlier-build"), false, "its token is revoked at the forge");
|
||||
const quiet: string[] = [];
|
||||
const failing = { ...options, listAccounts: async () => { throw new Error("no lists without files"); } };
|
||||
await new GiteaClient(env.MESH_GITEA_URL!, source(env, quiet, failing)).listRepos();
|
||||
assert.ok(quiet.every((l) => !l.includes("no lists")), quiet.join("\n"));
|
||||
});
|
||||
|
||||
@@ -374,14 +374,9 @@ test("the manifest hands the tools their account, and the Go forge bundle holds
|
||||
const packages = manifest.build.artifacts.find((a: any) => a.name === "package-registry");
|
||||
assert.equal(packages.env.MESH_GITEA_PACKAGES_USER, PACKAGES_ACCOUNT);
|
||||
assert.equal(packages.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined);
|
||||
// H-A-564: until gitea runs as its own account, the Go bundles are handed the token files the TypeScript bundle keeps
|
||||
// under its state directory, read when the vault refuses the caller's account; no other artifact is.
|
||||
const files: Record<string, [string | undefined, string | undefined]> = {
|
||||
forge: ["${dir:runtime-state}/token", undefined],
|
||||
"package-registry": ["${dir:runtime-state}/token", "${dir:runtime-state}/packages-token"],
|
||||
};
|
||||
// H-A-575: the vault alone hands a token: no artifact is given a token file.
|
||||
for (const a of manifest.build.artifacts) {
|
||||
assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], files[a.name] ?? [undefined, undefined],
|
||||
assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], [undefined, undefined],
|
||||
`${a.name}'s token files`);
|
||||
}
|
||||
assert.ok(manifest.invokes.includes("seat:mesh-vault.own-put") && manifest.invokes.includes("seat:mesh-vault.get"), manifest.invokes.join(","));
|
||||
|
||||
+81
-5
@@ -47,6 +47,7 @@ import { state, type State } from "@novox/mesh-sdk/state";
|
||||
import { setUpToolsAccount, TOOLS_ACCOUNT, type AdminCall } from "./tools-account.js";
|
||||
import { keepMainRules } from "./mainrules.js";
|
||||
import { durationMs } from "./taken.js";
|
||||
import { passOver, readLists, remaining, type FindingSink, type ForgeTokens, type Lists } from "./tokenfiles.js";
|
||||
|
||||
/** The tools' token's old fixed name in the forge's list, the one the admin's own token carried too (ADR 0365 §2). */
|
||||
export const TOKEN_NAME = "mesh-tools";
|
||||
@@ -283,8 +284,16 @@ export interface MintedTokenOptions {
|
||||
readonly leaseMs?: number;
|
||||
/** Who holds the lease when this process does: the node and the process. */
|
||||
readonly holder?: string;
|
||||
/** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered. */
|
||||
/** The module's runtime state directory, where a retirement of the admin's old token that failed is remembered, and
|
||||
* where an earlier build kept the token files (tokenfiles.ts). */
|
||||
readonly stateDir?: string;
|
||||
/** The name of the token file an earlier build kept for this account (`token`, `packages-token`): at each start while
|
||||
* it remains, it is ended once this start's token is held (H-A-575, H-A-699). */
|
||||
readonly tokenFile?: string;
|
||||
/** The accounts whose tokens at the forge are listed to find the files' tokens, besides the admin's (H-A-699 (2)). */
|
||||
readonly listAccounts?: () => Promise<readonly string[]>;
|
||||
/** The module's state `findings`, where a token file that stays is written (token-file-unrevoked). */
|
||||
readonly findings?: FindingSink;
|
||||
readonly now?: () => Date;
|
||||
readonly log?: (line: string) => void;
|
||||
readonly fetch?: typeof fetch;
|
||||
@@ -293,6 +302,9 @@ export interface MintedTokenOptions {
|
||||
/** The token the module mints for itself, kept in the vault and renewed when the forge rejects it. */
|
||||
export class MintedToken implements TokenSource {
|
||||
private held: VaultToken | null = null;
|
||||
/** The forge's token lists, read once at this start before it deletes any token there: null when they could not be read. */
|
||||
private fileLists: Lists | null | undefined;
|
||||
private filesPassed = false;
|
||||
private inflight: Promise<string> | null = null;
|
||||
private readonly scopes: readonly string[];
|
||||
private readonly ttlMs: number;
|
||||
@@ -330,7 +342,11 @@ export class MintedToken implements TokenSource {
|
||||
if (shared) return shared;
|
||||
if (account === admin) throw new Error(`MESH_GITEA_TOOLS_USER names the admin account "${admin}"; the tools act as an account of their own (novox/hq ADR 0365)`);
|
||||
const source = new MintedToken({
|
||||
...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME,
|
||||
...MintedToken.settingsFromEnv(env), url, admin, passwordFile, account, oldName: TOKEN_NAME, tokenFile: "token",
|
||||
listAccounts: async () => {
|
||||
const { PACKAGES_ACCOUNT } = await import("./packages-account.js");
|
||||
return [account, env.MESH_GITEA_PACKAGES_USER || PACKAGES_ACCOUNT];
|
||||
},
|
||||
// GiteaAdmin is loaded when first used: client.ts imports this file.
|
||||
setUp: async (password) => {
|
||||
const { GiteaAdmin } = await import("./client.js");
|
||||
@@ -344,12 +360,12 @@ export class MintedToken implements TokenSource {
|
||||
private static readonly shared = new Map<string, MintedToken>();
|
||||
|
||||
/** What every account's source takes from the environment: the vault and lease over the bus, the two settings. */
|
||||
static settingsFromEnv(env: NodeJS.ProcessEnv): Pick<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir"> {
|
||||
static settingsFromEnv(env: NodeJS.ProcessEnv): Pick<MintedTokenOptions, "vault" | "lease" | "ttlMs" | "leaseMs" | "stateDir" | "findings"> {
|
||||
const log = (line: string) => console.log(`[gitea] ${line}`);
|
||||
return {
|
||||
vault: sharedVault(), lease: sharedLease(),
|
||||
ttlMs: settingMs(env, "token-ttl", TOKEN_TTL_DEFAULT, log), leaseMs: settingMs(env, "mint-lease", MINT_LEASE_DEFAULT, log),
|
||||
stateDir: env.MESH_GITEA_STATE_DIR || undefined,
|
||||
stateDir: env.MESH_GITEA_STATE_DIR || undefined, findings: state<unknown>("findings"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -368,6 +384,7 @@ export class MintedToken implements TokenSource {
|
||||
if (this.retireFile && existsSync(this.retireFile)) await this.retireAdmin().catch((err) => this.log(`${err}`));
|
||||
}
|
||||
this.held = kept;
|
||||
await this.endTokenFiles();
|
||||
return kept.token;
|
||||
}
|
||||
|
||||
@@ -403,7 +420,10 @@ export class MintedToken implements TokenSource {
|
||||
private mint(why: string, stale: string | null): Promise<string> {
|
||||
if (this.inflight === null) {
|
||||
this.log(why);
|
||||
this.inflight = this.leased(stale).finally(() => {
|
||||
this.inflight = this.leased(stale).then(async (token) => {
|
||||
await this.endTokenFiles();
|
||||
return token;
|
||||
}).finally(() => {
|
||||
this.inflight = null;
|
||||
});
|
||||
}
|
||||
@@ -438,6 +458,59 @@ export class MintedToken implements TokenSource {
|
||||
}
|
||||
}
|
||||
|
||||
/** The forge's token lists, once a start, when a token file of this account remains; a read that fails is said and
|
||||
* leaves every file standing. */
|
||||
private async readFileLists(admin: AdminCall = this.adminCall()): Promise<void> {
|
||||
if (this.fileLists !== undefined || !this.opts.stateDir || !this.opts.tokenFile) return;
|
||||
if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return;
|
||||
try {
|
||||
const accounts = [...(await this.opts.listAccounts?.() ?? [this.opts.account]), this.opts.admin];
|
||||
this.fileLists = await readLists(this.forgeTokens(admin), accounts);
|
||||
} catch (err) {
|
||||
this.fileLists = null;
|
||||
this.log(`the forge's token lists could not be read, so the token files an earlier build kept stay: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
private forgeTokens(admin: AdminCall): ForgeTokens {
|
||||
return {
|
||||
list: async (account) => {
|
||||
const out: { id: number; token_last_eight: string; scopes: string[] }[] = [];
|
||||
for (let page = 1; page <= 100; page++) {
|
||||
const listed = await admin("GET", `/users/${encodeURIComponent(account)}/tokens?page=${page}&limit=50`);
|
||||
if (listed.status !== 200 || !Array.isArray(listed.body)) throw new Error(`Gitea GET /users/${account}/tokens: ${listed.status} ${detail(listed.body)}`);
|
||||
if (listed.body.length === 0) break;
|
||||
for (const t of listed.body) {
|
||||
if (typeof t?.id === "number" && typeof t?.token_last_eight === "string") {
|
||||
out.push({ id: t.id, token_last_eight: t.token_last_eight, scopes: Array.isArray(t.scopes) ? t.scopes.map(String) : [] });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
},
|
||||
revoke: async (account, id) => {
|
||||
const res = await admin("DELETE", `/users/${encodeURIComponent(account)}/tokens/${id}`);
|
||||
return res.status === 204 || res.status === 404 ? null : `${res.status} ${detail(res.body)}`;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The earlier build's token files end once this start's token is held, at the first time in this process (H-A-575,
|
||||
* H-A-602, H-A-699): never a failure of the token. */
|
||||
private async endTokenFiles(): Promise<void> {
|
||||
if (this.filesPassed || !this.opts.stateDir || !this.opts.tokenFile) return;
|
||||
this.filesPassed = true;
|
||||
if (remaining(this.opts.stateDir, this.opts.tokenFile).length === 0) return;
|
||||
try {
|
||||
await this.readFileLists();
|
||||
if (!this.fileLists) return;
|
||||
await passOver({ dir: this.opts.stateDir, base: this.opts.tokenFile, lists: this.fileLists, forge: this.forgeTokens(this.adminCall()),
|
||||
findings: this.opts.findings, log: (l) => this.log(l), now: this.now });
|
||||
} catch (err) {
|
||||
this.log(`the token files an earlier build kept could not be ended: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** The admin password, read now. */
|
||||
private password(): string {
|
||||
try {
|
||||
@@ -528,6 +601,9 @@ export class MintedToken implements TokenSource {
|
||||
if (kept !== generation) this.log(`the vault kept ${vaultName(account)} at generation ${kept}, the forge names it ${name}`);
|
||||
this.held = { token, scopes: this.scopes, generation: kept, changedAt: this.now().toISOString() };
|
||||
this.log(`minted ${name} for "${account}" (${this.scopes.join(", ")}), kept in the vault as ${vaultName(account)}`);
|
||||
// The lists are read now, after the own-put and before the drop of the old fixed name below: the earlier build's
|
||||
// token files hold tokens of that name (H-A-699 (2)).
|
||||
await this.readFileLists(admin);
|
||||
|
||||
// Only now, with the new token kept, does the one it replaces go.
|
||||
const gone = replaced ? mintName(account, replaced.generation) : this.opts.oldName;
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// The token files an earlier build kept under the module's state directory, and their end (design 47 H2 H-A-575,
|
||||
// H-A-602, H-A-642, H-A-699). An earlier build wrote each account's token to `token` (the tools') or `packages-token`
|
||||
// (the packages account's), the scopes it was minted with beside it in `<file>.scopes` ("<sorted scopes, comma-joined>",
|
||||
// then " for <account>" for an account that is not the admin), each written through a `.tmp` and renamed. The vault
|
||||
// keeps the tokens now, so no build writes these files and this pass ends them:
|
||||
//
|
||||
// - it runs at each start of the process while any of the files remains, once this start's token is held;
|
||||
// - a file's token is found at the forge by the last eight characters of the token and the scopes its `.scopes` names,
|
||||
// in the lists read before this start deleted any token there; a matched pair is revoked at the forge by its id,
|
||||
// then both files are deleted; a `.tmp` goes with its pair, and one holding no whole token (forty hexadecimal
|
||||
// characters) is deleted with no revocation, since it names no token at the forge;
|
||||
// - a pair with no match, and a pair whose revocation the forge refused, stay, said in the journal and written as the
|
||||
// finding `token-file-unrevoked` (id the file) in the module's `findings`, cleared when the pair is deleted.
|
||||
|
||||
import { existsSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { findingKey, findingValue } from "./findings.js";
|
||||
|
||||
export const TOKEN_FILE_UNREVOKED = "token-file-unrevoked";
|
||||
|
||||
/** A token as the forge lists it: never its value, its id, its last eight characters and its scopes. */
|
||||
export interface ListedToken { readonly id: number; readonly token_last_eight: string; readonly scopes: readonly string[] }
|
||||
|
||||
/** What the pass asks of the forge, as the administrator. */
|
||||
export interface ForgeTokens {
|
||||
/** Every token an account holds. */
|
||||
list(account: string): Promise<readonly ListedToken[]>;
|
||||
/** Delete one by its id; null when it is deleted or was gone, else the forge's answer. */
|
||||
revoke(account: string, id: number): Promise<string | null>;
|
||||
}
|
||||
|
||||
/** The module's state `findings`. */
|
||||
export interface FindingSink {
|
||||
put(key: string, value: unknown): Promise<unknown>;
|
||||
delete(key: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** The tokens each account held when the lists were read. */
|
||||
export type Lists = ReadonlyMap<string, readonly ListedToken[]>;
|
||||
|
||||
/** The files one token file's name stands for: the token, its scopes, and a `.tmp` of each. */
|
||||
export const filesOf = (base: string): string[] => [base, `${base}.tmp`, `${base}.scopes`, `${base}.scopes.tmp`];
|
||||
|
||||
/** The files of `base` that remain under `dir`. */
|
||||
export const remaining = (dir: string, base: string): string[] => filesOf(base).filter((f) => existsSync(join(dir, f)));
|
||||
|
||||
/** The lists of each account, read once. */
|
||||
export async function readLists(forge: ForgeTokens, accounts: readonly string[]): Promise<Lists> {
|
||||
const lists = new Map<string, readonly ListedToken[]>();
|
||||
for (const account of accounts) if (!lists.has(account)) lists.set(account, await forge.list(account));
|
||||
return lists;
|
||||
}
|
||||
|
||||
const WHOLE = /^[0-9a-f]{40}$/;
|
||||
const sorted = (scopes: readonly string[]): string => [...scopes].sort().join(",");
|
||||
|
||||
export interface PassOptions {
|
||||
readonly dir: string;
|
||||
/** `token` or `packages-token`. */
|
||||
readonly base: string;
|
||||
readonly lists: Lists;
|
||||
readonly forge: ForgeTokens;
|
||||
readonly findings?: FindingSink;
|
||||
readonly log: (line: string) => void;
|
||||
readonly now?: () => Date;
|
||||
}
|
||||
|
||||
/** The pass over one token file's pair and their `.tmp` files. Never throws for a file it cannot end: it stays, said. */
|
||||
export async function passOver(o: PassOptions): Promise<void> {
|
||||
const at = (o.now ?? (() => new Date()))().toISOString();
|
||||
const path = (f: string) => join(o.dir, f);
|
||||
const scopesFile = [`${o.base}.scopes`, `${o.base}.scopes.tmp`].find((f) => existsSync(path(f)));
|
||||
// The scopes its `.scopes` names, without the account they are "for".
|
||||
const named = scopesFile === undefined ? null : sorted(readFileSync(path(scopesFile), "utf8").trim().split(" for ")[0].split(",").filter(Boolean));
|
||||
const clear = async (file: string) => { await o.findings?.delete(findingKey("module", file, TOKEN_FILE_UNREVOKED)); };
|
||||
const keep = async (file: string, why: string) => {
|
||||
o.log(`the token file ${file} stays: ${why}`);
|
||||
const f = findingValue({ observer: "gitea", kind: TOKEN_FILE_UNREVOKED, id: file, at,
|
||||
summary: `the token file ${file} under gitea's state directory stays: ${why}`,
|
||||
headline: `gitea could not end the token file ${file}`,
|
||||
explanation: `An earlier build of gitea kept its token in ${file}. The vault keeps the tokens now, so the file is revoked at the forge and ` +
|
||||
`deleted at each start of the module; this one stays because ${why}. It is tried again at the next start; delete the token at the forge by hand and the file with it to end it.` });
|
||||
await o.findings?.put(f.key, f.value);
|
||||
};
|
||||
for (const file of [o.base, `${o.base}.tmp`]) {
|
||||
if (!existsSync(path(file))) continue;
|
||||
const token = readFileSync(path(file), "utf8").trim().split("\n")[0].trim();
|
||||
if (!WHOLE.test(token)) {
|
||||
rmSync(path(file), { force: true });
|
||||
o.log(`deleted the token file ${file}: it holds no whole token, so nothing is revoked at the forge`);
|
||||
await clear(file);
|
||||
continue;
|
||||
}
|
||||
const last = token.slice(-8);
|
||||
let found: { account: string; id: number } | null = null;
|
||||
if (named !== null) {
|
||||
for (const [account, tokens] of o.lists) {
|
||||
const t = tokens.find((x) => x.token_last_eight === last && sorted(x.scopes) === named);
|
||||
if (t) { found = { account, id: t.id }; break; }
|
||||
}
|
||||
}
|
||||
if (found === null) {
|
||||
await keep(file, named === null ? "its scopes file is gone, so no token at the forge can be matched to it" : "no token at the forge matches its last eight characters and its scopes");
|
||||
continue;
|
||||
}
|
||||
const refused = await o.forge.revoke(found.account, found.id).catch((err) => err instanceof Error ? err.message : String(err));
|
||||
if (refused !== null) {
|
||||
await keep(file, `the forge refused to revoke its token (${refused})`);
|
||||
continue;
|
||||
}
|
||||
rmSync(path(file), { force: true });
|
||||
o.log(`revoked the token ${file} held, at the forge, and deleted ${file}`);
|
||||
await clear(file);
|
||||
}
|
||||
// The scopes hold no token: they go when no token file of the pair remains.
|
||||
if (![o.base, `${o.base}.tmp`].some((f) => existsSync(path(f)))) {
|
||||
for (const f of [`${o.base}.scopes`, `${o.base}.scopes.tmp`]) {
|
||||
if (existsSync(path(f))) { rmSync(path(f), { force: true }); o.log(`deleted ${f}`); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,7 +153,7 @@ func TestManifestRequiresForgeAccountKeepsKeysAndTakesFilesFromTemplates(t *test
|
||||
kept := map[string]any{"name": "kept-builds", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024)}}
|
||||
// steps: a step's end over what step-ended carries inline, in the steps state's objects store (design 47 G A-254, A-313;
|
||||
// H2 H-A-412 addendum), read by the verb answer.
|
||||
steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(128)}}
|
||||
steps := map[string]any{"name": "steps", "storage": "key-value", "template": "state", "options": map[string]any{"ttl-seconds": float64(172800), "objects-max-mib": float64(256), "max-mib": float64(64)}}
|
||||
// outputs: a run's test output, read by the verb output (design 47 H2 §791, §820: 1 GiB, 7 days).
|
||||
outputs := map[string]any{"name": "outputs", "storage": "object-store", "template": "objects", "options": map[string]any{"max-mib": float64(1024), "max-age-days": float64(7)}}
|
||||
detected := map[string]any{"name": "detected-steps", "storage": "key-value", "template": "state", "options": map[string]any{"history": float64(1), "max-mib": float64(8)}}
|
||||
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -46,7 +48,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) {
|
||||
// not answer as a transport fault, and a failure of the source (an unknown revision, a checksum) as none.
|
||||
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
// A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its
|
||||
// first run and 60 s after its second by default (design 47 H2 §799; H-A-390).
|
||||
// first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603).
|
||||
t.Run("again-delays is declared and read", func(t *testing.T) {
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
@@ -65,7 +67,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
||||
_ = json.Unmarshal(decl, &c)
|
||||
delay, err := steprun.AgainDelays(c.Default)
|
||||
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second {
|
||||
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second {
|
||||
t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err)
|
||||
}
|
||||
})
|
||||
@@ -121,3 +123,59 @@ func TestThePullerCountsRunsThatStarted(t *testing.T) {
|
||||
return m.Puller(nil, steprun.NewFakeAsks())
|
||||
})
|
||||
}
|
||||
|
||||
// H-A-591 (4), H-A-593 (3): the kit's `reproducible` case. The module's own build step builds a fixture of each kind it builds (a bundle with the real
|
||||
// go, an archive, a Go package) twice, in two workspace folders of other names and other file times, and the archive's digest is the same: nothing of
|
||||
// the folder, the clock or the commit is in the program or its archive.
|
||||
func TestTheBuildOfABundleIsOneDigestInAnyFolder(t *testing.T) {
|
||||
if _, err := exec.LookPath("go"); err != nil {
|
||||
t.Skip("NOT RUN: no go installed where this check runs")
|
||||
}
|
||||
fill := func(dir string) error {
|
||||
module := filepath.Join(dir, "ws1", "tree", "modules", "demo")
|
||||
files := map[string]string{
|
||||
"module.json": manifestWith(goBundle + `,{"name":"files","kind":"archive","from":"files"},` +
|
||||
`{"name":"lib","kind":"package","language":"go","paths":["lib"]}`),
|
||||
"files/a.txt": "a",
|
||||
"files/b/c.txt": "c",
|
||||
"lib/go.mod": "module git.example/demo/lib\n\ngo 1.26\n",
|
||||
"lib/lib.go": "package lib\n",
|
||||
"go.mod": "module demo\n\ngo 1.26\n",
|
||||
"cmd/demo-tools/main.go": "package main\n\nimport \"fmt\"\n\nvar meshVersion, builtFor string\n\nfunc main() { fmt.Println(\"demo\", meshVersion, builtFor) }\n",
|
||||
}
|
||||
for name, body := range files {
|
||||
if err := os.MkdirAll(filepath.Dir(filepath.Join(module, name)), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(module, name), []byte(body), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
conformance.Reproducible(t, fill, func(dir string) (map[string]string, error) {
|
||||
states := newStates()
|
||||
m := moduleWith(states, "go1.27.1")
|
||||
m.Home, m.Work, m.Cache = t.TempDir(), dir, t.TempDir()
|
||||
m.Inside = true // the compile runs as itself: the kit's folders hold the whole difference
|
||||
run := StepRunner(m.Home)
|
||||
// no go.work of a folder above the kit's (a checker's, a placement's) takes the fixture into its workspace
|
||||
m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
return run(ctx, append(env, "GOWORK=off"), name, args...)
|
||||
}
|
||||
withStore(t, m)
|
||||
out := map[string]string{}
|
||||
for _, artifact := range []string{"tools", "files", "lib"} {
|
||||
args := map[string]any{"workspace": "ws1", "module": "modules/demo", "artifact": artifact, "version": askedVersion}
|
||||
if artifact == "lib" {
|
||||
args["seat"] = GoPackageSeat
|
||||
}
|
||||
res, st := runBuildArgs(t, m, states, args)
|
||||
if st.State != sdkstep.StepPassed {
|
||||
return nil, fmt.Errorf("the build step of %s ended %s: %s", artifact, st.State, st.Reason)
|
||||
}
|
||||
out[artifact] = res.Digest
|
||||
}
|
||||
return out, nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -81,10 +81,10 @@
|
||||
},
|
||||
"again-delays": {
|
||||
"type": "string",
|
||||
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
|
||||
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
|
||||
"trusted": false,
|
||||
"runtime": true,
|
||||
"default": "15s,60s"
|
||||
"default": "15s,90s"
|
||||
},
|
||||
"prune-mark": {
|
||||
"type": "number",
|
||||
@@ -131,7 +131,7 @@
|
||||
"options": {
|
||||
"ttl-seconds": 172800,
|
||||
"objects-max-mib": 256,
|
||||
"max-mib": 128
|
||||
"max-mib": 64
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -165,7 +165,10 @@ func (m *Module) build(ctx context.Context, args map[string]any) (any, error) {
|
||||
// --network pasta: a RUN step's network is pasta's, in user space. buildah's default for a rootless RUN is a
|
||||
// netavark bridge whose nftables rules cannot be applied for an account without a user session, so every RUN
|
||||
// failed before it started ("setup network: netavark: nftables error"; issue 1703, reproduced with buildah 1.45.2).
|
||||
argv := append(m.storeFlags(), "bud", "--isolation", "oci", "--network", "pasta", "--tag", local, "--file", dockerfile)
|
||||
// --timestamp 0: the image's creation time and the time of every file in its layers are the Unix epoch, so one source at one
|
||||
// version is one digest in any folder at any time; no label or annotation below names a commit, a folder, a time or a node
|
||||
// (design 47 H2 H-A-591 (3)).
|
||||
argv := append(m.storeFlags(), "bud", "--isolation", "oci", "--network", "pasta", "--timestamp", "0", "--tag", local, "--file", dockerfile)
|
||||
if art.Target != "" {
|
||||
argv = append(argv, "--target", art.Target)
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func TestBuildRunsBuildahRootlessAndAnswersTheDigest(t *testing.T) {
|
||||
}
|
||||
dir := filepath.Join(m.Work, "ws1", "tree", "modules", "demo")
|
||||
for _, want := range []string{
|
||||
"--root " + m.Store + "/root", "--runroot " + m.Store + "/run", "--isolation oci", "--network pasta",
|
||||
"--root " + m.Store + "/root", "--runroot " + m.Store + "/run", "--isolation oci", "--network pasta", "--timestamp 0 ",
|
||||
"--file " + dir + "/Dockerfile", "--target final",
|
||||
"--build-arg DEMO_BASE=docker.io/library/busybox@sha256:0000000000000000000000000000000000000000000000000000000000000001",
|
||||
} {
|
||||
@@ -343,7 +343,7 @@ func TestTheImageBuildGetsTheVersionTheAskCarriesAsMeshVersion(t *testing.T) {
|
||||
}
|
||||
m, f, states = setup(t, same)
|
||||
runBuild(t, m, states, nil)
|
||||
if bud := f.called("bud"); len(bud) != 1 || (strings.Contains(bud[0].line, "MESH_VERSION") || strings.Contains(bud[0].line, "image.version")) {
|
||||
if bud := f.called("bud"); len(bud) != 1 || (strings.Contains(bud[0].line, "MESH_VERSION") || strings.Contains(bud[0].line, "image.version") || strings.Contains(bud[0].line, "--label")) {
|
||||
t.Fatalf("a build with no version: %+v", bud)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun/conformance"
|
||||
)
|
||||
|
||||
func needTools(t *testing.T, what string, tools ...string) {
|
||||
@@ -159,6 +161,37 @@ func TestARealBuildAnswersTheImagesDigest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The kit's `reproducible` case over a real build (design 47 H2 H-A-591 (3), H-A-593 (3)): the image fixture, with no step that
|
||||
// fetches, built by real buildah in two workspace folders of other names and other file times gives one manifest digest.
|
||||
func TestARealImageBuildIsOneDigestInAnyFolder(t *testing.T) {
|
||||
needTools(t, "a rootless build", "buildah", "newuidmap")
|
||||
fill := func(dir string) error {
|
||||
module := filepath.Join(dir, "ws1", "tree", "modules", "img")
|
||||
if err := os.MkdirAll(module, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
for name, body := range map[string]string{
|
||||
"module.json": `{"module":"img","version":"1","build":{"artifacts":[{"name":"server","kind":"image","from":"Dockerfile"}]}}`,
|
||||
"Dockerfile": "FROM scratch\nCOPY hello.txt /hello.txt\n",
|
||||
"hello.txt": "hello\n",
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(module, name), []byte(body), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
conformance.Reproducible(t, fill, func(dir string) (map[string]string, error) {
|
||||
m, states := realModule(t)
|
||||
m.Work = dir
|
||||
res, st := buildReal(t, m, states)
|
||||
if st.State != sdkstep.StepPassed {
|
||||
return nil, fmt.Errorf("the build step ended %s: %s", st.State, st.Reason)
|
||||
}
|
||||
return map[string]string{"server": res.Digest}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// needBase skips unless the build node can pull the small base the isolation Dockerfiles run in.
|
||||
func needBase(t *testing.T, m *Module) string {
|
||||
t.Helper()
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) {
|
||||
// did not answer as a transport fault, and a failure of the source (a RUN line that fails) as none.
|
||||
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
// A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its
|
||||
// first run and 60 s after its second by default (design 47 H2 §799; H-A-390).
|
||||
// first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603).
|
||||
t.Run("again-delays is declared and read", func(t *testing.T) {
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
@@ -51,7 +51,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
||||
_ = json.Unmarshal(decl, &c)
|
||||
delay, err := steprun.AgainDelays(c.Default)
|
||||
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second {
|
||||
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second {
|
||||
t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -46,10 +46,10 @@
|
||||
},
|
||||
"again-delays": {
|
||||
"type": "string",
|
||||
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
|
||||
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
|
||||
"trusted": false,
|
||||
"runtime": true,
|
||||
"default": "15s,60s"
|
||||
"default": "15s,90s"
|
||||
}
|
||||
},
|
||||
"tools": [
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestTheStartSweepEndsWhatAPreviousProcessLeft(t *testing.T) {
|
||||
// not answer as a transport fault, and a failure of the source (a package the registry lacks) as none.
|
||||
func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
// A step whose fetch or publish met its holder away is given again after the module's again-delays, 15 s after its
|
||||
// first run and 60 s after its second by default (design 47 H2 §799; H-A-390).
|
||||
// first run and 90 s after its second by default, a span past the tool runner's restart (design 47 H2 §799; H-A-390, H-A-603).
|
||||
t.Run("again-delays is declared and read", func(t *testing.T) {
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
@@ -62,7 +62,7 @@ func TestTheStepsSayAFailedNetworkAsATransportFault(t *testing.T) {
|
||||
decl, ok := m.Config[steprun.AgainDelaysSetting]
|
||||
_ = json.Unmarshal(decl, &c)
|
||||
delay, err := steprun.AgainDelays(c.Default)
|
||||
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 60*time.Second {
|
||||
if !ok || !c.Runtime || err != nil || delay(1) != 15*time.Second || delay(2) != 90*time.Second {
|
||||
t.Fatalf("again-delays declared %v as %+v: %v", ok, c, err)
|
||||
}
|
||||
})
|
||||
@@ -115,3 +115,24 @@ func TestThePullerCountsRunsThatStarted(t *testing.T) {
|
||||
return m.Puller(nil, steprun.NewFakeAsks())
|
||||
})
|
||||
}
|
||||
|
||||
// H-A-591 (4), H-A-593 (3): the kit's `reproducible` case. The module's own build step packs a fixture bundle twice, in two
|
||||
// workspace folders of other names and other file times (the compiler and the bundler stand in, as in every build test of this
|
||||
// module, and write what they would from the same source), and the archive's digest is the same: nothing of the folder or
|
||||
// the clock is in the pack.
|
||||
func TestTheBuildOfABundleIsOneDigestInAnyFolder(t *testing.T) {
|
||||
conformance.Reproducible(t, func(dir string) error {
|
||||
workspaceWith(t, dir, map[string]string{"modules/m/module.json": strings.Replace(bundleManifest, "%s", "", 1),
|
||||
"modules/m/tools/index.ts": "export {}"})
|
||||
return nil
|
||||
}, func(dir string) (map[string]string, error) {
|
||||
m, f, _ := newMachine(t)
|
||||
m.Work = dir
|
||||
f.effect = esbuildEffect(t)
|
||||
out, err := m.build(context.Background(), buildArgs())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]string{"tools": out.(BuildResult).Digest}, nil
|
||||
})
|
||||
}
|
||||
|
||||
@@ -50,10 +50,10 @@
|
||||
},
|
||||
"again-delays": {
|
||||
"type": "string",
|
||||
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,60s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
|
||||
"description": "The delays a step ask whose fetch or publish met its holder away is given again after: after its first run, then after its second, as durations such as 15s,90s (design 47 H2 §799); a third run met so ends the step failed with why fetch: or publish:.",
|
||||
"trusted": false,
|
||||
"runtime": true,
|
||||
"default": "15s,60s"
|
||||
"default": "15s,90s"
|
||||
},
|
||||
"prune-mark": {
|
||||
"type": "number",
|
||||
|
||||
@@ -149,6 +149,7 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
own.follow()
|
||||
c := &Config{Store: runtimeStore{own: own}, Logf: logf, Asks: runtimeAsks{},
|
||||
Delivery: toolDelivery{ask: stdio.Ask}, Vault: toolVault{ask: stdio.Ask, recorder: recorder}}
|
||||
// The module's one held writer (design 47 G §689, A-16, A-29, A-32): the renames' and retirements' findings and the views reader's go through it.
|
||||
|
||||
@@ -95,22 +95,15 @@ func (o *ownerViews) read(state string) (*views.Follower, bool) {
|
||||
return f, ok
|
||||
}
|
||||
|
||||
// errUnanswered says a first view is not answered yet: a reader waits, and its next resolution reads it.
|
||||
func errUnanswered(f *views.Follower) error {
|
||||
s := f.Status()
|
||||
return fmt.Errorf("the first view of %s's %s is not answered yet (%s asked %d times)", s.Owner, s.State, s.Tool, s.Asks)
|
||||
}
|
||||
|
||||
// get is one key of a followed state.
|
||||
func (o *ownerViews) get(state, key string) (*Entry, bool, error) {
|
||||
f, ok := o.read(state)
|
||||
if !ok {
|
||||
return nil, false, nil
|
||||
}
|
||||
select {
|
||||
case <-f.Ready():
|
||||
default:
|
||||
return nil, true, errUnanswered(f)
|
||||
// A first view not answered yet is the fault `away`, naming the view's owner verb (design 47 H2 H-A-708 (2)).
|
||||
if err := f.Unread(); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
v, held := f.Get(key)
|
||||
if !held {
|
||||
@@ -125,10 +118,8 @@ func (o *ownerViews) keys(state string) ([]string, bool, error) {
|
||||
if !ok {
|
||||
return nil, false, nil
|
||||
}
|
||||
select {
|
||||
case <-f.Ready():
|
||||
default:
|
||||
return nil, true, errUnanswered(f)
|
||||
if err := f.Unread(); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
var out []string
|
||||
for k := range f.Values() {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
)
|
||||
|
||||
@@ -33,7 +34,10 @@ func TestAFollowedStateIsReadFromItsOwnersFirstViewAndEvents(t *testing.T) {
|
||||
}
|
||||
var changed atomic.Int32
|
||||
o := newOwnerViews(ask, func() { changed.Add(1) }, nopFindings{})
|
||||
if _, followed, err := o.get(WantsRead, "want.g14.dunst"); !followed || err == nil || !strings.Contains(err.Error(), "not answered yet") {
|
||||
// H-A-708 (2): a read before the first view is answered `away`, naming the view's owner verb, at once.
|
||||
var away *busretry.Away
|
||||
if _, followed, err := o.get(WantsRead, "want.g14.dunst"); !followed || !errors.As(err, &away) || away.Part != "mesh-delivery-assigner.assigner_read_wants" ||
|
||||
!strings.HasPrefix(away.Words, "not read yet since ") {
|
||||
t.Fatalf("before the first view: followed %v, %v", followed, err)
|
||||
}
|
||||
if !o.reader.Follows("mesh-delivery-assigner.wants") {
|
||||
|
||||
@@ -36,6 +36,10 @@ func newOwnCopy() *ownCopy {
|
||||
}
|
||||
|
||||
func (o *ownCopy) get(state, key string) (*Entry, error) {
|
||||
// A state whose copy is not read yet is the fault `away` at once, never a wait (design 47 H2 H-A-708 (2)).
|
||||
if err := o.copy.Unread(state); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, ok, err := o.copy.Get(state, key)
|
||||
if err != nil || !ok {
|
||||
return nil, err
|
||||
@@ -43,7 +47,20 @@ func (o *ownCopy) get(state, key string) (*Entry, error) {
|
||||
return &Entry{Key: key, Value: raw}, nil
|
||||
}
|
||||
|
||||
func (o *ownCopy) keys(state string) ([]string, error) { return o.copy.Keys(state) }
|
||||
func (o *ownCopy) keys(state string) ([]string, error) {
|
||||
if err := o.copy.Unread(state); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return o.copy.Keys(state)
|
||||
}
|
||||
|
||||
// follow starts the watch of every state the copy holds, each on its goroutine, so a read asked before one is in is
|
||||
// answered `away` and the copy is read by the time it is asked again (Unread; design 47 H2 H-A-708 (2)).
|
||||
func (o *ownCopy) follow() {
|
||||
for state := range ownStates {
|
||||
go o.copy.Follow(state, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// write puts a key and takes it into the copy at the revision the bus answered.
|
||||
func (o *ownCopy) write(state, key string, value any) error {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
occ "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
)
|
||||
|
||||
// countingStore counts the reads of the states by state: what the bus would be asked.
|
||||
@@ -203,6 +204,15 @@ func TestAnOwnStateIsReadFromItsWatchedCopyNotKeyByKey(t *testing.T) {
|
||||
}
|
||||
n := len(b.held[ValuesState])
|
||||
own := b.ownCopy()
|
||||
// H-A-708 (2): before the state's copy is read a read is the fault `away` at once, naming the state; the start's watch reads it.
|
||||
var away *busretry.Away
|
||||
if _, err := own.keys(ValuesState); !errors.As(err, &away) || away.Part != "the state "+ValuesState || !strings.HasPrefix(away.Words, "not read yet since ") {
|
||||
t.Fatalf("before the copy is read: %v", err)
|
||||
}
|
||||
if _, err := own.get(ValuesState, "mesh.key-0s"); !errors.As(err, &away) {
|
||||
t.Fatalf("a get before the copy is read: %v", err)
|
||||
}
|
||||
own.copy.Follow(ValuesState, nil)
|
||||
for pass := 0; pass < 3; pass++ {
|
||||
keys, err := own.keys(ValuesState)
|
||||
if err != nil || len(keys) != n {
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -471,6 +472,42 @@ func TestTheReviewEndsAtTheFirstPassedReviewStepOfTheRunner(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-709 (2): the runner's `show` is read to its last page; the steps of every page are the row's; a page that fails writes no row.
|
||||
func TestTheRunnersShowIsReadToItsLastPage(t *testing.T) {
|
||||
page := func(next, step, outcome, ended string) json.RawMessage {
|
||||
e := ""
|
||||
if ended != "" {
|
||||
e = `,"ended":"` + ended + `"`
|
||||
}
|
||||
return json.RawMessage(`{"pipeline":{"pipeline":"b.1.m","module":"m","outcome":"passed","steps":[{"step":"` + step + `","outcome":"` + outcome + `"` + e + `}]},"capped":` +
|
||||
fmt.Sprint(next != "") + `,"next":"` + next + `"}`)
|
||||
}
|
||||
pages := map[string]json.RawMessage{"": page("c1", "lint", "passed", ""), "c1": page("c2", "unit", "passed", ""),
|
||||
"c2": page("", "review", "passed", "2026-10-12T09:05:00Z")}
|
||||
var asked []string
|
||||
row, err := readPipeline(func(a map[string]any) (json.RawMessage, error) {
|
||||
next, _ := a["next"].(string)
|
||||
asked = append(asked, next)
|
||||
return pages[next], nil
|
||||
}, "b.1.m", "r#1")
|
||||
if err != nil || len(row.Steps) != 3 || row.reviewed.IsZero() || fmt.Sprint(asked) != "[ c1 c2]" {
|
||||
t.Fatalf("row %+v, asked %q, %v: every page's steps are the row's, the last page's review among them", row, asked, err)
|
||||
}
|
||||
// A page that fails: no row, the error names the page.
|
||||
if row, err := readPipeline(func(a map[string]any) (json.RawMessage, error) {
|
||||
if a["next"] == "c1" {
|
||||
return nil, errFake("the runner is away")
|
||||
}
|
||||
return pages[""], nil
|
||||
}, "b.1.m", "r#1"); err == nil || !strings.Contains(err.Error(), "page 2") || row.Module != "" {
|
||||
t.Fatalf("row %+v, error %v", row, err)
|
||||
}
|
||||
// A cursor answered again is no endless read.
|
||||
if _, err := readPipeline(func(map[string]any) (json.RawMessage, error) { return page("c1", "lint", "passed", ""), nil }, "b.1.m", "r#1"); err == nil {
|
||||
t.Fatal("a cursor repeated was read on")
|
||||
}
|
||||
}
|
||||
|
||||
type errFake string
|
||||
|
||||
func (e errFake) Error() string { return string(e) }
|
||||
|
||||
@@ -88,6 +88,46 @@ func parsePipelineRow(raw json.RawMessage, pr string) (PipelineRow, error) {
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// readPipeline reads one pipeline through `show`, page after page: each page's `next` is asked until none is left, the steps of
|
||||
// every page are the row's (design 47 H2 H-A-709 (2): the runner answers within a bound). A page that fails fails the read,
|
||||
// so no row is written from the pages before it.
|
||||
func readPipeline(ask func(args map[string]any) (json.RawMessage, error), key, pr string) (PipelineRow, error) {
|
||||
var row PipelineRow
|
||||
next, seen := "", map[string]bool{}
|
||||
for page := 1; ; page++ {
|
||||
args := map[string]any{"pipeline": key}
|
||||
if next != "" {
|
||||
args["next"] = next
|
||||
}
|
||||
raw, err := ask(args)
|
||||
if err != nil {
|
||||
return PipelineRow{}, fmt.Errorf("page %d of %s: %w", page, key, err)
|
||||
}
|
||||
got, err := parsePipelineRow(raw, pr)
|
||||
if err != nil {
|
||||
return PipelineRow{}, fmt.Errorf("page %d of %s: %w", page, key, err)
|
||||
}
|
||||
if page == 1 {
|
||||
row = got
|
||||
} else {
|
||||
row.Steps = append(row.Steps, got.Steps...)
|
||||
if !got.reviewed.IsZero() && (row.reviewed.IsZero() || got.reviewed.Before(row.reviewed)) {
|
||||
row.reviewed = got.reviewed
|
||||
}
|
||||
}
|
||||
m, _ := answerOf(raw, "mesh-pipeline-runner.show")
|
||||
next = ""
|
||||
_ = json.Unmarshal(m["next"], &next)
|
||||
if next == "" {
|
||||
return row, nil
|
||||
}
|
||||
if seen[next] {
|
||||
return PipelineRow{}, fmt.Errorf("page %d of %s: the runner answered the cursor %q again", page, key, next)
|
||||
}
|
||||
seen[next] = true
|
||||
}
|
||||
}
|
||||
|
||||
// busPipelines reads a pull request's head from the seat `git`, then its pipelines from the runner: `list` given the head
|
||||
// commit, `show` of each.
|
||||
func busPipelines(owner string) Pipelines {
|
||||
@@ -110,11 +150,9 @@ func busPipelines(owner string) Pipelines {
|
||||
}
|
||||
var rows []PipelineRow
|
||||
for _, k := range keys {
|
||||
raw, err := stdio.Ask("seat:mesh-pipeline-runner.show", map[string]any{"pipeline": k})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row, err := parsePipelineRow(raw, pr)
|
||||
row, err := readPipeline(func(args map[string]any) (json.RawMessage, error) {
|
||||
return stdio.Ask("seat:mesh-pipeline-runner.show", args)
|
||||
}, k, pr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1738,13 +1738,23 @@ func (w watchingStore) copied(state string) bool {
|
||||
return slices.Contains(WatchedReads, state) || slices.Contains(OwnStates, state)
|
||||
}
|
||||
|
||||
// unread is the fault `away` while the copy of a state the holder follows from its start is not read yet (design 47 H2
|
||||
// H-A-708 (2), H-A-717 DQ-55): a call made then is answered at once, never waits for the copy.
|
||||
func (w watchingStore) unread(state string) error {
|
||||
if !slices.Contains(WatchedReads, state) {
|
||||
return nil
|
||||
}
|
||||
return w.ws.Unread(state)
|
||||
}
|
||||
|
||||
func (w watchingStore) Get(state, key string) (*Entry, error) {
|
||||
get := w.ws.Get
|
||||
switch {
|
||||
case !w.copied(state):
|
||||
if !w.copied(state) {
|
||||
return w.Store.Get(state, key)
|
||||
}
|
||||
v, found, err := get(state, key)
|
||||
if err := w.unread(state); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, found, err := w.ws.Get(state, key)
|
||||
if err != nil || !found {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1755,6 +1765,9 @@ func (w watchingStore) Keys(state string) ([]string, error) {
|
||||
if !w.copied(state) {
|
||||
return w.Store.Keys(state)
|
||||
}
|
||||
if err := w.unread(state); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return w.ws.Keys(state)
|
||||
}
|
||||
|
||||
|
||||
@@ -203,6 +203,10 @@ func TestTheHolderPlansProvidesAndAsksOnTheBus(t *testing.T) {
|
||||
return p
|
||||
}
|
||||
key := node + ".restic.postgres-database"
|
||||
// The holder follows its states from its start (main.go), so a read finds its copies read (H-A-708 (2)).
|
||||
for _, r := range WatchedReads {
|
||||
ws.Follow(r, nil)
|
||||
}
|
||||
if _, err := h.ComposeNode(ctx, node); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
oc "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||
"git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
@@ -486,6 +487,14 @@ func TestAModuleHeldWithoutAWantIsComposedAtTheBuildItRuns(t *testing.T) {
|
||||
}, func(string, string) ([]byte, bool, error) { return nil, false, nil })
|
||||
m.h.Store = Watching(bus, ws)
|
||||
wk := &work{pending: map[string]bool{}, wake: make(chan struct{}, 1)}
|
||||
// H-A-708 (2): a state the holder follows from its start, asked before its copy is read, is the fault `away` at once.
|
||||
var away *busretry.Away
|
||||
if _, err := m.h.Store.Keys(WantsRead); !errors.As(err, &away) || !strings.HasPrefix(away.Words, "not read yet since ") || len(watches) != 0 {
|
||||
t.Fatalf("a read before the copy: %v, watches %v", err, watches)
|
||||
}
|
||||
for _, r := range []string{AssignmentsRead, WantsRead} {
|
||||
ws.Follow(r, nil)
|
||||
}
|
||||
for _, r := range []string{ComposedRead, HaveRead} {
|
||||
ws.Follow(r, func(c stdio.StateChange) error { wk.add(NodesOfNodeKey(c.Key)...); return nil })
|
||||
}
|
||||
|
||||
@@ -77,21 +77,18 @@ func unwrapToolAnswer(raw json.RawMessage) []byte {
|
||||
return raw
|
||||
}
|
||||
|
||||
// viewAssignments is the assignments reader over the picture: a key asked before the first view is answered is an error, so
|
||||
// the caller waits (the "not yet" of the vault's other reads), never a read of the owner's bucket.
|
||||
// viewAssignments is the assignments reader over the picture: a key asked before the first view is answered is the fault
|
||||
// `away` naming the view's owner verb (design 47 H2 H-A-708 (2), H-A-717 DQ-55), never a read of the owner's bucket.
|
||||
func viewAssignments(f func() *views.Follower) AssignerReader {
|
||||
ready := func() (*views.Follower, error) {
|
||||
fol := f()
|
||||
if fol == nil {
|
||||
return nil, fmt.Errorf("the vault reads the assigner's assignments only when it runs as the module")
|
||||
}
|
||||
select {
|
||||
case <-fol.Ready():
|
||||
return fol, nil
|
||||
default:
|
||||
s := fol.Status()
|
||||
return nil, fmt.Errorf("the first view of the assigner's assignments is not answered yet (%s asked %d times)", s.Tool, s.Asks)
|
||||
if err := fol.Unread(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fol, nil
|
||||
}
|
||||
return AssignerReader{
|
||||
Keys: func() ([]string, error) {
|
||||
|
||||
@@ -5,10 +5,12 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||
"git.novox.be/novox/mesh-sdk/go/views"
|
||||
)
|
||||
|
||||
@@ -32,8 +34,13 @@ func TestAnUnansweredFirstViewOfTheAssignmentsIsAFindingTheAnswerClears(t *testi
|
||||
f, _ := newAssignmentsView(ask, func(string) {}, nil, heldFindings{&mu, held})
|
||||
f.Bound, f.Wait = 30*time.Millisecond, 10*time.Millisecond
|
||||
reader := viewAssignments(func() *views.Follower { return f })
|
||||
if _, err := reader.Keys(); err == nil {
|
||||
t.Fatal("the assignments was read before its first view")
|
||||
// H-A-708 (2): before the first view a read is the fault `away` naming the view's owner verb, at once.
|
||||
var away *busretry.Away
|
||||
if _, err := reader.Keys(); !errors.As(err, &away) || away.Part != AssignmentsTool || !strings.HasPrefix(away.Words, "not read yet since ") {
|
||||
t.Fatalf("the assignments was read before its first view, or not as away: %v", err)
|
||||
}
|
||||
if _, err := reader.Read("g14.node"); !errors.As(err, &away) {
|
||||
t.Fatalf("a read before the first view: %v", err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- f.Start(context.Background()) }()
|
||||
|
||||
Reference in New Issue
Block a user