Merge pull request 'gitea's Go bundles read the token gitea keeps when the vault refuses their account (design 47 H2, H-A-564)' (#747) from fix/gitea-token-fallback into main

This commit was merged in pull request #747.
This commit is contained in:
2026-11-23 12:16:02 +00:00
5 changed files with 293 additions and 19 deletions
+9 -3
View File
@@ -694,6 +694,13 @@ 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 {
@@ -713,10 +720,9 @@ 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)
}
}
// Design 47 H2 §808, H-A-422 (1): the token is read through the vault seat's get, never from a file.
for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} {
if a.Env[k] != "" {
t.Errorf("%s is given %s: its token is read from the vault", a.From, k)
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])
}
}
}
+135 -15
View File
@@ -3,12 +3,20 @@ package forgehttp
// The forge module's tokens as its Go bundles read them (design 47 H2 §808; H-A-422 (1), H-A-426): kept in the vault as
// the module's own, `module/gitea/<account>`, written by the TypeScript bundle's minter through own-put, and read here
// 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. Never a file: the bundle holds the token in memory only, and says nothing of it.
// 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.
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
@@ -28,15 +36,41 @@ 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)
// VaultToken is one account's token as this process holds it, read from the vault.
// 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).
type VaultToken struct {
Account string
ask Ask
keys seal.KeyPair
// 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
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.
@@ -48,10 +82,20 @@ 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.
// Load reads the account's token from the vault again; from File when the vault refuses the caller's account.
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 {
@@ -77,16 +121,45 @@ func (t *VaultToken) Load() error {
return fmt.Errorf("the vault's %s is empty", VaultName(t.Account))
}
t.mu.Lock()
t.token, t.generation = token, got.Generation
t.token, t.generation, t.source = token, got.Generation, SourceVault
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 := t.token
token, source := t.token, t.source
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
}
@@ -135,12 +208,46 @@ 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 (never the token). It returns when the subscription ends.
// through logf what it read and, once at start, from which source (never the token). It returns when the
// subscription ends.
func Follow(logf func(format string, args ...any), accounts ...string) error {
var held []*VaultToken
for _, a := range accounts {
@@ -151,13 +258,7 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
held = append(held, t)
}
<-stdio.Served()
for _, t := range held {
if err := t.Load(); err != nil {
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
} else {
logf("read %s at generation %d", VaultName(t.Account), t.Generation())
}
}
Start(logf, held...)
return stdio.Subscribe(SecretChanged, func(e stdio.Envelope) error {
var errs []error
for _, t := range held {
@@ -171,3 +272,22 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
return errors.Join(errs...)
})
}
// Start reads each token once and says, through logf, from which source it came (H-A-564), never the token.
func Start(logf func(format string, args ...any), held ...*VaultToken) {
for _, t := range held {
switch err := t.Load(); {
case 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)
}
}
}
@@ -0,0 +1,138 @@
package forgehttp
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")
vaultHolds := func(token string) Ask {
return func(address string, args any) (json.RawMessage, error) {
a := args.(map[string]any)
value, _ := json.Marshal(map[string]any{"token": token})
box, err := seal.Seal(string(value), a["public_key"].(string))
if err != nil {
return nil, err
}
return json.Marshal(map[string]any{"generation": 3, "sealed": box})
}
}
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
}{
{"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"},
} {
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()
if c.err != "" {
if err == nil || !strings.Contains(err.Error(), c.err) {
t.Fatalf("token %q, error %v; want an error saying %q", got, err, c.err)
}
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 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)
}
})
}
// 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)
}
}
+3
View File
@@ -544,7 +544,9 @@
"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"
}
},
@@ -561,6 +563,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_PATCH_DIR": "${dir:forge-patches}"
}
},
+8 -1
View File
@@ -374,8 +374,15 @@ 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"],
};
for (const a of manifest.build.artifacts) {
assert.equal(a.env?.MESH_GITEA_TOKEN_FILE ?? a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE, undefined, `${a.name} is handed a token file`);
assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], files[a.name] ?? [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(","));
assert.ok(manifest.consumes.includes("mesh-vault.secret-changed"), "the Go bundles hear the vault's changes");