feat: v0 — glpi-go client, mglpi CLI, mglpi-mcp, fake-GLPI test suite [#767]
https://projects.knownelement.com/issues/767#note-4191
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
// Package cli implements the mglpi command line: a thin, machine-friendly
|
||||
// front end over the glpi library. Connection settings come from
|
||||
// MGLPI_URL / MGLPI_APP_TOKEN / MGLPI_USER_TOKEN env vars (plus optional
|
||||
// MGLPI_PROFILE_ID for agent mode) or a 0600 --config env file — tokens
|
||||
// are never flag values and never logged. Every command accepts -o json
|
||||
// for machine output. Exit codes: 0 ok, 1 usage/config, 2 API error
|
||||
// (single-line stderr carrying the http status, parseable).
|
||||
package cli
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/config"
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
|
||||
)
|
||||
|
||||
const usage = `mglpi: GLPI/CMDB CLI (stdlib-only, library-backed)
|
||||
|
||||
Usage:
|
||||
mglpi whoami [-o json]
|
||||
mglpi change create --title T [--urgency N] [--impact N] [--profile N]
|
||||
[--content FILE|-] [-o json]
|
||||
mglpi change show ID [-o json]
|
||||
mglpi change list [--status N|NAME] [-o json]
|
||||
mglpi change transition ID STATUS (STATUS numeric or: new evaluation
|
||||
approval test qualification waiting accepted assigned
|
||||
planned pending solved closed) [-o json]
|
||||
mglpi change followup ID [--content FILE|-] [-o json]
|
||||
mglpi ci search TYPE TERM [-o json]
|
||||
mglpi ci show TYPE ID [-o json]
|
||||
mglpi help
|
||||
|
||||
Connection: MGLPI_URL + MGLPI_APP_TOKEN + MGLPI_USER_TOKEN env vars, or
|
||||
--config PATH pointing at a 0600 env file with the same keys. Tokens
|
||||
never appear in flags, logs, or error output.
|
||||
|
||||
Agent mode: --profile N (or MGLPI_PROFILE_ID in the env file) switches
|
||||
the session's active profile (e.g. 5 = Hotliner) right after
|
||||
InitSession — servers that gate operations per profile then accept the
|
||||
calls. whoami never switches.
|
||||
|
||||
change create / change followup read their body from stdin by default
|
||||
(--content FILE to read a file instead).
|
||||
|
||||
Exit codes: 0 ok, 1 usage/config error, 2 API error (stderr: one line,
|
||||
"http NNN" included).`
|
||||
|
||||
// Run executes one command; it returns the process exit code.
|
||||
func Run(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprint(stderr, usage)
|
||||
return 1
|
||||
}
|
||||
// Hoist a leading global --config PATH onto the subcommand (the
|
||||
// subcommand flag sets already accept it anywhere).
|
||||
var hoisted []string
|
||||
for len(args) >= 2 && (args[0] == "--config" || args[0] == "-config") {
|
||||
hoisted = append(hoisted, args[0], args[1])
|
||||
args = args[2:]
|
||||
}
|
||||
if len(hoisted) > 0 {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprint(stderr, usage)
|
||||
return 1
|
||||
}
|
||||
args = append(args, hoisted...)
|
||||
}
|
||||
switch args[0] {
|
||||
case "help", "-h", "--help":
|
||||
fmt.Fprint(stdout, usage)
|
||||
return 0
|
||||
case "whoami":
|
||||
return cmdWhoami(args[1:], stdout, stderr)
|
||||
case "change":
|
||||
return cmdChange(args[1:], stdout, stderr)
|
||||
case "ci":
|
||||
return cmdCI(args[1:], stdout, stderr)
|
||||
default:
|
||||
fmt.Fprintf(stderr, "mglpi: unknown command %q\n\n%s\n", args[0], usage)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
// newFlags builds a quiet flag set with the shared --config and -o flags.
|
||||
func newFlags(name string, stderr io.Writer) (*flag.FlagSet, *string, *string) {
|
||||
fs := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
fs.SetOutput(io.Discard)
|
||||
cfg := fs.String("config", "", "env file with MGLPI_URL/MGLPI_APP_TOKEN/MGLPI_USER_TOKEN (must be 0600)")
|
||||
out := fs.String("o", "text", "output format: text|json")
|
||||
return fs, cfg, out
|
||||
}
|
||||
|
||||
// parseArgs parses flags that may appear AFTER positionals (the standard
|
||||
// flag package stops at the first positional; mglpi's documented surface
|
||||
// is "change show ID -o json", "ci search TYPE TERM"). It returns the
|
||||
// positional arguments.
|
||||
func parseArgs(fs *flag.FlagSet, args []string) ([]string, error) {
|
||||
var positionals []string
|
||||
rest := args
|
||||
for {
|
||||
if err := fs.Parse(rest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
got := fs.Args()
|
||||
i := 0
|
||||
for i < len(got) && (got[i] == "-" || !strings.HasPrefix(got[i], "-")) {
|
||||
i++
|
||||
}
|
||||
positionals = append(positionals, got[:i]...)
|
||||
if i == len(got) {
|
||||
return positionals, nil
|
||||
}
|
||||
rest = got[i:]
|
||||
}
|
||||
}
|
||||
|
||||
// client resolves config (env + optional 0600 file) and builds the
|
||||
// client, resolving the effective agent profile (flag wins over the
|
||||
// MGLPI_PROFILE_ID config key). A non-nil error means exit 1; profile
|
||||
// application (an API op) surfaces later as exit 2.
|
||||
func client(cfgPath string, profileFlag int) (*glpi.Client, int, error) {
|
||||
if cfgPath == "" {
|
||||
cfgPath = os.Getenv("MGLPI_CONFIG")
|
||||
}
|
||||
if cfgPath == "" {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
cand := filepath.Join(home, ".config", "mglpi", "env")
|
||||
if _, err := os.Stat(cand); err == nil {
|
||||
cfgPath = cand
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg, _, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
profile := profileFlag
|
||||
if profile == 0 {
|
||||
profile = cfg.ProfileID
|
||||
}
|
||||
return glpi.New(glpi.Config{
|
||||
BaseURL: cfg.BaseURL,
|
||||
AppToken: cfg.AppToken,
|
||||
UserToken: cfg.UserToken,
|
||||
}), profile, nil
|
||||
}
|
||||
|
||||
// apiErr reports an API failure the mglpi way: one line, exit 2.
|
||||
func apiErr(stderr io.Writer, err error) int {
|
||||
fmt.Fprintf(stderr, "mglpi: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
|
||||
// usageErr reports a usage/config failure: one line, exit 1.
|
||||
func usageErr(stderr io.Writer, format string, args ...any) int {
|
||||
fmt.Fprintf(stderr, "mglpi: "+format+"\n", args...)
|
||||
return 1
|
||||
}
|
||||
|
||||
// emitJSON pretty-prints v for -o json.
|
||||
func emitJSON(stdout io.Writer, v any) {
|
||||
b, err := marshalIndent(v)
|
||||
if err != nil {
|
||||
return // library types are JSON-clean by construction
|
||||
}
|
||||
stdout.Write(b)
|
||||
fmt.Fprintln(stdout)
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/fakeglpi"
|
||||
)
|
||||
|
||||
const (
|
||||
testApp = "fake-app-token-0123456789"
|
||||
testUser = "fake-user-token-0123456789"
|
||||
)
|
||||
|
||||
func boot(t *testing.T) *fakeglpi.Server {
|
||||
t.Helper()
|
||||
srv := fakeglpi.New(testApp, testUser)
|
||||
t.Cleanup(srv.Close)
|
||||
t.Setenv("MGLPI_URL", srv.URL)
|
||||
t.Setenv("MGLPI_APP_TOKEN", testApp)
|
||||
t.Setenv("MGLPI_USER_TOKEN", testUser)
|
||||
t.Setenv("MGLPI_PROFILE_ID", "")
|
||||
return srv
|
||||
}
|
||||
|
||||
func run(t *testing.T, args ...string) (string, string, int) {
|
||||
t.Helper()
|
||||
var out, errb strings.Builder
|
||||
code := Run(args, &out, &errb)
|
||||
return out.String(), errb.String(), code
|
||||
}
|
||||
|
||||
func contentFile(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "content.txt")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestUsageErrors(t *testing.T) {
|
||||
boot(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"no args", nil},
|
||||
{"unknown command", []string{"frobnicate"}},
|
||||
{"change alone", []string{"change"}},
|
||||
{"change create without title", []string{"change", "create"}},
|
||||
{"change show without id", []string{"change", "show"}},
|
||||
{"change show non-numeric id", []string{"change", "show", "abc"}},
|
||||
{"change transition bad status name", []string{"change", "transition", "5", "bogus"}},
|
||||
{"change list bad status name", []string{"change", "list", "--status", "bogus"}},
|
||||
{"ci search without term", []string{"ci", "search", "Computer"}},
|
||||
{"ci show without id", []string{"ci", "show", "Computer"}},
|
||||
{"whoami with positional", []string{"whoami", "extra"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
out, errb, code := run(t, tt.args...)
|
||||
if code != 1 {
|
||||
t.Fatalf("code = %d (out %q, err %q), want 1", code, out, errb)
|
||||
}
|
||||
if out != "" {
|
||||
t.Errorf("usage error wrote to stdout: %q", out)
|
||||
}
|
||||
if errb == "" {
|
||||
t.Errorf("no diagnostic on stderr")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigErrorIsExitOne(t *testing.T) {
|
||||
boot(t)
|
||||
t.Setenv("MGLPI_URL", "")
|
||||
t.Setenv("MGLPI_APP_TOKEN", "")
|
||||
t.Setenv("MGLPI_USER_TOKEN", "")
|
||||
_, errb, code := run(t, "change", "list")
|
||||
if code != 1 {
|
||||
t.Fatalf("code = %d, want 1 (config)", code)
|
||||
}
|
||||
if !strings.Contains(errb, "MGLPI_URL") {
|
||||
t.Fatalf("stderr = %q", errb)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhoami(t *testing.T) {
|
||||
boot(t)
|
||||
out, errb, code := run(t, "whoami")
|
||||
if code != 0 {
|
||||
t.Fatalf("code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
for _, want := range []string{"Self-Service", "Hotliner", "Super-admin", "active"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("whoami output missing %q:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
out, _, code = run(t, "whoami", "-o", "json")
|
||||
if code != 0 {
|
||||
t.Fatalf("json whoami code %d", code)
|
||||
}
|
||||
var got struct {
|
||||
Profiles []struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
} `json:"profiles"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &got); err != nil || len(got.Profiles) != 3 {
|
||||
t.Errorf("json whoami = %q err %v", out, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeCreateFullFlags(t *testing.T) {
|
||||
srv := boot(t)
|
||||
content := contentFile(t, "<p>scope body</p>")
|
||||
|
||||
out, errb, code := run(t, "change", "create",
|
||||
"--title", "Quota: per-identity accounting",
|
||||
"--content", content,
|
||||
"--urgency", "3", "--impact", "4",
|
||||
"-o", "json")
|
||||
if code != 0 {
|
||||
t.Fatalf("code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
var got struct {
|
||||
Change struct {
|
||||
ID int `json:"id"`
|
||||
} `json:"change"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &got); err != nil || got.Change.ID == 0 {
|
||||
t.Fatalf("stdout not json: %v (%q)", err, out)
|
||||
}
|
||||
stored, ok := srv.Change(got.Change.ID)
|
||||
if !ok || stored.Name != "Quota: per-identity accounting" || stored.Content != "<p>scope body</p>" ||
|
||||
stored.Urgency != 3 || stored.Impact != 4 || stored.Status != fakeglpi.StatusNew {
|
||||
t.Errorf("stored = %+v", stored)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeCreateRequiresTitle(t *testing.T) {
|
||||
boot(t)
|
||||
_, errb, code := run(t, "change", "create")
|
||||
if code != 1 || !strings.Contains(errb, "--title") {
|
||||
t.Fatalf("code = %d stderr = %q, want usage naming --title", code, errb)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeList(t *testing.T) {
|
||||
srv := boot(t)
|
||||
open := srv.AddChange(fakeglpi.Change{Name: "open one", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
|
||||
solved := srv.AddChange(fakeglpi.Change{Name: "solved one", Status: fakeglpi.StatusSolved, Urgency: 3, Impact: 3})
|
||||
|
||||
out, errb, code := run(t, "change", "list")
|
||||
if code != 0 {
|
||||
t.Fatalf("code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
if !strings.Contains(out, "open one") || !strings.Contains(out, strconv.Itoa(open)) {
|
||||
t.Errorf("text list = %q", out)
|
||||
}
|
||||
out, _, code = run(t, "change", "list", "--status", "solved")
|
||||
if code != 0 || !strings.Contains(out, "solved one") || strings.Contains(out, "open one") {
|
||||
t.Errorf("status filter = %q code %d", out, code)
|
||||
}
|
||||
out, _, code = run(t, "change", "list", "--status", strconv.Itoa(fakeglpi.StatusNew))
|
||||
if code != 0 || !strings.Contains(out, "open one") || strings.Contains(out, "solved one") {
|
||||
t.Errorf("numeric status filter = %q code %d", out, code)
|
||||
}
|
||||
out, _, code = run(t, "change", "list", "-o", "json")
|
||||
if code != 0 {
|
||||
t.Fatalf("json list code %d", code)
|
||||
}
|
||||
var arr struct {
|
||||
Changes []struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Status int `json:"status"`
|
||||
} `json:"changes"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &arr); err != nil || len(arr.Changes) != 2 || arr.Changes[0].ID != open || arr.Changes[1].Status != fakeglpi.StatusSolved {
|
||||
t.Errorf("json list = %q err %v", out, err)
|
||||
}
|
||||
_ = solved
|
||||
}
|
||||
|
||||
func TestChangeShow(t *testing.T) {
|
||||
srv := boot(t)
|
||||
id := srv.AddChange(fakeglpi.Change{Name: "shown change", Content: "body text", Status: fakeglpi.StatusAssigned, Urgency: 4, Impact: 3})
|
||||
|
||||
out, errb, code := run(t, "change", "show", strconv.Itoa(id))
|
||||
if code != 0 {
|
||||
t.Fatalf("code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
for _, want := range []string{strconv.Itoa(id), "shown change", "body text", "assigned", "4"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("show output missing %q:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
out, _, code = run(t, "change", "show", strconv.Itoa(id), "-o", "json")
|
||||
if code != 0 {
|
||||
t.Fatalf("json show code %d", code)
|
||||
}
|
||||
var got struct {
|
||||
Change struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Content string `json:"content"`
|
||||
Status int `json:"status"`
|
||||
} `json:"change"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &got); err != nil || got.Change.Name != "shown change" || got.Change.Status != fakeglpi.StatusAssigned {
|
||||
t.Errorf("json show = %q err %v", out, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeTransition(t *testing.T) {
|
||||
srv := boot(t)
|
||||
id := srv.AddChange(fakeglpi.Change{Name: "flow", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
|
||||
|
||||
out, errb, code := run(t, "change", "transition", strconv.Itoa(id), "solved")
|
||||
if code != 0 {
|
||||
t.Fatalf("code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
if !strings.Contains(out, strconv.Itoa(id)) {
|
||||
t.Errorf("confirmation = %q", out)
|
||||
}
|
||||
if got, _ := srv.Change(id); got.Status != fakeglpi.StatusSolved {
|
||||
t.Errorf("stored status = %d, want solved", got.Status)
|
||||
}
|
||||
out, errb, code = run(t, "change", "transition", strconv.Itoa(id), strconv.Itoa(fakeglpi.StatusClosed))
|
||||
if code != 0 {
|
||||
t.Fatalf("numeric transition code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
if got, _ := srv.Change(id); got.Status != fakeglpi.StatusClosed {
|
||||
t.Errorf("stored status = %d, want closed", got.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeFollowup(t *testing.T) {
|
||||
srv := boot(t)
|
||||
id := srv.AddChange(fakeglpi.Change{Name: "with note", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
|
||||
content := contentFile(t, "REPORT delivered: see inbox")
|
||||
|
||||
out, errb, code := run(t, "change", "followup", strconv.Itoa(id), "--content", content)
|
||||
if code != 0 {
|
||||
t.Fatalf("code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
if !strings.Contains(out, strconv.Itoa(id)) {
|
||||
t.Errorf("confirmation = %q", out)
|
||||
}
|
||||
fups := srv.Followups(id)
|
||||
if len(fups) != 1 || fups[0].Content != "REPORT delivered: see inbox" {
|
||||
t.Errorf("followups = %+v", fups)
|
||||
}
|
||||
|
||||
empty := contentFile(t, "")
|
||||
_, errb, code = run(t, "change", "followup", strconv.Itoa(id), "--content", empty)
|
||||
if code != 1 || !strings.Contains(errb, "content") {
|
||||
t.Errorf("empty followup = code %d stderr %q, want usage error", code, errb)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCISearchAndShow(t *testing.T) {
|
||||
srv := boot(t)
|
||||
web := srv.AddItem("Computer", map[string]any{"name": "web-01", "serial": "ABC123"})
|
||||
|
||||
out, errb, code := run(t, "ci", "search", "Computer", "web")
|
||||
if code != 0 {
|
||||
t.Fatalf("code = %d, stderr = %q", code, errb)
|
||||
}
|
||||
if !strings.Contains(out, "web-01") || !strings.Contains(out, strconv.Itoa(web)) {
|
||||
t.Errorf("search = %q", out)
|
||||
}
|
||||
out, _, code = run(t, "ci", "search", "Computer", "web", "-o", "json")
|
||||
if code != 0 {
|
||||
t.Fatalf("json search code %d", code)
|
||||
}
|
||||
var arr struct {
|
||||
Results []struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"results"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &arr); err != nil || len(arr.Results) != 1 || arr.Results[0].Name != "web-01" {
|
||||
t.Errorf("json search = %q err %v", out, err)
|
||||
}
|
||||
|
||||
out, _, code = run(t, "ci", "show", "Computer", strconv.Itoa(web), "-o", "json")
|
||||
if code != 0 {
|
||||
t.Fatalf("ci show code = %d", code)
|
||||
}
|
||||
var raw map[string]any
|
||||
if err := json.Unmarshal([]byte(out), &raw); err != nil || raw["serial"] != "ABC123" {
|
||||
t.Errorf("ci show = %q err %v", out, err)
|
||||
}
|
||||
if _, errb, code := run(t, "ci", "show", "Computer", "424242"); code != 2 || !strings.Contains(errb, "http 404") {
|
||||
t.Errorf("missing ci = code %d stderr %q, want exit 2 http 404", code, errb)
|
||||
}
|
||||
}
|
||||
|
||||
// THE agent-mode CLI proof: the fake rejects change creation unless the
|
||||
// session's active profile is 5; --profile and MGLPI_PROFILE_ID both
|
||||
// must flip it.
|
||||
func TestProfileSwitchAgentMode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envProfile string
|
||||
flag []string
|
||||
wantCode int
|
||||
}{
|
||||
{"no profile -> rejected", "", nil, 2},
|
||||
{"--profile 5 -> accepted", "", []string{"--profile", "5"}, 0},
|
||||
{"--profile 4 -> rejected", "", []string{"--profile", "4"}, 2},
|
||||
{"env profile 5 -> accepted", "5", nil, 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := boot(t)
|
||||
srv.RequireChangeProfile = 5
|
||||
t.Setenv("MGLPI_PROFILE_ID", tt.envProfile)
|
||||
args := append([]string{"change", "create", "--title", "agent-mode", "--content", "-"}, tt.flag...)
|
||||
out, errb, code := run(t, args...)
|
||||
if code != tt.wantCode {
|
||||
t.Fatalf("code = %d (stderr %q), want %d", code, errb, tt.wantCode)
|
||||
}
|
||||
if tt.wantCode == 0 {
|
||||
if !strings.Contains(out, "created change #") {
|
||||
t.Errorf("out = %q", out)
|
||||
}
|
||||
} else if !strings.Contains(errb, "http 403") {
|
||||
t.Errorf("stderr = %q, want http 403", errb)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIErrorIsExitTwo(t *testing.T) {
|
||||
srv := boot(t)
|
||||
srv.Fail = &fakeglpi.FailSpec{Status: 404, Body: `[{"ERROR_ITEM_NOT_FOUND":"gone %s"}]`}
|
||||
out, errb, code := run(t, "change", "list")
|
||||
if code != 2 {
|
||||
t.Fatalf("code = %d, want 2", code)
|
||||
}
|
||||
if out != "" {
|
||||
t.Errorf("stdout on API error: %q", out)
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(errb, "\n"), "\n")
|
||||
if len(lines) != 1 || !strings.Contains(lines[0], "http 404") {
|
||||
t.Fatalf("stderr = %q, want single parseable line with http 404", errb)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokensNeverPrinted(t *testing.T) {
|
||||
srv := fakeglpi.New(testApp, testUser)
|
||||
t.Cleanup(srv.Close)
|
||||
t.Setenv("MGLPI_URL", srv.URL)
|
||||
t.Setenv("MGLPI_APP_TOKEN", "wrong-app-token")
|
||||
t.Setenv("MGLPI_USER_TOKEN", testUser)
|
||||
t.Setenv("MGLPI_PROFILE_ID", "")
|
||||
_, errb, code := run(t, "change", "list")
|
||||
if code != 2 {
|
||||
t.Fatalf("code = %d, want 2", code)
|
||||
}
|
||||
if strings.Contains(errb, "wrong-app-token") || strings.Contains(errb, testUser) || strings.Contains(errb, testApp) {
|
||||
t.Fatalf("stderr leaks a token: %q", errb)
|
||||
}
|
||||
if strings.Count(errb, "\n") != 1 { // one diagnostic line + trailing newline
|
||||
t.Fatalf("stderr not one line: %q", errb)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpExitsZero(t *testing.T) {
|
||||
boot(t)
|
||||
out, _, code := run(t, "help")
|
||||
if code != 0 || !strings.Contains(out, "change") {
|
||||
t.Fatalf("help code = %d out = %q", code, out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
|
||||
)
|
||||
|
||||
func marshalIndent(v any) ([]byte, error) { return json.MarshalIndent(v, "", " ") }
|
||||
|
||||
// --- whoami -----------------------------------------------------------------
|
||||
|
||||
// cmdWhoami lists the session's profiles. It NEVER switches the active
|
||||
// profile (agent mode's MGLPI_PROFILE_ID is deliberately not applied).
|
||||
func cmdWhoami(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("whoami", stderr)
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 0 {
|
||||
return usageErr(stderr, "whoami: usage: mglpi whoami")
|
||||
}
|
||||
c, _, err := client(*cfgPath, 0)
|
||||
if err != nil {
|
||||
return usageErr(stderr, "%v", err)
|
||||
}
|
||||
profs, err := c.GetMyProfiles(context.Background())
|
||||
if err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
if *out == "json" {
|
||||
emitJSON(stdout, map[string]any{"profiles": profs})
|
||||
return 0
|
||||
}
|
||||
for _, p := range profs {
|
||||
line := fmt.Sprintf("%-6d %s", p.ID, p.Name)
|
||||
if p.IsActive {
|
||||
line += " [active]"
|
||||
}
|
||||
fmt.Fprintln(stdout, line)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// --- change -------------------------------------------------------------------
|
||||
|
||||
func cmdChange(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
return usageErr(stderr, "change: expected list|show|create|transition|followup (see mglpi help)")
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "list":
|
||||
return cmdChangeList(rest, stdout, stderr)
|
||||
case "show":
|
||||
return cmdChangeShow(rest, stdout, stderr)
|
||||
case "create":
|
||||
return cmdChangeCreate(rest, stdout, stderr)
|
||||
case "transition":
|
||||
return cmdChangeTransition(rest, stdout, stderr)
|
||||
case "followup":
|
||||
return cmdChangeFollowup(rest, stdout, stderr)
|
||||
default:
|
||||
return usageErr(stderr, "change: unknown subcommand %q", sub)
|
||||
}
|
||||
}
|
||||
|
||||
// withClient is the common preamble: resolve config + profile, switch
|
||||
// profile when one is set (an API op -> exit 2 on failure), and hand
|
||||
// the client over.
|
||||
func withClient(stderr io.Writer, cfgPath string, profileFlag int, fn func(c *glpi.Client, ctx context.Context) int) int {
|
||||
c, profile, err := client(cfgPath, profileFlag)
|
||||
if err != nil {
|
||||
return usageErr(stderr, "%v", err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if profile > 0 {
|
||||
if err := c.ChangeActiveProfile(ctx, profile); err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
}
|
||||
return fn(c, ctx)
|
||||
}
|
||||
|
||||
func cmdChangeList(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("change list", stderr)
|
||||
status := fs.String("status", "", "filter by status name or numeric id (e.g. new, solved, 1)")
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 0 {
|
||||
return usageErr(stderr, "change list: usage: mglpi change list [--status N|NAME]")
|
||||
}
|
||||
want := 0
|
||||
if *status != "" {
|
||||
if id, ok := glpi.StatusID(*status); ok {
|
||||
want = id
|
||||
} else {
|
||||
n, err := strconv.Atoi(*status)
|
||||
if err != nil || n <= 0 {
|
||||
return usageErr(stderr, "change list: --status must be a status name or positive number, got %q", *status)
|
||||
}
|
||||
want = n
|
||||
}
|
||||
}
|
||||
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
|
||||
rows, err := c.ListChanges(ctx, want)
|
||||
if err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
if *out == "json" {
|
||||
emitJSON(stdout, map[string]any{"changes": rows})
|
||||
return 0
|
||||
}
|
||||
for _, r := range rows {
|
||||
fmt.Fprintf(stdout, "%-6d %-12s %s\n", r.ID, glpi.StatusName(r.Status), r.Name)
|
||||
}
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
func cmdChangeShow(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("change show", stderr)
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 1 {
|
||||
return usageErr(stderr, "change show: usage: mglpi change show ID")
|
||||
}
|
||||
id, err := strconv.Atoi(pos[0])
|
||||
if err != nil {
|
||||
return usageErr(stderr, "change show: ID must be numeric, got %q", pos[0])
|
||||
}
|
||||
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
|
||||
ch, err := c.GetChange(ctx, id)
|
||||
if err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
if *out == "json" {
|
||||
emitJSON(stdout, map[string]any{"change": ch})
|
||||
return 0
|
||||
}
|
||||
printChange(stdout, ch)
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
func printChange(w io.Writer, ch *glpi.Change) {
|
||||
fmt.Fprintf(w, "#%d %s\n", ch.ID, ch.Name)
|
||||
fmt.Fprintf(w, "Status: %-12s Urgency: %d Impact: %d\n", glpi.StatusName(ch.Status), ch.Urgency, ch.Impact)
|
||||
fmt.Fprintf(w, "Created: %s Updated: %s\n", ch.Date, ch.DateMod)
|
||||
if ch.Content != "" {
|
||||
fmt.Fprintln(w)
|
||||
fmt.Fprintln(w, ch.Content)
|
||||
}
|
||||
}
|
||||
|
||||
func cmdChangeCreate(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("change create", stderr)
|
||||
title := fs.String("title", "", "change title (required)")
|
||||
content := fs.String("content", "-", "content body from FILE, or - for stdin")
|
||||
urgency := fs.Int("urgency", 3, "urgency 1..5 (3 = medium)")
|
||||
impact := fs.Int("impact", 3, "impact 1..5 (3 = medium)")
|
||||
profile := fs.Int("profile", 0, "agent profile id to switch to after InitSession (e.g. 5 = Hotliner)")
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 0 || *title == "" {
|
||||
return usageErr(stderr, "change create: usage: mglpi change create --title T [--urgency N] [--impact N] [--profile N] [--content FILE|-]")
|
||||
}
|
||||
if *urgency < 1 || *urgency > 5 || *impact < 1 || *impact > 5 {
|
||||
return usageErr(stderr, "change create: --urgency/--impact must be 1..5")
|
||||
}
|
||||
body := ""
|
||||
if *content != "" {
|
||||
text, err := readBody(*content)
|
||||
if err != nil {
|
||||
return usageErr(stderr, "%v", err)
|
||||
}
|
||||
body = text
|
||||
}
|
||||
return withClient(stderr, *cfgPath, *profile, func(c *glpi.Client, ctx context.Context) int {
|
||||
id, err := c.CreateChange(ctx, *title, body, *urgency, *impact)
|
||||
if err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
if *out == "json" {
|
||||
emitJSON(stdout, map[string]any{"change": map[string]any{"id": id}})
|
||||
return 0
|
||||
}
|
||||
fmt.Fprintf(stdout, "created change #%d\n", id)
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
func cmdChangeTransition(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("change transition", stderr)
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 2 {
|
||||
return usageErr(stderr, "change transition: usage: mglpi change transition ID STATUS")
|
||||
}
|
||||
id, err := strconv.Atoi(pos[0])
|
||||
if err != nil {
|
||||
return usageErr(stderr, "change transition: ID must be numeric, got %q", pos[0])
|
||||
}
|
||||
status, ok := glpi.StatusID(pos[1])
|
||||
if !ok {
|
||||
status, err = strconv.Atoi(pos[1])
|
||||
if err != nil || status <= 0 {
|
||||
return usageErr(stderr, "change transition: STATUS must be a status name or positive number, got %q", pos[1])
|
||||
}
|
||||
}
|
||||
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
|
||||
if err := c.TransitionChange(ctx, id, status); err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
if *out == "json" {
|
||||
ch, err := c.GetChange(ctx, id)
|
||||
if err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
emitJSON(stdout, map[string]any{"change": ch})
|
||||
return 0
|
||||
}
|
||||
fmt.Fprintf(stdout, "updated change #%d (status %s)\n", id, glpi.StatusName(status))
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
func cmdChangeFollowup(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("change followup", stderr)
|
||||
content := fs.String("content", "-", "followup body from FILE, or - for stdin")
|
||||
profile := fs.Int("profile", 0, "agent profile id to switch to after InitSession")
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 1 {
|
||||
return usageErr(stderr, "change followup: usage: mglpi change followup ID [--content FILE|-]")
|
||||
}
|
||||
id, err := strconv.Atoi(pos[0])
|
||||
if err != nil {
|
||||
return usageErr(stderr, "change followup: ID must be numeric, got %q", pos[0])
|
||||
}
|
||||
body := ""
|
||||
if *content != "" {
|
||||
text, err := readBody(*content)
|
||||
if err != nil {
|
||||
return usageErr(stderr, "%v", err)
|
||||
}
|
||||
body = text
|
||||
}
|
||||
if strings.TrimSpace(body) == "" {
|
||||
return usageErr(stderr, "change followup: content is required (stdin or --content FILE)")
|
||||
}
|
||||
return withClient(stderr, *cfgPath, *profile, func(c *glpi.Client, ctx context.Context) int {
|
||||
if err := c.AddFollowup(ctx, id, body); err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
if *out == "json" {
|
||||
emitJSON(stdout, map[string]any{"followup": map[string]any{"items_id": id}})
|
||||
return 0
|
||||
}
|
||||
fmt.Fprintf(stdout, "added followup to change #%d\n", id)
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
// readBody loads a body from a file, or from stdin when path is "-".
|
||||
func readBody(path string) (string, error) {
|
||||
if path == "-" {
|
||||
b, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("content: cannot read stdin: %w", err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("content: cannot read %s", path)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// --- ci ----------------------------------------------------------------------
|
||||
|
||||
func cmdCI(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
return usageErr(stderr, "ci: expected search|show (see mglpi help)")
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "search":
|
||||
return cmdCISearch(rest, stdout, stderr)
|
||||
case "show":
|
||||
return cmdCIShow(rest, stdout, stderr)
|
||||
default:
|
||||
return usageErr(stderr, "ci: unknown subcommand %q", sub)
|
||||
}
|
||||
}
|
||||
|
||||
func cmdCISearch(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("ci search", stderr)
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 2 {
|
||||
return usageErr(stderr, "ci search: usage: mglpi ci search TYPE TERM")
|
||||
}
|
||||
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
|
||||
rows, err := c.SearchCI(ctx, pos[0], pos[1])
|
||||
if err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
type result struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
results := make([]result, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
results = append(results, result{ID: r.ID, Name: r.Name})
|
||||
}
|
||||
if *out == "json" {
|
||||
emitJSON(stdout, map[string]any{"results": results})
|
||||
return 0
|
||||
}
|
||||
for _, r := range results {
|
||||
fmt.Fprintf(stdout, "%-6d %s\n", r.ID, r.Name)
|
||||
}
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
func cmdCIShow(args []string, stdout, stderr io.Writer) int {
|
||||
fs, cfgPath, out := newFlags("ci show", stderr)
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil || len(pos) != 2 {
|
||||
return usageErr(stderr, "ci show: usage: mglpi ci show TYPE ID")
|
||||
}
|
||||
id, err := strconv.Atoi(pos[1])
|
||||
if err != nil {
|
||||
return usageErr(stderr, "ci show: ID must be numeric, got %q", pos[1])
|
||||
}
|
||||
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
|
||||
obj, err := c.GetItem(ctx, pos[0], id)
|
||||
if err != nil {
|
||||
return apiErr(stderr, err)
|
||||
}
|
||||
if *out == "json" {
|
||||
emitJSON(stdout, obj)
|
||||
return 0
|
||||
}
|
||||
fmt.Fprintf(stdout, "%s #%d %s\n", pos[0], id, obj["name"])
|
||||
for _, k := range sortedKeys(obj) {
|
||||
if k == "id" || k == "name" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(stdout, " %s: %v\n", k, obj[k])
|
||||
}
|
||||
return 0
|
||||
})
|
||||
}
|
||||
|
||||
// sortedKeys orders an object's keys for stable text output.
|
||||
func sortedKeys(m map[string]any) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// Package config loads GLPI connection settings for the mglpi CLI.
|
||||
// The base URL, app token, and user token arrive ONLY from (a)
|
||||
// MGLPI_URL / MGLPI_APP_TOKEN / MGLPI_USER_TOKEN environment variables
|
||||
// or (b) a 0600 env file parsed in pure Go — never from flags or
|
||||
// command-line arguments. MGLPI_PROFILE_ID is optional (agent mode: the
|
||||
// CLI switches to this profile after InitSession). Files looser than
|
||||
// 0600 are refused BEFORE being read. Error messages carry line numbers
|
||||
// and key names, never values; tokens are never logged or echoed.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Keys understood in the environment and the env file.
|
||||
const (
|
||||
KeyURL = "MGLPI_URL"
|
||||
KeyAppToken = "MGLPI_APP_TOKEN"
|
||||
KeyUserToken = "MGLPI_USER_TOKEN"
|
||||
KeyProfileID = "MGLPI_PROFILE_ID"
|
||||
)
|
||||
|
||||
// Config is the resolved connection set.
|
||||
type Config struct {
|
||||
BaseURL string // full API endpoint, e.g. https://cmdb.knownelement.com/apirest.php
|
||||
AppToken string // GLPI App-Token; header-only, never logged
|
||||
UserToken string // GLPI user token; Authorization header at init, never logged
|
||||
ProfileID int // optional agent profile id; 0 = no auto-switch
|
||||
}
|
||||
|
||||
// Source records where each value came from (for safe diagnostics).
|
||||
type Source struct{ Env, File string }
|
||||
|
||||
// Load resolves settings: process env wins over the env file. path may
|
||||
// be empty (file simply not consulted). A file that exists but is looser
|
||||
// than 0600 is an error before any read. MGLPI_URL, MGLPI_APP_TOKEN and
|
||||
// MGLPI_USER_TOKEN are required; there is no default server.
|
||||
func Load(path string) (*Config, *Source, error) {
|
||||
cfg := &Config{}
|
||||
src := &Source{}
|
||||
|
||||
fileVals, err := loadFile(path)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
get := func(key string) (string, bool) {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
src.Env = key
|
||||
return v, true
|
||||
}
|
||||
if v, ok := fileVals[key]; ok && v != "" {
|
||||
src.File = key
|
||||
return v, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
if v, ok := get(KeyURL); ok {
|
||||
cfg.BaseURL = strings.TrimRight(v, "/")
|
||||
}
|
||||
if v, ok := get(KeyAppToken); ok {
|
||||
cfg.AppToken = v
|
||||
}
|
||||
if v, ok := get(KeyUserToken); ok {
|
||||
cfg.UserToken = v
|
||||
}
|
||||
// MGLPI_PROFILE_ID is optional (agent mode). Empty and unset are 0;
|
||||
// a present but non-numeric value is an error that names the key and
|
||||
// never echoes the value.
|
||||
if v, ok := get(KeyProfileID); ok {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("config: %s: must be an integer", KeyProfileID)
|
||||
}
|
||||
cfg.ProfileID = n
|
||||
}
|
||||
|
||||
var missing []string
|
||||
if cfg.BaseURL == "" {
|
||||
missing = append(missing, KeyURL)
|
||||
}
|
||||
if cfg.AppToken == "" {
|
||||
missing = append(missing, KeyAppToken)
|
||||
}
|
||||
if cfg.UserToken == "" {
|
||||
missing = append(missing, KeyUserToken)
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return nil, nil, fmt.Errorf("config: missing %s (set env or %s)", strings.Join(missing, " and "), pathOrDefault(path))
|
||||
}
|
||||
return cfg, src, nil
|
||||
}
|
||||
|
||||
// loadFile reads and parses path when given. It enforces the 0600 rule
|
||||
// before reading a single byte; a missing file is not an error (env may
|
||||
// carry everything).
|
||||
func loadFile(path string) (map[string]string, error) {
|
||||
if path == "" {
|
||||
return nil, nil
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config: %s: %w", filepath.Base(path), err)
|
||||
}
|
||||
if info.Mode().Perm()&0o077 != 0 {
|
||||
return nil, fmt.Errorf("config: %s: insecure mode %04o (must be 0600 or stricter)", filepath.Base(path), info.Mode().Perm())
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config: %s: unreadable", filepath.Base(path))
|
||||
}
|
||||
vals, err := parseEnvFile(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("config: %s: %w", filepath.Base(path), err)
|
||||
}
|
||||
return vals, nil
|
||||
}
|
||||
|
||||
// parseEnvFile parses KEY=VALUE lines in pure Go (same discipline as
|
||||
// mopac-bitwarden-go): no sourcing, no shell expansion, no interpolation.
|
||||
// Comments, blank lines, an optional "export " prefix and one matched pair
|
||||
// of surrounding quotes are handled; later duplicate keys win. Malformed
|
||||
// lines fail with the line NUMBER only — never the contents.
|
||||
func parseEnvFile(data []byte) (map[string]string, error) {
|
||||
out := map[string]string{}
|
||||
for i, line := range strings.Split(string(data), "\n") {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
continue
|
||||
}
|
||||
line = trimmed
|
||||
if strings.HasPrefix(line, "export ") || strings.HasPrefix(line, "export\t") {
|
||||
line = strings.TrimSpace(line[len("export"):])
|
||||
}
|
||||
eq := strings.IndexByte(line, '=')
|
||||
if eq <= 0 {
|
||||
return nil, fmt.Errorf("line %d: malformed KEY=VALUE line", i+1)
|
||||
}
|
||||
key := strings.TrimSpace(line[:eq])
|
||||
if !validEnvKey(key) {
|
||||
return nil, fmt.Errorf("line %d: malformed KEY=VALUE line", i+1)
|
||||
}
|
||||
value := strings.TrimSpace(line[eq+1:])
|
||||
if idx := commentIndex(value); idx >= 0 {
|
||||
value = strings.TrimSpace(value[:idx])
|
||||
}
|
||||
out[key] = unquote(value)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func validEnvKey(key string) bool {
|
||||
if key == "" {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(key); i++ {
|
||||
c := key[i]
|
||||
switch {
|
||||
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c == '_':
|
||||
case c >= '0' && c <= '9':
|
||||
if i == 0 {
|
||||
return false
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// commentIndex finds an inline comment start (a # preceded by whitespace)
|
||||
// outside a quoted value; -1 if none.
|
||||
func commentIndex(value string) int {
|
||||
var quote byte
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
switch {
|
||||
case quote != 0:
|
||||
if c == quote {
|
||||
quote = 0
|
||||
}
|
||||
case c == '"' || c == '\'':
|
||||
quote = c
|
||||
case c == '#' && (i == 0 || value[i-1] == ' ' || value[i-1] == ' '):
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func unquote(v string) string {
|
||||
if len(v) >= 2 {
|
||||
if (v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'') {
|
||||
return v[1 : len(v)-1]
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func pathOrDefault(path string) string {
|
||||
if path != "" {
|
||||
return path
|
||||
}
|
||||
return "the --config env file"
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writeFile(t *testing.T, name string, mode os.FileMode, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), name)
|
||||
if err := os.WriteFile(path, []byte(content), mode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestLoadEnvOnly(t *testing.T) {
|
||||
t.Setenv("MGLPI_URL", "https://cmdb.example/apirest.php/")
|
||||
t.Setenv("MGLPI_APP_TOKEN", "a1")
|
||||
t.Setenv("MGLPI_USER_TOKEN", "u1")
|
||||
cfg, src, err := Load("")
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.BaseURL != "https://cmdb.example/apirest.php" {
|
||||
t.Errorf("BaseURL = %q, want trailing slash trimmed", cfg.BaseURL)
|
||||
}
|
||||
if cfg.AppToken != "a1" || cfg.UserToken != "u1" {
|
||||
t.Errorf("tokens = %q/%q", cfg.AppToken, cfg.UserToken)
|
||||
}
|
||||
if cfg.ProfileID != 0 {
|
||||
t.Errorf("ProfileID = %d, want 0 when unset", cfg.ProfileID)
|
||||
}
|
||||
if src.Env == "" {
|
||||
t.Errorf("source env = %q, want a key name", src.Env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFileOnly(t *testing.T) {
|
||||
path := writeFile(t, "env", 0o600,
|
||||
"MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a2\nMGLPI_USER_TOKEN=u2\nMGLPI_PROFILE_ID=5\n")
|
||||
cfg, _, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.BaseURL != "https://cmdb.example/apirest.php" || cfg.AppToken != "a2" || cfg.UserToken != "u2" {
|
||||
t.Errorf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ProfileID != 5 {
|
||||
t.Errorf("ProfileID = %d, want 5", cfg.ProfileID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadEnvWinsOverFile(t *testing.T) {
|
||||
t.Setenv("MGLPI_USER_TOKEN", "env-user")
|
||||
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=fa\nMGLPI_USER_TOKEN=file-user\n")
|
||||
cfg, src, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.UserToken != "env-user" {
|
||||
t.Errorf("UserToken = %q, want env value to win", cfg.UserToken)
|
||||
}
|
||||
if src.File != "" && src.Env != "MGLPI_USER_TOKEN" {
|
||||
t.Errorf("source = %+v", src)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsLooseFile(t *testing.T) {
|
||||
path := writeFile(t, "env", 0o644, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\n")
|
||||
_, _, err := Load(path)
|
||||
if err == nil || !strings.Contains(err.Error(), "insecure mode") {
|
||||
t.Fatalf("err = %v, want insecure-mode rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadMissingEverything(t *testing.T) {
|
||||
_, _, err := Load(filepath.Join(t.TempDir(), "absent"))
|
||||
if err == nil || !strings.Contains(err.Error(), "MGLPI_URL") {
|
||||
t.Fatalf("err = %v, want guidance naming MGLPI_URL", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadTokenAbsent(t *testing.T) {
|
||||
t.Setenv("MGLPI_URL", "https://cmdb.example/apirest.php")
|
||||
t.Setenv("MGLPI_APP_TOKEN", "a")
|
||||
path := writeFile(t, "env", 0o600, "# nothing useful\n")
|
||||
_, _, err := Load(path)
|
||||
if err == nil || !strings.Contains(err.Error(), "MGLPI_USER_TOKEN") {
|
||||
t.Fatalf("err = %v, want MGLPI_USER_TOKEN named", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadMalformedLineReportsNumberOnly(t *testing.T) {
|
||||
path := writeFile(t, "env", 0o600,
|
||||
"MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=secret-app\nMGLPI_USER_TOKEN=secret-user\nBROKEN LINE HERE\n")
|
||||
_, _, err := Load(path)
|
||||
if err == nil || !strings.Contains(err.Error(), "line 4") {
|
||||
t.Fatalf("err = %v, want line-number-only diagnostic", err)
|
||||
}
|
||||
if err != nil && (strings.Contains(err.Error(), "secret-app") || strings.Contains(err.Error(), "secret-user")) {
|
||||
t.Fatalf("err = %v leaks file contents", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadQuotedAndExported(t *testing.T) {
|
||||
path := writeFile(t, "env", 0o600,
|
||||
"export MGLPI_URL=\"https://cmdb.example/apirest.php\"\nexport MGLPI_APP_TOKEN='a3'\nexport MGLPI_USER_TOKEN=u3\n")
|
||||
cfg, _, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.BaseURL != "https://cmdb.example/apirest.php" || cfg.AppToken != "a3" || cfg.UserToken != "u3" {
|
||||
t.Errorf("cfg = %+v, want quotes stripped", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileIDValidation(t *testing.T) {
|
||||
t.Run("absent is 0", func(t *testing.T) {
|
||||
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\n")
|
||||
cfg, _, err := Load(path)
|
||||
if err != nil || cfg.ProfileID != 0 {
|
||||
t.Fatalf("cfg = %+v err = %v", cfg, err)
|
||||
}
|
||||
})
|
||||
t.Run("empty string is 0", func(t *testing.T) {
|
||||
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\nMGLPI_PROFILE_ID=\n")
|
||||
cfg, _, err := Load(path)
|
||||
if err != nil || cfg.ProfileID != 0 {
|
||||
t.Fatalf("cfg = %+v err = %v", cfg, err)
|
||||
}
|
||||
})
|
||||
t.Run("garbage is an error that never echoes the value", func(t *testing.T) {
|
||||
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\nMGLPI_PROFILE_ID=hotliner\n")
|
||||
_, _, err := Load(path)
|
||||
if err == nil || !strings.Contains(err.Error(), "MGLPI_PROFILE_ID") {
|
||||
t.Fatalf("err = %v, want MGLPI_PROFILE_ID named", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "hotliner") {
|
||||
t.Fatalf("err = %v echoes the value", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
// Package fakeglpi is a stateful in-memory GLPI REST fake used by the
|
||||
// test suite and the smoke run. The real CMDB is NEVER contacted.
|
||||
// It implements exactly the endpoints the glpi client uses, enforces
|
||||
// App-Token + session auth on every one of them, and records every
|
||||
// request (headers included) so tests can assert the header discipline.
|
||||
//
|
||||
// GLPI quirks modeled faithfully:
|
||||
// - POST create endpoints return an ARRAY: [{"id":N,"message":"..."}].
|
||||
// - Change create takes {"input":{...}} (object); ITILFollowup REQUIRES
|
||||
// {"input":[{...}]} (array of objects) and rejects the object form.
|
||||
// - search endpoints return data rows OBJECTS KEYED BY FIELD-ID STRING
|
||||
// ({"1":"name","2":7,"12":3}) when forcedisplay is used.
|
||||
// - initSession -> {"session_token":"..."}; killSession invalidates it.
|
||||
// - changeActiveProfile switches the session's active profile; with
|
||||
// RequireChangeProfile set, change creation is rejected (403
|
||||
// ERROR_RIGHT_MISSING) until the right profile is active.
|
||||
//
|
||||
// Error responses deliberately echo the presented token back in the
|
||||
// body: any test that survives that proves the client never surfaces
|
||||
// response bodies (token-redaction guarantee).
|
||||
package fakeglpi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// criteria is one search criterion from the criteria query parameter.
|
||||
type criteria struct {
|
||||
Field int `json:"field"`
|
||||
Searchtype string `json:"searchtype"`
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
// Change status constants (GLPI change lifecycle).
|
||||
const (
|
||||
StatusNew = 1
|
||||
StatusEvaluation = 2
|
||||
StatusApproval = 3
|
||||
StatusTest = 4
|
||||
StatusQualification = 5
|
||||
StatusWaiting = 6
|
||||
StatusAccepted = 7
|
||||
StatusAssigned = 8
|
||||
StatusPlanned = 9
|
||||
StatusPending = 10
|
||||
StatusSolved = 11
|
||||
StatusClosed = 12
|
||||
)
|
||||
|
||||
// Request is one recorded exchange (auth checked, body captured).
|
||||
type Request struct {
|
||||
Method string
|
||||
Path string // path without query, trailing slash normalized
|
||||
Query string // raw query
|
||||
Body string
|
||||
// What was presented in each auth header (header-discipline tests).
|
||||
AppToken string
|
||||
AuthHeader string // Authorization header (initSession only)
|
||||
SessionToken string // Session-Token header (everything after init)
|
||||
}
|
||||
|
||||
// FailSpec pins the next response (error-mapping tests). The body is a
|
||||
// format string: %s is replaced with the token presented on the request.
|
||||
type FailSpec struct {
|
||||
Status int
|
||||
Body string
|
||||
}
|
||||
|
||||
// Profile is one GLPI profile of the logged-in user.
|
||||
type Profile struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsActive bool `json:"is_active"`
|
||||
}
|
||||
|
||||
// Change is the stored change (server side).
|
||||
type Change struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Content string `json:"content"`
|
||||
Status int `json:"status"`
|
||||
Urgency int `json:"urgency"`
|
||||
Impact int `json:"impact"`
|
||||
Date string `json:"date"`
|
||||
DateMod string `json:"date_mod"`
|
||||
}
|
||||
|
||||
// Followup is one ITILFollowup attached to a change.
|
||||
type Followup struct {
|
||||
ID int `json:"id"`
|
||||
Itemtype string `json:"itemtype"`
|
||||
ItemsID int `json:"items_id"`
|
||||
Content string `json:"content"`
|
||||
Date string `json:"date"`
|
||||
}
|
||||
|
||||
// Server is the fake GLPI.
|
||||
type Server struct {
|
||||
URL string
|
||||
AppToken string
|
||||
UserToken string
|
||||
// RequireChangeProfile, when > 0, makes change creation answer 403
|
||||
// ERROR_RIGHT_MISSING unless the session's active profile equals it
|
||||
// (the agent-mode switch path).
|
||||
RequireChangeProfile int
|
||||
// Fail, when non-nil, is returned instead of normal handling; it is
|
||||
// consumed by the first request that sees it.
|
||||
Fail *FailSpec
|
||||
|
||||
mu sync.Mutex
|
||||
srv *httptest.Server
|
||||
requests []Request
|
||||
sessions map[string]bool
|
||||
activeProfile map[string]int
|
||||
nextSess int
|
||||
profiles []Profile
|
||||
changes map[int]*Change
|
||||
followups map[int][]Followup
|
||||
items map[string]map[int]map[string]any
|
||||
nextID int
|
||||
}
|
||||
|
||||
// New starts a fake on a random port with GLPI's default profiles and a
|
||||
// few demo CIs (Computers/Monitors) for search.
|
||||
func New(appToken, userToken string) *Server {
|
||||
s := newServer(appToken, userToken)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", s.handler)
|
||||
s.srv = httptest.NewServer(mux)
|
||||
s.URL = s.srv.URL
|
||||
return s
|
||||
}
|
||||
|
||||
// ListenAndServe runs the fake on a fixed address (the smoke run boots
|
||||
// it in a container). requireChangeProfile sets the agent-mode gate.
|
||||
func ListenAndServe(addr, appToken, userToken string, requireChangeProfile int) error {
|
||||
s := newServer(appToken, userToken)
|
||||
s.RequireChangeProfile = requireChangeProfile
|
||||
seedDemo(s)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", s.handler)
|
||||
return http.ListenAndServe(addr, mux)
|
||||
}
|
||||
|
||||
func newServer(appToken, userToken string) *Server {
|
||||
return &Server{
|
||||
AppToken: appToken,
|
||||
UserToken: userToken,
|
||||
sessions: map[string]bool{},
|
||||
activeProfile: map[string]int{},
|
||||
profiles: []Profile{
|
||||
{ID: 4, Name: "Self-Service"},
|
||||
{ID: 5, Name: "Hotliner"},
|
||||
{ID: 6, Name: "Super-admin", IsActive: true},
|
||||
},
|
||||
changes: map[int]*Change{},
|
||||
followups: map[int][]Followup{},
|
||||
items: map[string]map[int]map[string]any{},
|
||||
nextID: 100,
|
||||
}
|
||||
}
|
||||
|
||||
// seedDemo adds the CIs the smoke run searches for.
|
||||
func seedDemo(s *Server) {
|
||||
s.AddItem("Computer", map[string]any{"name": "smoke-web-01", "serial": "SMOKEWEB01"})
|
||||
s.AddItem("Computer", map[string]any{"name": "smoke-db-01", "serial": "SMOKEDB01"})
|
||||
s.AddItem("Monitor", map[string]any{"name": "smoke-mon-01"})
|
||||
}
|
||||
|
||||
// Close shuts the fake down.
|
||||
func (s *Server) Close() { s.srv.Close() }
|
||||
|
||||
// Requests returns a copy of the recorded exchanges.
|
||||
func (s *Server) Requests() []Request {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]Request, len(s.requests))
|
||||
copy(out, s.requests)
|
||||
return out
|
||||
}
|
||||
|
||||
// Sessions returns the still-valid session tokens (sorted).
|
||||
func (s *Server) Sessions() []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]string, 0, len(s.sessions))
|
||||
for tok := range s.sessions {
|
||||
out = append(out, tok)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// SessionCount reports the number of valid sessions.
|
||||
func (s *Server) SessionCount() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.sessions)
|
||||
}
|
||||
|
||||
// AddChange seeds a change directly (bypassing REST) and returns its id.
|
||||
func (s *Server) AddChange(c Change) int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.nextID++
|
||||
c.ID = s.nextID
|
||||
if c.Status == 0 {
|
||||
c.Status = StatusNew
|
||||
}
|
||||
if c.Date == "" {
|
||||
c.Date = "2026-09-03T12:00:00Z"
|
||||
}
|
||||
if c.DateMod == "" {
|
||||
c.DateMod = c.Date
|
||||
}
|
||||
cc := c
|
||||
s.changes[c.ID] = &cc
|
||||
return c.ID
|
||||
}
|
||||
|
||||
// Change returns a copy of a stored change (for assertions).
|
||||
func (s *Server) Change(id int) (Change, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
c, ok := s.changes[id]
|
||||
if !ok {
|
||||
return Change{}, false
|
||||
}
|
||||
return *c, true
|
||||
}
|
||||
|
||||
// Followups returns the followups attached to a change (for assertions).
|
||||
func (s *Server) Followups(changeID int) []Followup {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]Followup, len(s.followups[changeID]))
|
||||
copy(out, s.followups[changeID])
|
||||
return out
|
||||
}
|
||||
|
||||
// AddItem seeds a CI (any itemtype) directly and returns its id.
|
||||
func (s *Server) AddItem(itemtype string, obj map[string]any) int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.nextID++
|
||||
id := s.nextID
|
||||
obj["id"] = id
|
||||
if s.items[itemtype] == nil {
|
||||
s.items[itemtype] = map[int]map[string]any{}
|
||||
}
|
||||
s.items[itemtype][id] = obj
|
||||
return id
|
||||
}
|
||||
|
||||
// Item returns a copy of a stored CI (for assertions).
|
||||
func (s *Server) Item(itemtype string, id int) (map[string]any, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
obj, ok := s.items[itemtype][id]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
out := map[string]any{}
|
||||
for k, v := range obj {
|
||||
out[k] = v
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// presented picks the token the request showed (the one an echo may
|
||||
// leak into an error body).
|
||||
func presented(r *http.Request) string {
|
||||
if v := r.Header.Get("Session-Token"); v != "" {
|
||||
return v
|
||||
}
|
||||
if v := r.Header.Get("Authorization"); v != "" {
|
||||
return v
|
||||
}
|
||||
return r.Header.Get("App-Token")
|
||||
}
|
||||
|
||||
func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
present := presented(r)
|
||||
|
||||
s.mu.Lock()
|
||||
// Fail overrides everything (echoes the presented token in the body).
|
||||
if s.Fail != nil {
|
||||
spec := *s.Fail
|
||||
s.Fail = nil
|
||||
s.record(r, body)
|
||||
s.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(spec.Status)
|
||||
fmt.Fprintf(w, spec.Body, present)
|
||||
return
|
||||
}
|
||||
// App-Token is required on EVERY endpoint.
|
||||
if r.Header.Get("App-Token") != s.AppToken {
|
||||
s.record(r, nil)
|
||||
s.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprintf(w, `[{"ERROR_APP_TOKEN_PARAMETERS_MISSING":"presented %s"}]`, present)
|
||||
return
|
||||
}
|
||||
|
||||
// GLPI serves every endpoint under /apirest.php; accept both the
|
||||
// prefixed and bare forms.
|
||||
path := strings.TrimSuffix(r.URL.Path, "/")
|
||||
path = strings.TrimPrefix(path, "/apirest.php")
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
|
||||
// initSession is the only endpoint that authenticates with the user
|
||||
// token (Authorization: user_token ...); everything else needs a
|
||||
// live Session-Token.
|
||||
if path == "/initSession" {
|
||||
respStatus, respBody := s.initSession(r)
|
||||
s.record(r, body)
|
||||
s.mu.Unlock()
|
||||
writeJSON(w, respStatus, respBody)
|
||||
return
|
||||
}
|
||||
tok := r.Header.Get("Session-Token")
|
||||
if !s.sessions[tok] {
|
||||
s.record(r, nil)
|
||||
s.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprintf(w, `[{"ERROR_SESSION_TOKEN_MISSING":"presented %s"}]`, present)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
respStatus = http.StatusOK
|
||||
respBody string
|
||||
)
|
||||
q := r.URL.Query()
|
||||
switch {
|
||||
case (r.Method == http.MethodGet || r.Method == http.MethodPost) && path == "/killSession":
|
||||
delete(s.sessions, tok)
|
||||
delete(s.activeProfile, tok)
|
||||
respBody = `true`
|
||||
case r.Method == http.MethodGet && path == "/getMyProfiles":
|
||||
respStatus, respBody = s.getMyProfiles(tok)
|
||||
case r.Method == http.MethodPost && path == "/changeActiveProfile":
|
||||
respStatus, respBody = s.changeActiveProfile(tok, body)
|
||||
case r.Method == http.MethodGet && strings.HasPrefix(path, "/Profile/"):
|
||||
respStatus, respBody = s.getProfile(tok, trimPrefixInt(path, "/Profile/"))
|
||||
case r.Method == http.MethodPost && path == "/change":
|
||||
respStatus, respBody = s.createChange(tok, body)
|
||||
case r.Method == http.MethodGet && strings.HasPrefix(path, "/change/"):
|
||||
respStatus, respBody = s.getChange(trimPrefixInt(path, "/change/"))
|
||||
case r.Method == http.MethodPut && strings.HasPrefix(path, "/change/"):
|
||||
respStatus, respBody = s.updateChange(tok, trimPrefixInt(path, "/change/"), body)
|
||||
case r.Method == http.MethodPost && path == "/ITILFollowup":
|
||||
respStatus, respBody = s.createFollowup(body)
|
||||
case r.Method == http.MethodGet && strings.HasPrefix(path, "/search/"):
|
||||
respStatus, respBody = s.search(itemtypeOf(path), q)
|
||||
case len(strings.SplitN(strings.TrimPrefix(path, "/"), "/", 2)) == 2:
|
||||
respStatus, respBody = s.getItem(path)
|
||||
default:
|
||||
respStatus, respBody = http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
|
||||
}
|
||||
s.record(r, body)
|
||||
s.mu.Unlock()
|
||||
|
||||
writeJSON(w, respStatus, respBody)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if body != "" {
|
||||
io.WriteString(w, body)
|
||||
}
|
||||
}
|
||||
|
||||
// record appends one exchange; callers hold s.mu.
|
||||
func (s *Server) record(r *http.Request, body []byte) {
|
||||
s.requests = append(s.requests, Request{
|
||||
Method: r.Method,
|
||||
Path: strings.TrimSuffix(r.URL.Path, "/"),
|
||||
Query: r.URL.RawQuery,
|
||||
Body: string(body),
|
||||
AppToken: r.Header.Get("App-Token"),
|
||||
AuthHeader: r.Header.Get("Authorization"),
|
||||
SessionToken: r.Header.Get("Session-Token"),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) initSession(r *http.Request) (int, string) {
|
||||
if auth := r.Header.Get("Authorization"); auth != "user_token "+s.UserToken {
|
||||
return http.StatusBadRequest, fmt.Sprintf(`[{"ERROR_GLPI_LOGIN":"login %s refused"}]`, auth)
|
||||
}
|
||||
s.nextSess++
|
||||
tok := fmt.Sprintf("sess-%d", s.nextSess)
|
||||
s.sessions[tok] = true
|
||||
s.activeProfile[tok] = 6 // Super-admin is the default active profile
|
||||
return http.StatusOK, `{"session_token":"` + tok + `"}`
|
||||
}
|
||||
|
||||
func (s *Server) getMyProfiles(tok string) (int, string) {
|
||||
out := make([]Profile, len(s.profiles))
|
||||
copy(out, s.profiles)
|
||||
for i := range out {
|
||||
out[i].IsActive = out[i].ID == s.activeProfile[tok]
|
||||
}
|
||||
return jsonReply(out)
|
||||
}
|
||||
|
||||
func (s *Server) changeActiveProfile(tok string, body []byte) (int, string) {
|
||||
var p struct {
|
||||
ProfilesID int `json:"profiles_id"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &p); err != nil || p.ProfilesID == 0 {
|
||||
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
|
||||
}
|
||||
found := false
|
||||
for _, pr := range s.profiles {
|
||||
if pr.ID == p.ProfilesID {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return http.StatusBadRequest, `[{"ERROR_PROFILE_NOT_FOUND":true}]`
|
||||
}
|
||||
s.activeProfile[tok] = p.ProfilesID
|
||||
return http.StatusOK, `true`
|
||||
}
|
||||
|
||||
func (s *Server) getProfile(tok string, id int) (int, string) {
|
||||
for _, pr := range s.profiles {
|
||||
if pr.ID == id {
|
||||
p := pr
|
||||
p.IsActive = p.ID == s.activeProfile[tok]
|
||||
return jsonReply(p)
|
||||
}
|
||||
}
|
||||
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
|
||||
}
|
||||
|
||||
// createChange enforces the agent profile gate, the object-input
|
||||
// contract, and GLPI's array reply shape.
|
||||
func (s *Server) createChange(tok string, body []byte) (int, string) {
|
||||
if s.RequireChangeProfile > 0 && s.activeProfile[tok] != s.RequireChangeProfile {
|
||||
return http.StatusForbidden, `[{"ERROR_RIGHT_MISSING":true}]`
|
||||
}
|
||||
input, ok := inputObject(body)
|
||||
if !ok {
|
||||
return http.StatusBadRequest, `[{"ERROR_INPUT_OBJECT_EXPECTED":true}]`
|
||||
}
|
||||
var c Change
|
||||
if err := json.Unmarshal(input, &c); err != nil {
|
||||
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
|
||||
}
|
||||
if c.Name == "" {
|
||||
return http.StatusBadRequest, `[{"ERROR_GLPI_ADD":true}]`
|
||||
}
|
||||
s.nextID++
|
||||
c.ID = s.nextID
|
||||
if c.Status == 0 {
|
||||
c.Status = StatusNew
|
||||
}
|
||||
c.Date = "2026-09-03T12:00:00Z"
|
||||
c.DateMod = c.Date
|
||||
cc := c
|
||||
s.changes[c.ID] = &cc
|
||||
return http.StatusCreated, fmt.Sprintf(`[{"id":%d,"message":"change created"}]`, c.ID)
|
||||
}
|
||||
|
||||
func (s *Server) getChange(id int) (int, string) {
|
||||
c, ok := s.changes[id]
|
||||
if !ok {
|
||||
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
|
||||
}
|
||||
return jsonReply(*c)
|
||||
}
|
||||
|
||||
// updateChange applies a partial update and answers GLPI's array shape
|
||||
// [{"<id>":true,"message":""}].
|
||||
func (s *Server) updateChange(tok string, id int, body []byte) (int, string) {
|
||||
if s.RequireChangeProfile > 0 && s.activeProfile[tok] != s.RequireChangeProfile {
|
||||
return http.StatusForbidden, `[{"ERROR_RIGHT_MISSING":true}]`
|
||||
}
|
||||
c, ok := s.changes[id]
|
||||
if !ok {
|
||||
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
|
||||
}
|
||||
input, ok := inputObject(body)
|
||||
if !ok {
|
||||
return http.StatusBadRequest, `[{"ERROR_INPUT_OBJECT_EXPECTED":true}]`
|
||||
}
|
||||
var p Change
|
||||
if err := json.Unmarshal(input, &p); err != nil {
|
||||
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
|
||||
}
|
||||
if p.Name != "" {
|
||||
c.Name = p.Name
|
||||
}
|
||||
if p.Content != "" {
|
||||
c.Content = p.Content
|
||||
}
|
||||
if p.Status != 0 {
|
||||
if p.Status < StatusNew || p.Status > StatusClosed {
|
||||
return http.StatusBadRequest, `[{"ERROR_GLPI_UPDATE":true}]`
|
||||
}
|
||||
c.Status = p.Status
|
||||
}
|
||||
if p.Urgency != 0 {
|
||||
c.Urgency = p.Urgency
|
||||
}
|
||||
if p.Impact != 0 {
|
||||
c.Impact = p.Impact
|
||||
}
|
||||
c.DateMod = "2026-09-03T13:00:00Z"
|
||||
return http.StatusOK, fmt.Sprintf(`[{"%d":true,"message":""}]`, id)
|
||||
}
|
||||
|
||||
// createFollowup enforces the ARRAY-input contract ({"input":[{...}]});
|
||||
// the object form is rejected, mirroring the real ITILFollowup endpoint.
|
||||
func (s *Server) createFollowup(body []byte) (int, string) {
|
||||
var probe struct {
|
||||
Input json.RawMessage `json:"input"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &probe); err != nil || len(probe.Input) == 0 {
|
||||
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
|
||||
}
|
||||
if bytes.TrimSpace(probe.Input)[0] != '[' {
|
||||
return http.StatusBadRequest, `[{"ERROR_INPUT_ARRAY_EXPECTED":true}]`
|
||||
}
|
||||
var ins []Followup
|
||||
if err := json.Unmarshal(probe.Input, &ins); err != nil {
|
||||
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
|
||||
}
|
||||
var created []map[string]any
|
||||
for _, in := range ins {
|
||||
if in.Itemtype != "Change" || in.Content == "" {
|
||||
return http.StatusBadRequest, `[{"ERROR_GLPI_ADD":true}]`
|
||||
}
|
||||
if _, ok := s.changes[in.ItemsID]; !ok {
|
||||
return http.StatusBadRequest, `[{"ERROR_GLPI_ADD":true}]`
|
||||
}
|
||||
s.nextID++
|
||||
in.ID = s.nextID
|
||||
in.Date = "2026-09-03T13:00:00Z"
|
||||
s.followups[in.ItemsID] = append(s.followups[in.ItemsID], in)
|
||||
created = append(created, map[string]any{"id": in.ID, "message": "followup added"})
|
||||
}
|
||||
if created == nil {
|
||||
created = []map[string]any{}
|
||||
}
|
||||
// Create endpoints answer 201 with the array reply shape.
|
||||
return http.StatusCreated, mustJSON(created)
|
||||
}
|
||||
|
||||
func mustJSON(v any) string {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// search serves /search/<itemtype>: criteria filtering plus rows keyed
|
||||
// by forcedisplay field-id strings ({"1":"name","2":7,"12":3}).
|
||||
func (s *Server) search(itemtype string, q url.Values) (int, string) {
|
||||
if itemtype != "Change" && s.items[itemtype] == nil {
|
||||
return http.StatusBadRequest, `[{"ERROR_GLPI_SEARCH":true}]`
|
||||
}
|
||||
base := map[int]map[string]any{}
|
||||
var ids []int
|
||||
appendRow := func(id int, row map[string]any) {
|
||||
base[id] = row
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if itemtype == "Change" {
|
||||
for id, c := range s.changes {
|
||||
appendRow(id, map[string]any{"1": c.Name, "2": c.ID, "12": c.Status})
|
||||
}
|
||||
} else {
|
||||
for id, obj := range s.items[itemtype] {
|
||||
name, _ := obj["name"].(string)
|
||||
appendRow(id, map[string]any{"1": name, "2": id})
|
||||
}
|
||||
}
|
||||
sort.Ints(ids)
|
||||
|
||||
var criteriaList []criteria
|
||||
if c := q.Get("criteria"); c != "" {
|
||||
if err := json.Unmarshal([]byte(c), &criteriaList); err != nil {
|
||||
return http.StatusBadRequest, `[{"ERROR_GLPI_SEARCH":true}]`
|
||||
}
|
||||
}
|
||||
rows := []map[string]any{}
|
||||
for _, id := range ids {
|
||||
row := base[id]
|
||||
if !matchCriteria(row, criteriaList) {
|
||||
continue
|
||||
}
|
||||
forced := q["forcedisplay[]"]
|
||||
if len(forced) == 0 {
|
||||
forced = []string{"1", "2"}
|
||||
}
|
||||
projected := map[string]any{}
|
||||
for _, f := range forced {
|
||||
if v, ok := row[f]; ok {
|
||||
projected[f] = v
|
||||
}
|
||||
}
|
||||
rows = append(rows, projected)
|
||||
}
|
||||
out := map[string]any{
|
||||
"totalcount": len(rows),
|
||||
"count": len(rows),
|
||||
"sort": 1,
|
||||
"order": "ASC",
|
||||
"data": rows,
|
||||
}
|
||||
return jsonReply(out)
|
||||
}
|
||||
|
||||
func matchCriteria(row map[string]any, criteriaList []criteria) bool {
|
||||
for _, cr := range criteriaList {
|
||||
val, ok := row[strconv.Itoa(cr.Field)]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
switch cr.Searchtype {
|
||||
case "equals":
|
||||
if asFloat(val) != asFloat(cr.Value) {
|
||||
return false
|
||||
}
|
||||
case "contains":
|
||||
vs, _ := cr.Value.(string)
|
||||
if !strings.Contains(strings.ToLower(fmt.Sprint(val)), strings.ToLower(vs)) {
|
||||
return false
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func asFloat(v any) float64 {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
return n
|
||||
case int:
|
||||
return float64(n)
|
||||
case string:
|
||||
f, _ := strconv.ParseFloat(n, 64)
|
||||
return f
|
||||
default:
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
// getItem serves GET /<itemtype>/<id> for seeded CI types.
|
||||
func (s *Server) getItem(path string) (int, string) {
|
||||
parts := strings.SplitN(strings.TrimPrefix(path, "/"), "/", 2)
|
||||
itemtype := parts[0]
|
||||
id, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
|
||||
}
|
||||
obj, ok := s.items[itemtype][id]
|
||||
if !ok {
|
||||
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
|
||||
}
|
||||
return jsonReply(obj)
|
||||
}
|
||||
|
||||
// inputObject extracts the "input" member and reports whether it is a
|
||||
// JSON object (Change family) — the array form is a distinct error.
|
||||
func inputObject(body []byte) (json.RawMessage, bool) {
|
||||
var probe struct {
|
||||
Input json.RawMessage `json:"input"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &probe); err != nil || len(probe.Input) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
trimmed := bytes.TrimSpace(probe.Input)
|
||||
if len(trimmed) == 0 || trimmed[0] != '{' {
|
||||
return nil, false
|
||||
}
|
||||
return trimmed, true
|
||||
}
|
||||
|
||||
func trimPrefixInt(path, prefix string) int {
|
||||
n, _ := strconv.Atoi(strings.TrimPrefix(path, prefix))
|
||||
return n
|
||||
}
|
||||
|
||||
func itemtypeOf(path string) string {
|
||||
return strings.TrimPrefix(path, "/search/")
|
||||
}
|
||||
|
||||
func jsonReply(v any) (int, string) {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, `[{"ERROR_MARSHAL":true}]`
|
||||
}
|
||||
return http.StatusOK, string(b)
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// Package mcp implements a minimal stdio JSON-RPC MCP (Model Context
|
||||
// Protocol) server over the glpi library — stdlib only, no third-party
|
||||
// modules. Transport is newline-delimited JSON on the reader/writer
|
||||
// pair. Tools: change_create, change_list, change_transition,
|
||||
// change_followup, ci_search, ci_show. An optional agent profile id
|
||||
// (e.g. 5 = Hotliner) is applied on the first tool call.
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
|
||||
)
|
||||
|
||||
// protocolVersionDefault answers initialize when the client does not
|
||||
// name one.
|
||||
const protocolVersionDefault = "2025-06-18"
|
||||
|
||||
// Server is the MCP server over one glpi.Client.
|
||||
type Server struct {
|
||||
client *glpi.Client
|
||||
profile int
|
||||
|
||||
once sync.Once
|
||||
profileErr error
|
||||
}
|
||||
|
||||
// New builds a Server. profileID > 0 switches the session's active
|
||||
// profile (agent mode) on first use.
|
||||
func New(c *glpi.Client, profileID int) *Server {
|
||||
return &Server{client: c, profile: profileID}
|
||||
}
|
||||
|
||||
// Serve reads newline-delimited JSON-RPC requests until EOF, writing
|
||||
// one response line per request that carries an id (notifications are
|
||||
// acknowledged by silence).
|
||||
func (s *Server) Serve(in io.Reader, out io.Writer) error {
|
||||
sc := bufio.NewScanner(in)
|
||||
sc.Buffer(make([]byte, 0, 64*1024), 4<<20)
|
||||
for sc.Scan() {
|
||||
line := bytes.TrimSpace(sc.Bytes())
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
if err := s.handle(line, out); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return sc.Err()
|
||||
}
|
||||
|
||||
// request is one inbound JSON-RPC message.
|
||||
type request struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
} `json:"params"`
|
||||
}
|
||||
|
||||
// response is one outbound JSON-RPC message (result XOR error).
|
||||
type response struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *rpcError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (s *Server) handle(line []byte, out io.Writer) error {
|
||||
var req request
|
||||
if err := json.Unmarshal(line, &req); err != nil || req.Method == "" {
|
||||
return nil // cannot route a malformed line; never guess an id
|
||||
}
|
||||
if len(req.ID) == 0 || string(req.ID) == "null" {
|
||||
return nil // notification: no response per JSON-RPC
|
||||
}
|
||||
|
||||
resp := response{JSONRPC: "2.0", ID: req.ID}
|
||||
switch req.Method {
|
||||
case "initialize":
|
||||
pv := req.Params.ProtocolVersion
|
||||
if pv == "" {
|
||||
pv = protocolVersionDefault
|
||||
}
|
||||
resp.Result = map[string]any{
|
||||
"protocolVersion": pv,
|
||||
"capabilities": map[string]any{"tools": map[string]any{}},
|
||||
"serverInfo": map[string]any{"name": "mglpi-mcp", "version": "0.1.0"},
|
||||
}
|
||||
case "ping":
|
||||
resp.Result = map[string]any{}
|
||||
case "tools/list":
|
||||
resp.Result = map[string]any{"tools": toolDefs()}
|
||||
case "tools/call":
|
||||
resp.Result = s.callTool(req.Params.Name, req.Params.Arguments)
|
||||
default:
|
||||
resp.Result = nil
|
||||
resp.Error = &rpcError{Code: -32601, Message: fmt.Sprintf("method not found: %s", req.Method)}
|
||||
}
|
||||
return writeLine(out, resp)
|
||||
}
|
||||
|
||||
// ensureProfile applies the agent profile once per server lifetime (an
|
||||
// API op; it also warms the session).
|
||||
func (s *Server) ensureProfile() error {
|
||||
s.once.Do(func() {
|
||||
if s.profile > 0 {
|
||||
s.profileErr = s.client.ChangeActiveProfile(context.Background(), s.profile)
|
||||
}
|
||||
})
|
||||
return s.profileErr
|
||||
}
|
||||
|
||||
// callTool dispatches one tools/call. Tool failures are RESULTS with
|
||||
// isError=true (protocol errors are the -32601 path only).
|
||||
func (s *Server) callTool(name string, args json.RawMessage) map[string]any {
|
||||
if err := s.ensureProfile(); err != nil {
|
||||
return toolError(err)
|
||||
}
|
||||
var a map[string]any
|
||||
if len(args) > 0 {
|
||||
if err := json.Unmarshal(args, &a); err != nil {
|
||||
return toolError(fmt.Errorf("arguments are not an object"))
|
||||
}
|
||||
}
|
||||
ctx := context.Background()
|
||||
var payload any
|
||||
switch name {
|
||||
case "change_create":
|
||||
title, _ := a["title"].(string)
|
||||
if title == "" {
|
||||
return toolError(fmt.Errorf("change_create requires title"))
|
||||
}
|
||||
content, _ := a["content"].(string)
|
||||
id, err := s.client.CreateChange(ctx, title, content, argInt(a, "urgency", 3), argInt(a, "impact", 3))
|
||||
if err != nil {
|
||||
return toolError(err)
|
||||
}
|
||||
payload = map[string]any{"change": map[string]any{"id": id}}
|
||||
case "change_list":
|
||||
rows, err := s.client.ListChanges(ctx, argInt(a, "status", 0))
|
||||
if err != nil {
|
||||
return toolError(err)
|
||||
}
|
||||
payload = map[string]any{"changes": rows}
|
||||
case "change_transition":
|
||||
id := argInt(a, "id", 0)
|
||||
status, ok := glpi.StatusID(argString(a, "status"))
|
||||
if !ok {
|
||||
status = argInt(a, "status", 0)
|
||||
}
|
||||
if id == 0 || status == 0 {
|
||||
return toolError(fmt.Errorf("change_transition requires id and status"))
|
||||
}
|
||||
if err := s.client.TransitionChange(ctx, id, status); err != nil {
|
||||
return toolError(err)
|
||||
}
|
||||
payload = map[string]any{"transitioned": map[string]any{"id": id, "status": glpi.StatusName(status)}}
|
||||
case "change_followup":
|
||||
id := argInt(a, "id", 0)
|
||||
content, _ := a["content"].(string)
|
||||
if id == 0 || content == "" {
|
||||
return toolError(fmt.Errorf("change_followup requires id and content"))
|
||||
}
|
||||
if err := s.client.AddFollowup(ctx, id, content); err != nil {
|
||||
return toolError(err)
|
||||
}
|
||||
payload = map[string]any{"followup": map[string]any{"items_id": id}}
|
||||
case "ci_search":
|
||||
rows, err := s.client.SearchCI(ctx, argString(a, "itemtype"), argString(a, "term"))
|
||||
if err != nil {
|
||||
return toolError(err)
|
||||
}
|
||||
type result struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
results := make([]result, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
results = append(results, result{ID: r.ID, Name: r.Name})
|
||||
}
|
||||
payload = map[string]any{"results": results}
|
||||
case "ci_show":
|
||||
id := argInt(a, "id", 0)
|
||||
obj, err := s.client.GetItem(ctx, argString(a, "itemtype"), id)
|
||||
if err != nil {
|
||||
return toolError(err)
|
||||
}
|
||||
payload = obj
|
||||
default:
|
||||
return toolError(fmt.Errorf("unknown tool: %s", name))
|
||||
}
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return toolError(fmt.Errorf("cannot encode tool result"))
|
||||
}
|
||||
return map[string]any{
|
||||
"content": []map[string]any{{"type": "text", "text": string(b)}},
|
||||
"isError": false,
|
||||
}
|
||||
}
|
||||
|
||||
func toolError(err error) map[string]any {
|
||||
return map[string]any{
|
||||
"content": []map[string]any{{"type": "text", "text": err.Error()}},
|
||||
"isError": true,
|
||||
}
|
||||
}
|
||||
|
||||
func argString(a map[string]any, key string) string {
|
||||
s, _ := a[key].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
func argInt(a map[string]any, key string, def int) int {
|
||||
switch v := a[key].(type) {
|
||||
case float64:
|
||||
return int(v)
|
||||
case string:
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// toolDefs is the advertised tool surface (stable order).
|
||||
func toolDefs() []map[string]any {
|
||||
schema := func(required ...string) map[string]any {
|
||||
props := map[string]any{}
|
||||
for _, p := range required {
|
||||
props[p] = map[string]any{"type": "string"}
|
||||
}
|
||||
return map[string]any{
|
||||
"type": "object",
|
||||
"properties": props,
|
||||
"required": required,
|
||||
}
|
||||
}
|
||||
full := func(req []string, opt map[string]string) map[string]any {
|
||||
props := map[string]any{}
|
||||
for _, p := range req {
|
||||
props[p] = map[string]any{"type": "string"}
|
||||
}
|
||||
for p, t := range opt {
|
||||
props[p] = map[string]any{"type": t}
|
||||
}
|
||||
return map[string]any{
|
||||
"type": "object",
|
||||
"properties": props,
|
||||
"required": req,
|
||||
}
|
||||
}
|
||||
return []map[string]any{
|
||||
{"name": "change_create", "description": "Create a GLPI change (urgency/impact 1-5, 3=medium)", "inputSchema": full([]string{"title"}, map[string]string{"content": "string", "urgency": "integer", "impact": "integer"})},
|
||||
{"name": "change_list", "description": "List GLPI changes (optional status filter)", "inputSchema": schema()},
|
||||
{"name": "change_transition", "description": "Move a change to a status (name or numeric id)", "inputSchema": schema("id", "status")},
|
||||
{"name": "change_followup", "description": "Append a followup note to a change", "inputSchema": schema("id", "content")},
|
||||
{"name": "ci_search", "description": "Search CIs of an itemtype by name substring", "inputSchema": schema("itemtype", "term")},
|
||||
{"name": "ci_show", "description": "Fetch one CI raw by itemtype and id", "inputSchema": schema("itemtype", "id")},
|
||||
}
|
||||
}
|
||||
|
||||
// writeLine emits one compact JSON response line.
|
||||
func writeLine(out io.Writer, v any) error {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = out.Write(append(b, '\n'))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
|
||||
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/fakeglpi"
|
||||
)
|
||||
|
||||
const (
|
||||
testApp = "fake-app-token-0123456789"
|
||||
testUser = "fake-user-token-0123456789"
|
||||
)
|
||||
|
||||
// serve feeds one batch of JSON-RPC lines through the server and
|
||||
// returns the response lines.
|
||||
func serve(t *testing.T, s *Server, lines ...string) []map[string]any {
|
||||
t.Helper()
|
||||
var out strings.Builder
|
||||
if err := s.Serve(strings.NewReader(strings.Join(lines, "\n")+"\n"), &out); err != nil {
|
||||
t.Fatalf("Serve: %v", err)
|
||||
}
|
||||
var msgs []map[string]any
|
||||
for i, line := range strings.Split(strings.TrimRight(out.String(), "\n"), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(line), &m); err != nil {
|
||||
t.Fatalf("response line %d not json: %v (%q)", i+1, err, line)
|
||||
}
|
||||
msgs = append(msgs, m)
|
||||
}
|
||||
return msgs
|
||||
}
|
||||
|
||||
func newServer(t *testing.T) (*Server, *fakeglpi.Server) {
|
||||
t.Helper()
|
||||
srv := fakeglpi.New(testApp, testUser)
|
||||
t.Cleanup(srv.Close)
|
||||
c := glpi.New(glpi.Config{BaseURL: srv.URL, AppToken: testApp, UserToken: testUser, Timeout: 5 * time.Second})
|
||||
return New(c, 0), srv
|
||||
}
|
||||
|
||||
func rpc(id int, method string, params map[string]any) string {
|
||||
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestInitializeHandshake(t *testing.T) {
|
||||
s, _ := newServer(t)
|
||||
msgs := serve(t, s, rpc(1, "initialize", map[string]any{
|
||||
"protocolVersion": "2025-06-18",
|
||||
"capabilities": map[string]any{},
|
||||
"clientInfo": map[string]any{"name": "test", "version": "0"},
|
||||
}))
|
||||
if len(msgs) != 1 {
|
||||
t.Fatalf("responses = %d, want 1", len(msgs))
|
||||
}
|
||||
res, _ := msgs[0]["result"].(map[string]any)
|
||||
if res == nil {
|
||||
t.Fatalf("no result: %+v", msgs[0])
|
||||
}
|
||||
pv, _ := res["protocolVersion"].(string)
|
||||
if pv == "" {
|
||||
t.Errorf("initialize response missing protocol_version: %+v", res)
|
||||
}
|
||||
info, _ := res["serverInfo"].(map[string]any)
|
||||
if info == nil || info["name"] != "mglpi-mcp" {
|
||||
t.Errorf("serverInfo = %+v", info)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationProducesNoResponse(t *testing.T) {
|
||||
s, _ := newServer(t)
|
||||
// A notification (no id) must not yield a response line.
|
||||
msgs := serve(t, s, `{"jsonrpc":"2.0","method":"notifications/initialized"}`)
|
||||
if len(msgs) != 0 {
|
||||
t.Fatalf("responses = %+v, want none", msgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolsList(t *testing.T) {
|
||||
s, _ := newServer(t)
|
||||
msgs := serve(t, s, rpc(2, "tools/list", map[string]any{}))
|
||||
res, _ := msgs[0]["result"].(map[string]any)
|
||||
tools, _ := res["tools"].([]any)
|
||||
want := map[string]bool{
|
||||
"change_create": false, "change_list": false, "change_transition": false,
|
||||
"change_followup": false, "ci_search": false, "ci_show": false,
|
||||
}
|
||||
if len(tools) != len(want) {
|
||||
t.Fatalf("tools = %+v, want %d", tools, len(want))
|
||||
}
|
||||
for _, tl := range tools {
|
||||
tm, _ := tl.(map[string]any)
|
||||
name, _ := tm["name"].(string)
|
||||
if _, ok := want[name]; !ok {
|
||||
t.Errorf("unexpected tool %q", name)
|
||||
}
|
||||
if tm["inputSchema"] == nil {
|
||||
t.Errorf("tool %q missing inputSchema", name)
|
||||
}
|
||||
want[name] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolCallsRoundTrip(t *testing.T) {
|
||||
s, srv := newServer(t)
|
||||
web := srv.AddItem("Computer", map[string]any{"name": "web-01", "serial": "ABC123"})
|
||||
|
||||
// change_create
|
||||
msgs := serve(t, s, rpc(3, "tools/call", map[string]any{
|
||||
"name": "change_create",
|
||||
"arguments": map[string]any{
|
||||
"title": "Quota accounting", "content": "<p>body</p>", "urgency": 3, "impact": 4,
|
||||
},
|
||||
}))
|
||||
var created struct {
|
||||
Content []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"content"`
|
||||
}
|
||||
b, _ := json.Marshal(msgs[0]["result"])
|
||||
if err := json.Unmarshal(b, &created); err != nil || len(created.Content) == 0 {
|
||||
t.Fatalf("create result = %s err %v", b, err)
|
||||
}
|
||||
var payload struct {
|
||||
Change struct {
|
||||
ID int `json:"id"`
|
||||
} `json:"change"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(created.Content[0].Text), &payload); err != nil || payload.Change.ID == 0 {
|
||||
t.Fatalf("tool text = %q err %v", created.Content[0].Text, err)
|
||||
}
|
||||
stored, ok := srv.Change(payload.Change.ID)
|
||||
if !ok || stored.Name != "Quota accounting" || stored.Impact != 4 {
|
||||
t.Fatalf("stored = %+v", stored)
|
||||
}
|
||||
|
||||
// change_list
|
||||
msgs = serve(t, s, rpc(4, "tools/call", map[string]any{"name": "change_list", "arguments": map[string]any{}}))
|
||||
if !strings.Contains(msgs[0]["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string), "Quota accounting") {
|
||||
t.Errorf("change_list text missing created change")
|
||||
}
|
||||
|
||||
// change_transition
|
||||
msgs = serve(t, s, rpc(5, "tools/call", map[string]any{
|
||||
"name": "change_transition",
|
||||
"arguments": map[string]any{"id": payload.Change.ID, "status": "solved"},
|
||||
}))
|
||||
if got, _ := srv.Change(payload.Change.ID); got.Status != fakeglpi.StatusSolved {
|
||||
t.Errorf("status after transition = %d", got.Status)
|
||||
}
|
||||
|
||||
// change_followup
|
||||
msgs = serve(t, s, rpc(6, "tools/call", map[string]any{
|
||||
"name": "change_followup",
|
||||
"arguments": map[string]any{"id": payload.Change.ID, "content": "REPORT delivered"},
|
||||
}))
|
||||
if fups := srv.Followups(payload.Change.ID); len(fups) != 1 || fups[0].Content != "REPORT delivered" {
|
||||
t.Errorf("followups = %+v", srv.Followups(payload.Change.ID))
|
||||
}
|
||||
|
||||
// ci_search
|
||||
msgs = serve(t, s, rpc(7, "tools/call", map[string]any{
|
||||
"name": "ci_search",
|
||||
"arguments": map[string]any{"itemtype": "Computer", "term": "web"},
|
||||
}))
|
||||
text := msgs[0]["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
|
||||
if !strings.Contains(text, "web-01") {
|
||||
t.Errorf("ci_search text = %q", text)
|
||||
}
|
||||
|
||||
// ci_show
|
||||
msgs = serve(t, s, rpc(8, "tools/call", map[string]any{
|
||||
"name": "ci_show",
|
||||
"arguments": map[string]any{"itemtype": "Computer", "id": web},
|
||||
}))
|
||||
text = msgs[0]["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
|
||||
if !strings.Contains(text, "ABC123") {
|
||||
t.Errorf("ci_show text = %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolCallErrorsAreResults(t *testing.T) {
|
||||
s, _ := newServer(t)
|
||||
msgs := serve(t, s,
|
||||
rpc(9, "tools/call", map[string]any{"name": "no_such_tool", "arguments": map[string]any{}}),
|
||||
rpc(10, "tools/call", map[string]any{"name": "change_create", "arguments": map[string]any{}}),
|
||||
)
|
||||
for i, m := range msgs {
|
||||
res, _ := m["result"].(map[string]any)
|
||||
if res == nil || res["isError"] != true {
|
||||
t.Fatalf("response %d = %+v, want isError result", i, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownMethodIsProtocolError(t *testing.T) {
|
||||
s, _ := newServer(t)
|
||||
msgs := serve(t, s, rpc(11, "resources/list", map[string]any{}))
|
||||
errObj, _ := msgs[0]["error"].(map[string]any)
|
||||
if errObj == nil || errObj["code"] != float64(-32601) {
|
||||
t.Fatalf("error = %+v, want -32601", errObj)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPing(t *testing.T) {
|
||||
s, _ := newServer(t)
|
||||
msgs := serve(t, s, rpc(12, "ping", map[string]any{}))
|
||||
if msgs[0]["result"] == nil {
|
||||
t.Fatalf("ping = %+v", msgs[0])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user