GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Dashboard: unnamed numbered key values with labels and order, key poo… · gitmoot/keyring@28a90cf

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • README.md
  • cmd/keyring
    • main.go
    • poolconvert.go
    • poolconvert_test.go
  • docs
    • dashboard.md
    • proxy.md
  • internal
    • admin
      • admin.go
    • dashboard
      • dashboard.go
      • key_editing_fail_test.go
      • key_editing_rlimit_linux_test.go
      • key_editing_test.go
      • key_parts_test.go
      • keyedit.go
      • pages.go
      • pool_test.go
      • services.go
      • upload.go
    • policy
      • catalog.go
      • policy.go
    • server
      • pool_test.go
      • server.go
    • store
      • store.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎README.md‎

Copy file name to clipboardExpand all lines: README.md
+2-2Lines changed: 2 additions & 2 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@ The key never leaves the keyring machine. The agent holds only a role token, whi
3333

3434
## What it does
3535

36-
- **API proxy.** Bearer (or another `Authorization` scheme, such as `Key`), header or query-parameter keys, up to two extra secret headers, keys with several values, and [key pools](docs/proxy.md#key-pools-several-keys-behind-one-service) that switch to the next key when one is refused or runs out. Paths are normalised, keys echoed back by an API are masked, redirects are not followed. [Proxy](docs/proxy.md)
36+
- **API proxy.** Bearer (or another `Authorization` scheme, such as `Key`), header or query-parameter keys, up to two extra secret headers, keys with up to 32 values (numbered or named, with optional labels), and [key pools](docs/proxy.md#key-pools-several-keys-behind-one-service) that try a key's values in the order you set and switch to the next when one is refused or runs out. Paths are normalised, keys echoed back by an API are masked, redirects are not followed. [Proxy](docs/proxy.md)
3737
- **Request signing without handing out the private key.** Apple Ads and App Store Connect JWTs, Sign in with Apple client secrets, APNs push, raw Ed25519, and minisign release signatures. [Apple](docs/apple.md) · [Signing](docs/signing.md)
3838
- **OAuth with refresh.** The keyring holds the refresh token and mints access tokens, for Gmail, Drive and any OAuth 2 provider; Google accounts can also come from `gcloud`. [OAuth](docs/oauth.md) · [Google via gcloud](docs/google-gcloud.md)
3939
- **Per-agent access.** Each agent (a *role*) gets only the services, methods and paths it was given, with daily request and byte limits and an end date. Agents find services with `keyring services --search`, ask with `keyring request`, and the owner approves in one tap. [Finding services](docs/proxy.md#finding-services)
4040
- **Projects.** Group a client's services, give an agent a whole project, pause it or let it expire in one place. [Projects](docs/projects.md)
41-
- **Dashboard and audit.** Add, test, replace and upload keys; see each key's status and use; approve agents; search the audit log of every call. [Dashboard](docs/dashboard.md)
41+
- **Dashboard and audit.** Add, test, replace, rename and upload keys; add, label, order, rename and remove their values; see each key's status and use; approve agents; search the audit log of every call. [Dashboard](docs/dashboard.md)
4242
- **Consent links.** Send a person a one-time link to connect their own account (OAuth sign-in) or paste a key, instead of sending it in a chat. [Consent links](docs/consent-links.md)
4343
- **Egress tunnels.** Let an agent's traffic leave through a person's own proxy, with the proxy credential kept in the keyring. [Egress proxy](docs/egress-proxy.md)
4444
- **One keyring per person.** Instance mode runs a small keyring per user under a supervisor, for example on Cloudflare Containers. [Instance mode](docs/instance-mode.md)
Collapse file

‎cmd/keyring/main.go‎

Copy file name to clipboardExpand all lines: cmd/keyring/main.go
+16-3Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
245245
}
246246

247247
func check(configPath, storePath string, stdout io.Writer) error {
248-
cfg, err := policy.Load(configPath)
248+
cfg, err := loadConfig(configPath, storePath, false, stdout)
249249
if err != nil {
250250
return err
251251
}
@@ -273,6 +273,13 @@ func check(configPath, storePath string, stdout io.Writer) error {
273273
func missingKeys(cfg *policy.Config, keys map[string]string) []string {
274274
var missing []string
275275
for _, svc := range cfg.Services {
276+
if svc.KeyPool {
277+
// A pool names its key; any stored value of it will do.
278+
if len(policy.PoolMembers(svc, keys, nil)) == 0 {
279+
missing = append(missing, svc.Key)
280+
}
281+
continue
282+
}
276283
for _, name := range svc.KeyNames() {
277284
if keys[name] == "" {
278285
missing = append(missing, name)
@@ -284,7 +291,7 @@ func missingKeys(cfg *policy.Config, keys map[string]string) []string {
284291
}
285292

286293
func serve(configPath, storePath string, stderr io.Writer) error {
287-
cfg, err := policy.Load(configPath)
294+
cfg, err := loadConfig(configPath, storePath, true, stderr)
288295
if err != nil {
289296
return err
290297
}
@@ -325,7 +332,13 @@ func serve(configPath, storePath string, stderr io.Writer) error {
325332
// changes serializes the dashboard's writes, consent links and the
326333
// SIGHUP reload.
327334
changes := &sync.Mutex{}
328-
metaPath := filepath.Join(filepath.Dir(storePath), "keymeta.json")
335+
metaPath := metaPathOf(storePath)
336+
// Key pools try a key's values in the list order the dashboard keeps.
337+
if order, err := dashboardpkg.ValueOrder(metaPath); err != nil {
338+
fmt.Fprintf(stderr, "key value order not loaded (key pools use name order): %v\n", err)
339+
} else {
340+
handler.SetValueOrder(order)
341+
}
329342
dashboard, dashboardSrv, err := startDashboard(cfg, audit, stderr, func(a *admin.Server) {
330343
reqs := requests.Open(filepath.Join(filepath.Dir(storePath), "requests.json"))
331344
handler.SetRequests(reqs)
Collapse file

‎cmd/keyring/poolconvert.go‎

Copy file name to clipboard
+107Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"maps"
7+
"path/filepath"
8+
"slices"
9+
"strings"
10+
11+
dashboardpkg "github.com/gitmoot/keyring/internal/dashboard"
12+
"github.com/gitmoot/keyring/internal/policy"
13+
"github.com/gitmoot/keyring/internal/store"
14+
)
15+
16+
// metaPathOf is the dashboard's key notes file next to the key store.
17+
func metaPathOf(storePath string) string {
18+
return filepath.Join(filepath.Dir(storePath), "keymeta.json")
19+
}
20+
21+
// loadConfig is policy.Load, plus the one-time upgrade of v0.14.18 key pools:
22+
// such a pool named one value of its key ("key":"CLAUDE_KEYS.main"), which
23+
// is now refused, as a pool names the key. Each is converted to name the key,
24+
// and the key's list (keymeta.json next to the store) gets the order v0.14.18
25+
// tried: the value it named first, then the key's other values by name
26+
// (lexically: "10" before "2"), so the pool keeps its whole failover order.
27+
// Conversions that would change what a pool sends are refused before
28+
// anything is written: two pools of one key with different first values,
29+
// and a pool whose key also holds a plain value (v0.14.18 never sent it; a
30+
// pool now would, once the key has no other values). Without write (keyring
31+
// check) the conversion is checked in memory only; the service writes it
32+
// when it starts. The key notes are written before the access file, so a
33+
// failure in between is redone at the next start.
34+
func loadConfig(configPath, storePath string, write bool, out io.Writer) (*policy.Config, error) {
35+
rules, err := policy.LoadRules(configPath)
36+
if err != nil {
37+
return nil, err
38+
}
39+
access, err := policy.LoadAccess(rules.AccessFile)
40+
if err != nil {
41+
return nil, err
42+
}
43+
first, err := policy.ConvertNamedValuePools(&access)
44+
if err != nil {
45+
return nil, fmt.Errorf("converting v0.14.18 key pools: %w", err)
46+
}
47+
cfg := &policy.Config{Rules: rules, AccessList: access}
48+
if err := cfg.Validate(); err != nil {
49+
if len(first) > 0 {
50+
return nil, fmt.Errorf("converting v0.14.18 key pools (%s): %w", poolKeys(first), err)
51+
}
52+
return nil, err
53+
}
54+
if len(first) == 0 {
55+
return cfg, nil
56+
}
57+
order := map[string][]string{}
58+
for key, part := range first {
59+
order[key] = []string{part}
60+
}
61+
if storePath != "" {
62+
keys, err := store.Load(storePath)
63+
if err != nil {
64+
return nil, err
65+
}
66+
for _, key := range slices.Sorted(maps.Keys(first)) {
67+
if keys[key] != "" {
68+
return nil, fmt.Errorf("converting v0.14.18 key pools: the pool on %s.%s never sent the plain value %s, but a pool on %s now would once its other values are gone; store that value as %s.<name>, or delete it, or remove key_pool, then start again", key, first[key], key, key, key)
69+
}
70+
order[key] = append(order[key], otherValues(keys, key, first[key])...)
71+
}
72+
}
73+
if !write {
74+
fmt.Fprintf(out, "key pools naming one value (%s) are converted to name the key when the service starts\n", poolKeys(first))
75+
return cfg, nil
76+
}
77+
if err := dashboardpkg.PutValueOrder(metaPathOf(storePath), order); err != nil {
78+
return nil, fmt.Errorf("converting key pools: %w", err)
79+
}
80+
cfg, err = policy.SaveAccess(rules, access)
81+
if err != nil {
82+
return nil, fmt.Errorf("converting key pools: %w", err)
83+
}
84+
fmt.Fprintf(out, "converted key pools to name the key, each first value kept first: %s\n", poolKeys(first))
85+
return cfg, nil
86+
}
87+
88+
// otherValues are the names of key's stored values (key.part) other than
89+
// skip, sorted by name as v0.14.18 tried a pool's backups.
90+
func otherValues(keys map[string]string, key, skip string) []string {
91+
var parts []string
92+
for name, value := range keys {
93+
if base, part := store.SplitPart(name); base == key && part != "" && part != skip && value != "" {
94+
parts = append(parts, part)
95+
}
96+
}
97+
slices.Sort(parts)
98+
return parts
99+
}
100+
101+
func poolKeys(first map[string]string) string {
102+
var names []string
103+
for _, key := range slices.Sorted(maps.Keys(first)) {
104+
names = append(names, key+"."+first[key])
105+
}
106+
return strings.Join(names, ", ")
107+
}
Collapse file

‎cmd/keyring/poolconvert_test.go‎

Copy file name to clipboard
+160Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"maps"
7+
"os"
8+
"path/filepath"
9+
"slices"
10+
"strings"
11+
"testing"
12+
13+
dashboardpkg "github.com/gitmoot/keyring/internal/dashboard"
14+
"github.com/gitmoot/keyring/internal/policy"
15+
"github.com/gitmoot/keyring/internal/store"
16+
)
17+
18+
// An install upgraded from v0.14.18 may have the pool that release accepted:
19+
// "key":"CLAUDE_KEYS.main" with key_pool. The new release still checks and
20+
// starts with it: the pool is converted to name the key, and main stays the
21+
// value it tries first (by name order, backup1 would come first).
22+
func TestUpgradeConvertsAPoolThatNamedOneValue(t *testing.T) {
23+
dir := t.TempDir()
24+
rules := filepath.Join(dir, "rules.json")
25+
accessPath := filepath.Join(dir, "access.json")
26+
keysPath := filepath.Join(dir, "keys.json")
27+
if err := os.WriteFile(rules, []byte(oldRules(dir, "127.0.0.1:7701")), 0o640); err != nil {
28+
t.Fatal(err)
29+
}
30+
if err := migrate(rules, accessPath, &bytes.Buffer{}); err != nil {
31+
t.Fatal(err)
32+
}
33+
cfg, err := policy.Load(rules)
34+
if err != nil {
35+
t.Fatal(err)
36+
}
37+
access := cfg.AccessList
38+
access.Services["claude-api"] = policy.Service{Base: "https://api.anthropic.com", Key: "CLAUDE_KEYS.main", Auth: policy.AuthHeader, Header: "x-api-key", KeyPool: true}
39+
raw, _ := json.MarshalIndent(access, "", " ")
40+
if err := os.WriteFile(accessPath, raw, 0o600); err != nil {
41+
t.Fatal(err)
42+
}
43+
for name, value := range map[string]string{"CLAUDE_KEYS.main": "sk-ant-main-0000", "CLAUDE_KEYS.backup1": "sk-ant-b1-1111", "CLAUDE_KEYS.2": "sk-ant-two-2222", "CLAUDE_KEYS.10": "sk-ant-ten-1010", "API_KEY": "sk-api-0123456789"} {
44+
if err := store.Set(keysPath, name, value); err != nil {
45+
t.Fatal(err)
46+
}
47+
}
48+
49+
// keyring check (the installer runs it before the restart) passes and
50+
// writes nothing.
51+
var out bytes.Buffer
52+
if err := check(rules, "", &out); err != nil {
53+
t.Fatalf("check with the old pool: %v", err)
54+
}
55+
if now, _ := os.ReadFile(accessPath); !bytes.Equal(now, raw) {
56+
t.Fatal("check changed the access file")
57+
}
58+
59+
// The service start converts it once, on disk.
60+
cfg, err = loadConfig(rules, keysPath, true, &out)
61+
if err != nil {
62+
t.Fatalf("start with the old pool: %v", err)
63+
}
64+
if got := cfg.Services["claude-api"].Key; got != "CLAUDE_KEYS" {
65+
t.Fatalf("pool key = %s", got)
66+
}
67+
if _, err := policy.Load(rules); err != nil {
68+
t.Fatalf("converted access file: %v", err)
69+
}
70+
if !strings.Contains(out.String(), "CLAUDE_KEYS.main") || strings.Contains(out.String(), "sk-ant-") {
71+
t.Fatalf("output: %q", out.String())
72+
}
73+
keys, err := store.Load(keysPath)
74+
if err != nil {
75+
t.Fatal(err)
76+
}
77+
order, err := dashboardpkg.ValueOrder(metaPathOf(keysPath))
78+
if err != nil {
79+
t.Fatal(err)
80+
}
81+
members := policy.PoolMembers(cfg.Services["claude-api"], keys, order["CLAUDE_KEYS"])
82+
// v0.14.18 tried main, then the others by name: "10" before "2".
83+
if want := []string{"CLAUDE_KEYS.main", "CLAUDE_KEYS.10", "CLAUDE_KEYS.2", "CLAUDE_KEYS.backup1"}; !slices.Equal(members, want) {
84+
t.Fatalf("pool tries %v, want %v", members, want)
85+
}
86+
if missing := missingKeys(cfg, keys); len(missing) > 0 {
87+
t.Fatalf("missing %v", missing)
88+
}
89+
90+
// A second start changes nothing.
91+
before, _ := os.ReadFile(accessPath)
92+
out.Reset()
93+
if _, err := loadConfig(rules, keysPath, true, &out); err != nil || out.Len() > 0 {
94+
t.Fatalf("second start: %v %q", err, out.String())
95+
}
96+
if after, _ := os.ReadFile(accessPath); !bytes.Equal(before, after) {
97+
t.Fatal("second start rewrote the access file")
98+
}
99+
}
100+
101+
// A conversion that would change what a v0.14.18 pool sends is refused, with
102+
// the services named, and nothing is written: two pools of one key with
103+
// different first values (a key has one list order now), and a pool whose
104+
// key holds only a plain value (v0.14.18 never sent it).
105+
func TestUpgradeRefusesPoolConversionsThatChangeWhatIsSent(t *testing.T) {
106+
pool := func(key string) policy.Service {
107+
return policy.Service{Base: "https://api.anthropic.com", Key: key, Auth: policy.AuthHeader, Header: "x-api-key", KeyPool: true}
108+
}
109+
for _, c := range []struct {
110+
name string
111+
services map[string]policy.Service
112+
keys map[string]string
113+
want string
114+
}{
115+
{"different first values", map[string]policy.Service{"alpha": pool("CLAUDE_KEYS.main"), "beta": pool("CLAUDE_KEYS.backup")},
116+
map[string]string{"CLAUDE_KEYS.main": "sk-ant-main-0000", "CLAUDE_KEYS.backup": "sk-ant-b-1111"}, "alpha and beta"},
117+
{"only a plain value", map[string]policy.Service{"lone": pool("LONE.main")},
118+
map[string]string{"LONE": "sk-ant-lone-0000"}, "never sent the plain value LONE"},
119+
{"a plain value beside named ones", map[string]policy.Service{"mix": pool("MIX.main")},
120+
map[string]string{"MIX": "sk-ant-mix-0000", "MIX.main": "sk-ant-main-0000"}, "never sent the plain value MIX"},
121+
} {
122+
t.Run(c.name, func(t *testing.T) {
123+
dir := t.TempDir()
124+
rules := filepath.Join(dir, "rules.json")
125+
accessPath := filepath.Join(dir, "access.json")
126+
keysPath := filepath.Join(dir, "keys.json")
127+
if err := os.WriteFile(rules, []byte(oldRules(dir, "127.0.0.1:7701")), 0o640); err != nil {
128+
t.Fatal(err)
129+
}
130+
if err := migrate(rules, accessPath, &bytes.Buffer{}); err != nil {
131+
t.Fatal(err)
132+
}
133+
cfg, err := policy.Load(rules)
134+
if err != nil {
135+
t.Fatal(err)
136+
}
137+
access := cfg.AccessList
138+
maps.Copy(access.Services, c.services)
139+
raw, _ := json.MarshalIndent(access, "", " ")
140+
if err := os.WriteFile(accessPath, raw, 0o600); err != nil {
141+
t.Fatal(err)
142+
}
143+
for name, value := range c.keys {
144+
if err := store.Set(keysPath, name, value); err != nil {
145+
t.Fatal(err)
146+
}
147+
}
148+
_, err = loadConfig(rules, keysPath, true, &bytes.Buffer{})
149+
if err == nil || !strings.Contains(err.Error(), c.want) {
150+
t.Fatalf("start: %v", err)
151+
}
152+
if now, _ := os.ReadFile(accessPath); !bytes.Equal(now, raw) {
153+
t.Fatal("the access file was changed")
154+
}
155+
if _, err := os.Stat(metaPathOf(keysPath)); err == nil {
156+
t.Fatal("the key notes were written")
157+
}
158+
})
159+
}
160+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.