feat: teai role

This commit is contained in:
ydc3148
2026-09-14 16:13:02 +08:00
parent 8735e35db6
commit 540718dda7
12 changed files with 416 additions and 120 deletions
+28 -29
View File
@@ -1,7 +1,7 @@
// auth.go — 認證來源的解析與選序。
//
// 選序(README「全域介面」):--token 旗標 → TEAI_TOKEN 環境變數 →
// tea 登入組態(TEA_CONFIG 指定的路徑,或 ~/.config/tea/config.yml)。
// teai 登入組態(TEAI_CONFIG 指定的路徑,或 ~/.config/teai/config.yml)。
// token 一律只在記憶體傳遞,不寫入輸出、日誌或錯誤訊息。
package gitea
@@ -23,8 +23,8 @@ const (
SourceFlag
// SourceEnv 是 TEAI_TOKEN 環境變數。
SourceEnv
// SourceTeaConfig 是 tea 登入組態。
SourceTeaConfig
// SourceConfig 是 teai 登入組態。
SourceConfig
)
// String 回傳來源名稱(診斷用)。
@@ -34,8 +34,8 @@ func (s TokenSource) String() string {
return "flag"
case SourceEnv:
return "env"
case SourceTeaConfig:
return "tea-config"
case SourceConfig:
return "config"
default:
return "none"
}
@@ -62,12 +62,12 @@ func osReadFile(path string) ([]byte, error) {
type AuthOptions struct {
// FlagToken 是 --token 旗標值;空字串表示未提供。
FlagToken string
// SiteURL 是目標站點(用來比對 tea 組態中的 login url)。
// SiteURL 是目標站點(用來比對組態中的 login url)。
SiteURL string
// Env 是環境變數查詢;nil 時用 os.LookupEnv。
Env EnvLookup
// ConfigPath 是 tea 組態的明確路徑(TEA_CONFIG 或 --config)。
// 空字串表示用預設 ~/.config/tea/config.yml。
// ConfigPath 是 teai 組態的明確路徑(TEAI_CONFIG 或 --config)。
// 空字串表示用預設 ~/.config/teai/config.yml。
ConfigPath string
// Home 是使用者家目錄(展開 ~ 用);空字串表示不展開。
Home string
@@ -75,7 +75,7 @@ type AuthOptions struct {
ReadFile ReadFileFunc
}
// ResolveToken 依選序解析 token:flag → env(TEAI_TOKEN) → tea 組態。
// ResolveToken 依選序解析 token:flag → env(TEAI_TOKEN) → teai 組態。
//
// 找不到任何 token 時回傳 ("", SourceNone, nil)——查詢公開端點不需要
// token,是否為錯由呼叫端依情境決定。組態檔存在但解析失敗(格式錯誤)
@@ -93,8 +93,8 @@ func ResolveToken(opts AuthOptions) (string, TokenSource, error) {
}
path := opts.ConfigPath
if path == "" {
// --config 未給時,先看 TEA_CONFIG 環境變數。
if p, ok := env("TEA_CONFIG"); ok && strings.TrimSpace(p) != "" {
// --config 未給時,先看 TEAI_CONFIG 環境變數。
if p, ok := env("TEAI_CONFIG"); ok && strings.TrimSpace(p) != "" {
path = strings.TrimSpace(p)
}
}
@@ -110,7 +110,7 @@ func ResolveToken(opts AuthOptions) (string, TokenSource, error) {
if home == "" {
return "", SourceNone, nil
}
path = filepath.Join(home, ".config", "tea", "config.yml")
path = filepath.Join(home, ".config", "teai", "config.yml")
}
if path == "" {
return "", SourceNone, nil
@@ -124,33 +124,32 @@ func ResolveToken(opts AuthOptions) (string, TokenSource, error) {
// 組態不存在或讀不到:視為沒有這個來源,不是錯誤。
return "", SourceNone, nil
}
login, err := parseTeaConfig(data, opts.SiteURL)
login, err := parseConfig(data, opts.SiteURL)
if err != nil {
return "", SourceNone, fmt.Errorf("gitea: parse tea config %s: %w", path, err)
return "", SourceNone, fmt.Errorf("gitea: parse config %s: %w", path, err)
}
if login.Token == "" {
return "", SourceNone, nil
}
return login.Token, SourceTeaConfig, nil
return login.Token, SourceConfig, nil
}
// teaLogin 是 tea 組態中一筆登入資料(只取 teai 需要的欄位)。
type teaLogin struct {
// configLogin 是組態中一筆登入資料(只取解析 token 需要的欄位)。
type configLogin struct {
Name string
URL string
Token string
Default bool
}
// parseTeaConfig 從 tea 的 config.yml 內容挑出最匹配 siteURL 的登入:
// parseConfig 從 teai 的 config.yml 內容挑出最匹配 siteURL 的登入:
// url 主機相同者優先,其中 default: true 最優,否則取第一筆;
// 都不相同時退而取 default: true,再退第一筆。
//
// 僅解析 tea 實際寫出的 YAML 子集:頂層 `logins:` 清單,項目為
// `key: value` 的平面映射。不處理錨點、多文件、巢狀清單——tea 不會寫出
// 這些,遇到也不該默默誤讀。
func parseTeaConfig(data []byte, siteURL string) (teaLogin, error) {
var logins []teaLogin
// 僅解析 teai 寫出的 YAML 子集:頂層 `logins:` 清單,項目為
// `key: value` 的平面映射。不處理錨點、多文件、巢狀清單。
func parseConfig(data []byte, siteURL string) (configLogin, error) {
var logins []configLogin
inLogins := false
cur := -1 // 目前項目在 logins 的索引;-1 表示尚未開始任何項目
for lineNo, raw := range strings.Split(string(data), "\n") {
@@ -171,26 +170,26 @@ func parseTeaConfig(data []byte, siteURL string) (teaLogin, error) {
}
if strings.HasPrefix(trimmed, "- ") || trimmed == "-" {
// 新的清單項目;`- name: x` 形式同行帶鍵值。
logins = append(logins, teaLogin{})
logins = append(logins, configLogin{})
cur = len(logins) - 1
rest := strings.TrimSpace(strings.TrimPrefix(trimmed, "-"))
if rest != "" {
if err := applyLoginField(&logins[cur], rest, lineNo+1); err != nil {
return teaLogin{}, err
return configLogin{}, err
}
}
continue
}
if cur < 0 {
// logins: 底下卻不是清單項目——不是預期的結構。
return teaLogin{}, fmt.Errorf("line %d: expected list item under logins:", lineNo+1)
return configLogin{}, fmt.Errorf("line %d: expected list item under logins:", lineNo+1)
}
if err := applyLoginField(&logins[cur], trimmed, lineNo+1); err != nil {
return teaLogin{}, err
return configLogin{}, err
}
}
if len(logins) == 0 {
return teaLogin{}, nil
return configLogin{}, nil
}
wantHost := hostOf(siteURL)
// 第一輪:主機相符者,default 優先,否則第一筆。
@@ -219,7 +218,7 @@ func parseTeaConfig(data []byte, siteURL string) (teaLogin, error) {
}
// applyLoginField 把 `key: value` 套用到 login;value 的引號會剝除。
func applyLoginField(l *teaLogin, kv string, lineNo int) error {
func applyLoginField(l *configLogin, kv string, lineNo int) error {
key, value, ok := strings.Cut(kv, ":")
if !ok {
return fmt.Errorf("line %d: expected key: value, got %q", lineNo, kv)
+41 -23
View File
@@ -1,5 +1,5 @@
// auth_test.go 驗證認證來源選序(--token → TEAI_TOKEN → tea 組態)
// 與 tea 組態解析。
// auth_test.go 驗證認證來源選序(--token → TEAI_TOKEN → teai 組態)
// 與組態解析。
package gitea
import (
@@ -25,7 +25,7 @@ func fakeReadFile(m map[string]string) ReadFileFunc {
}
}
const sampleTeaConfig = `logins:
const sampleConfig = `logins:
- name: other.example.com
url: https://other.example.com
token: other-token
@@ -43,7 +43,7 @@ func TestResolveTokenOrdering(t *testing.T) {
SiteURL: "https://gitea.alterminal.com",
Env: fakeEnv(nil),
ReadFile: fakeReadFile(map[string]string{
"/cfg/config.yml": sampleTeaConfig,
"/cfg/config.yml": sampleConfig,
}),
ConfigPath: "/cfg/config.yml",
}
@@ -67,11 +67,11 @@ func TestResolveTokenOrdering(t *testing.T) {
}
})
t.Run("tea config used when flag and env absent", func(t *testing.T) {
t.Run("config used when flag and env absent", func(t *testing.T) {
opts := base
tok, src, err := ResolveToken(opts)
if err != nil || tok != "site-token" || src != SourceTeaConfig {
t.Fatalf("want site-token/tea-config, got %q/%v (err %v)", tok, src, err)
if err != nil || tok != "site-token" || src != SourceConfig {
t.Fatalf("want site-token/config, got %q/%v (err %v)", tok, src, err)
}
})
@@ -88,8 +88,8 @@ func TestResolveTokenOrdering(t *testing.T) {
opts := base
opts.Env = fakeEnv(map[string]string{"TEAI_TOKEN": " "})
tok, src, err := ResolveToken(opts)
if err != nil || tok != "site-token" || src != SourceTeaConfig {
t.Fatalf("want site-token/tea-config, got %q/%v (err %v)", tok, src, err)
if err != nil || tok != "site-token" || src != SourceConfig {
t.Fatalf("want site-token/config, got %q/%v (err %v)", tok, src, err)
}
})
@@ -103,36 +103,54 @@ func TestResolveTokenOrdering(t *testing.T) {
}
})
t.Run("TEA_CONFIG points config path", func(t *testing.T) {
t.Run("TEAI_CONFIG points config path", func(t *testing.T) {
opts := base
opts.ConfigPath = "" // 不用 --config,改用 TEA_CONFIG
opts.ConfigPath = "" // 不用 --config,改用 TEAI_CONFIG
opts.Env = fakeEnv(map[string]string{
"TEA_CONFIG": "/cfg/config.yml",
"TEAI_CONFIG": "/cfg/config.yml",
})
tok, src, err := ResolveToken(opts)
if err != nil || tok != "site-token" || src != SourceTeaConfig {
t.Fatalf("want site-token/tea-config via TEA_CONFIG, got %q/%v (err %v)", tok, src, err)
if err != nil || tok != "site-token" || src != SourceConfig {
t.Fatalf("want site-token/config via TEAI_CONFIG, got %q/%v (err %v)", tok, src, err)
}
})
t.Run("explicit --config beats TEA_CONFIG", func(t *testing.T) {
t.Run("explicit --config beats TEAI_CONFIG", func(t *testing.T) {
opts := base // ConfigPath = /cfg/config.yml(有 site-token)
opts.Env = fakeEnv(map[string]string{
"TEA_CONFIG": "/cfg/other.yml",
"TEAI_CONFIG": "/cfg/other.yml",
})
read := fakeReadFile(map[string]string{
"/cfg/config.yml": sampleTeaConfig,
"/cfg/config.yml": sampleConfig,
"/cfg/other.yml": "logins:\n - name: x\n url: https://gitea.alterminal.com\n token: other\n default: true\n",
})
opts.ReadFile = read
tok, src, err := ResolveToken(opts)
if err != nil || tok != "site-token" || src != SourceTeaConfig {
if err != nil || tok != "site-token" || src != SourceConfig {
t.Fatalf("want site-token from explicit config, got %q/%v (err %v)", tok, src, err)
}
})
t.Run("TEA_CONFIG is ignored", func(t *testing.T) {
opts := AuthOptions{
SiteURL: "https://gitea.alterminal.com",
Env: fakeEnv(map[string]string{
"TEA_CONFIG": "/cfg/config.yml",
}),
ReadFile: fakeReadFile(map[string]string{
"/cfg/config.yml": sampleConfig,
"/home/.config/teai/config.yml": "logins:\n - name: x\n url: https://gitea.alterminal.com\n token: teai-token\n default: true\n",
}),
Home: "/home",
}
tok, src, err := ResolveToken(opts)
if err != nil || tok != "teai-token" || src != SourceConfig {
t.Fatalf("want teai-token from teai config, got %q/%v (err %v)", tok, src, err)
}
})
}
func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
func TestParseConfigPicksMatchingLogin(t *testing.T) {
t.Run("host match preferred over default", func(t *testing.T) {
cfg := `logins:
- name: other
@@ -144,7 +162,7 @@ func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
token: right-token
default: false
`
login, err := parseTeaConfig([]byte(cfg), "https://gitea.alterminal.com")
login, err := parseConfig([]byte(cfg), "https://gitea.alterminal.com")
if err != nil {
t.Fatalf("parse error: %v", err)
}
@@ -155,7 +173,7 @@ func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
t.Run("quoted token unquoted", func(t *testing.T) {
cfg := "logins:\n - name: t\n url: https://gitea.alterminal.com\n token: \"quoted-token\"\n default: true\n"
login, err := parseTeaConfig([]byte(cfg), "https://gitea.alterminal.com")
login, err := parseConfig([]byte(cfg), "https://gitea.alterminal.com")
if err != nil {
t.Fatalf("parse error: %v", err)
}
@@ -166,14 +184,14 @@ func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
t.Run("malformed login entry errors", func(t *testing.T) {
cfg := "logins:\n - name: t\n url: https://gitea.alterminal.com\n oops\n"
if _, err := parseTeaConfig([]byte(cfg), ""); err == nil {
if _, err := parseConfig([]byte(cfg), ""); err == nil {
t.Fatal("malformed line should error")
}
})
t.Run("no logins yields empty", func(t *testing.T) {
cfg := "preferences:\n editor: false\n"
login, err := parseTeaConfig([]byte(cfg), "")
login, err := parseConfig([]byte(cfg), "")
if err != nil || login.Token != "" {
t.Fatalf("want empty login, got %+v (err %v)", login, err)
}
+11 -20
View File
@@ -1,9 +1,8 @@
// config.go — tea 相容登入組態的讀取與行級編輯。
// config.go — teai 登入組態的讀取與行級編輯。
//
// teai 與 tea 共用同一份組態檔(README 設計原則 5),因此寫入採「行級編輯」:
// 只修改目標登入項目的所屬行,其餘內容(未知欄位、註解、preferences 區段、
// 空行與縮排)逐字保留,避免改壞 tea 也在使用的檔案。新增項目依 tea 實際
// 寫出的欄位順序輸出,讓檔案外觀與 tea 一致。
// 組態由 teai 自行管理(README 設計原則 5),不依賴 tea。寫入採「行級編輯」:
// 只修改目標登入項目的所屬行,其餘內容(未知欄位、註解、空行與縮排)逐字
// 保留。新增項目只寫 teai 使用的欄位:name/url/token/default/user。
//
// token 值只會進出這個套件的資料結構與組態檔本身,永遠不出現在錯誤訊息。
package gitea
@@ -18,7 +17,7 @@ import (
"strings"
)
// LoginEntry 是組態檔中的一筆登入資料(編輯用,含 tea 的 user 欄位)。
// LoginEntry 是組態檔中的一筆登入資料(編輯用,含 user 欄位)。
type LoginEntry struct {
Name string
URL string
@@ -43,7 +42,7 @@ type configDoc struct {
}
// parseConfigDoc 掃描組態內容,定位 logins 清單與各項目的行範圍。
// 只認識 tea 實際寫出的格式:頂層 `logins:` 加縮排的 `- key: value` 項目;
// 只認識 teai 寫出的格式:頂層 `logins:` 加縮排的 `- key: value` 項目;
// 其餘行原樣保留在 lines 中。
func parseConfigDoc(data []byte) configDoc {
doc := configDoc{lines: splitLines(data), loginsHeader: -1, itemIndent: " "}
@@ -103,7 +102,7 @@ func (d configDoc) findItem(name string) int {
return -1
}
// fieldIndent 回傳項目內屬性行的縮排(項目縮排 + 兩格,tea 的格式)。
// fieldIndent 回傳項目內屬性行的縮排(項目縮排 + 兩格)。
func (d configDoc) fieldIndent() string {
return d.itemIndent + " "
}
@@ -168,7 +167,7 @@ func ListLoginsFile(path string) ([]LoginEntry, error) {
// UpsertLogin 新增或更新名為 e.Name 的登入。
//
// 已存在則就地更新 url/token/user/default(保留其他欄位與行);不存在則
// 依 tea 的欄位順序插入新項目。makeDefault 為 true 時將其設為預設並取消
// 依 teai 的欄位順序插入新項目。makeDefault 為 true 時將其設為預設並取消
// 其他登入的預設旗標;新增後若成為唯一登入也自動成為預設。
// 回傳新內容與最終生效的項目值。
func UpsertLogin(data []byte, e LoginEntry, makeDefault bool) ([]byte, LoginEntry, error) {
@@ -326,7 +325,7 @@ func setFieldInItem(lines []string, it loginItemSpan, key, value, fieldIndent st
return append(out, lines[it.end:]...)
}
// newLoginBlock 產生 tea 格式的新登入項目(欄位順序與 tea 實際寫出的一致)。
// newLoginBlock 產生 teai 格式的新登入項目(name/url/token/default/user)。
func newLoginBlock(itemIndent, name, url, token string, isDefault bool, user string) []string {
f := itemIndent + " "
return []string{
@@ -334,15 +333,7 @@ func newLoginBlock(itemIndent, name, url, token string, isDefault bool, user str
f + "url: " + yamlScalar(url),
f + "token: " + yamlScalar(token),
f + "default: " + strconv.FormatBool(isDefault),
f + `ssh_host: ""`,
f + `ssh_key: ""`,
f + "insecure: false",
f + `ssh_certificate_principal: ""`,
f + "ssh_agent: false",
f + `ssh_key_agent_pub: ""`,
f + "version_check: false",
f + "user: " + yamlScalar(user),
f + "created: 0",
}
}
@@ -385,9 +376,9 @@ func joinLines(lines []string) []byte {
return []byte(s)
}
// SaveTeaConfigFile 把組態內容原子寫入 path:先寫同目錄暫存檔(0600),
// SaveConfigFile 把組態內容原子寫入 path:先寫同目錄暫存檔(0600),
// 再 rename 取代,避免半寫入狀態。必要時建立上層目錄(0700)。
func SaveTeaConfigFile(path string, data []byte) error {
func SaveConfigFile(path string, data []byte) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o700); err != nil {
return fmt.Errorf("gitea: create config dir: %w", err)
+25 -14
View File
@@ -1,4 +1,4 @@
// config_test.go 驗證 tea 相容組態的行級編輯:新增、更新、設預設、
// config_test.go 驗證登入組態的行級編輯:新增、更新、設預設、
// 移除,以及「未知欄位與其他區段逐字保留」的關鍵性質。
package gitea
@@ -10,8 +10,8 @@ import (
"testing"
)
// realWorldTeaConfig 是 tea 實際寫出的組態(含 ssh_* 等未知欄位與 preferences)。
const realWorldTeaConfig = `logins:
// extraFieldsConfig 含未知欄位與額外區段,用來驗證行級編輯不會改壞不相干內容。
const extraFieldsConfig = `logins:
- name: alterminal
url: https://gitea.alterminal.com
token: tok-1
@@ -32,7 +32,7 @@ preferences:
`
func TestListLoginsParsesAllEntries(t *testing.T) {
logins := ListLogins([]byte(realWorldTeaConfig))
logins := ListLogins([]byte(extraFieldsConfig))
if len(logins) != 1 {
t.Fatalf("want 1 login, got %d", len(logins))
}
@@ -43,7 +43,7 @@ func TestListLoginsParsesAllEntries(t *testing.T) {
}
func TestUpsertLoginUpdatesExistingPreservesRest(t *testing.T) {
out, final, err := UpsertLogin([]byte(realWorldTeaConfig), LoginEntry{
out, final, err := UpsertLogin([]byte(extraFieldsConfig), LoginEntry{
Name: "alterminal", URL: "https://gitea.alterminal.com", Token: "tok-2", User: "ceo",
}, false)
if err != nil {
@@ -74,7 +74,7 @@ func TestUpsertLoginUpdatesExistingPreservesRest(t *testing.T) {
}
func TestUpsertLoginAppendsNewAndMakesDefault(t *testing.T) {
out, final, err := UpsertLogin([]byte(realWorldTeaConfig), LoginEntry{
out, final, err := UpsertLogin([]byte(extraFieldsConfig), LoginEntry{
Name: "second", URL: "https://git.example.com", Token: "tok-b", User: "bob",
}, true)
if err != nil {
@@ -93,10 +93,15 @@ func TestUpsertLoginAppendsNewAndMakesDefault(t *testing.T) {
if !final.Default {
t.Fatalf("final should be default: %+v", final)
}
// tea 的欄位順序仍在。
// 新項目依 teai 欄位順序附加。
s := string(out)
if !strings.Contains(s, " - name: second\n") {
t.Fatalf("new item not appended in tea style:\n%s", s)
t.Fatalf("new item not appended:\n%s", s)
}
for _, ban := range []string{"ssh_", "insecure:", "version_check:", "created:"} {
if strings.Contains(s[strings.Index(s, "- name: second"):], ban) {
t.Fatalf("new item leaked tea field %q:\n%s", ban, s)
}
}
}
@@ -117,6 +122,12 @@ func TestUpsertLoginFirstEverLoginCreatesSection(t *testing.T) {
if !strings.HasPrefix(string(out), "logins:\n") {
t.Fatalf("section not created:\n%s", out)
}
s := string(out)
for _, ban := range []string{"ssh_", "insecure:", "version_check:", "created:", "preferences:"} {
if strings.Contains(s, ban) {
t.Fatalf("new config leaked tea field %q:\n%s", ban, s)
}
}
}
func TestUpsertLoginRejectsBadInput(t *testing.T) {
@@ -158,7 +169,7 @@ func TestSetDefaultLoginSwitchesFlag(t *testing.T) {
}
func TestSetDefaultLoginUnknownNameErrors(t *testing.T) {
if _, err := SetDefaultLogin([]byte(realWorldTeaConfig), "nope"); err == nil {
if _, err := SetDefaultLogin([]byte(extraFieldsConfig), "nope"); err == nil {
t.Fatal("unknown name should error")
}
}
@@ -195,7 +206,7 @@ preferences:
}
func TestRemoveLoginLastOne(t *testing.T) {
out, promoted, err := RemoveLogin([]byte(realWorldTeaConfig), "alterminal")
out, promoted, err := RemoveLogin([]byte(extraFieldsConfig), "alterminal")
if err != nil || promoted != "" {
t.Fatalf("want clean removal, promoted=%q err=%v", promoted, err)
}
@@ -207,10 +218,10 @@ func TestRemoveLoginLastOne(t *testing.T) {
}
}
func TestSaveTeaConfigFileAtomicAndMode(t *testing.T) {
func TestSaveConfigFileAtomicAndMode(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "tea", "config.yml")
if err := SaveTeaConfigFile(path, []byte("logins: []\n")); err != nil {
path := filepath.Join(dir, "teai", "config.yml")
if err := SaveConfigFile(path, []byte("logins: []\n")); err != nil {
t.Fatal(err)
}
info, err := os.Stat(path)
@@ -221,7 +232,7 @@ func TestSaveTeaConfigFileAtomicAndMode(t *testing.T) {
t.Fatalf("perm = %v, want 0600", info.Mode().Perm())
}
// 再寫一次(覆蓋既有檔),不留暫存殘檔。
if err := SaveTeaConfigFile(path, []byte("logins: []\n# v2\n")); err != nil {
if err := SaveConfigFile(path, []byte("logins: []\n# v2\n")); err != nil {
t.Fatal(err)
}
entries, _ := os.ReadDir(filepath.Dir(path))