- member add --publisher makes a publisher, --publisher=false demotes; without the flag an existing member keeps its role - member ls has a ROLE column: publisher or subscriber - new member set <list> <email> --publisher=true|false (usage error without the flag) - member import reads an optional third column, the keyword publisher (any case); anything else there fails that line; an empty third column is ignored - list set --post publishers; help text updated - the old import test now uses the publisher keyword in its third column
396 lines
12 KiB
Go
396 lines
12 KiB
Go
// Package cli is the command-line client for the Parsimony admin API.
|
|
package cli
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"text/tabwriter"
|
|
"time"
|
|
)
|
|
|
|
// IO bundles the standard streams so tests can drive the CLI.
|
|
type IO struct {
|
|
In io.Reader
|
|
Out, Err io.Writer
|
|
}
|
|
|
|
const usageText = `Usage: parsimony [--url URL] [--insecure] [--json] <command> [arguments]
|
|
|
|
Administration (talks to the REST API):
|
|
list ls show all lists
|
|
list add <name@domain> [--title T] create a list
|
|
list show <list> show one list
|
|
list set <list> [--title T] [--post members|moderated|publishers]
|
|
[--join open|closed] [--archive public|private|off]
|
|
list rm <list> --yes delete a list with its members and archive
|
|
|
|
member ls <list> [--emails] show subscribers and publishers
|
|
member add <list> <email> [--name N] [--publisher]
|
|
subscribe (or re-enable) an address;
|
|
--publisher lets it post to a publishers list,
|
|
--publisher=false takes that away
|
|
member set <list> <email> --publisher=true|false
|
|
make a member a publisher or a plain subscriber
|
|
member rm <list> <email> unsubscribe an address
|
|
member import <list> <file|-> subscribe addresses from a file or stdin,
|
|
one "email[,name[,publisher]]" per line
|
|
|
|
held ls <list> messages waiting for moderation
|
|
held approve <id> deliver a held message
|
|
held discard <id> delete a held message
|
|
|
|
archive ls <list> [--q TEXT] [--limit N] [--offset N]
|
|
archive show <id>
|
|
archive rm <id> --yes
|
|
archive import <list> <file|-> add the messages of an mbox file (Mailman export);
|
|
safe to repeat, threads are rebuilt
|
|
|
|
queue ls outbound queue
|
|
queue rm <id> discard one queued delivery
|
|
|
|
DKIM (works offline, needs no token):
|
|
dkim keygen <domain> [--selector mail] [--out FILE] [--force]
|
|
create a signing key and print the DNS record and config
|
|
dkim record <domain> --key FILE [--selector mail]
|
|
print the DNS record of an existing key
|
|
dkim check <domain> --key FILE [--selector mail]
|
|
look the record up in DNS and compare it with the key
|
|
|
|
Daemon:
|
|
serve [-config FILE] run the mailing list server
|
|
|
|
<list> is a list address (dev@example.org) or its numeric id.
|
|
|
|
Environment:
|
|
PARSIMONY_API_TOKEN bearer token for the API (required, never a flag)
|
|
PARSIMONY_URL API address, default http://127.0.0.1:8080 (--url overrides)
|
|
|
|
--json prints the API's JSON instead of tables.
|
|
--insecure allows sending the token over plain http to a host other than localhost.
|
|
Exit status: 0 success, 1 failure, 2 usage error.
|
|
`
|
|
|
|
// Run executes one CLI invocation and returns the process exit code.
|
|
func Run(args []string, io IO, getenv func(string) string) int {
|
|
c := &cmd{io: io, getenv: getenv}
|
|
|
|
fs := newFlagSet("parsimony")
|
|
fs.StringVar(&c.url, "url", "", "")
|
|
fs.BoolVar(&c.json, "json", false, "")
|
|
fs.BoolVar(&c.insecure, "insecure", false, "")
|
|
if err := fs.Parse(args); err != nil {
|
|
if errors.Is(err, flag.ErrHelp) {
|
|
fmt.Fprint(io.Out, usageText)
|
|
return 0
|
|
}
|
|
return c.usageError(err.Error())
|
|
}
|
|
rest := fs.Args()
|
|
if len(rest) == 0 {
|
|
fmt.Fprint(io.Err, "usage: parsimony [--url URL] [--insecure] [--json] <command> (see parsimony help)\n")
|
|
return 2
|
|
}
|
|
if rest[0] == "help" {
|
|
fmt.Fprint(io.Out, usageText)
|
|
return 0
|
|
}
|
|
|
|
commands := map[string]map[string]func([]string) int{
|
|
"list": {"ls": c.listLs, "add": c.listAdd, "show": c.listShow, "set": c.listSet, "rm": c.listRm},
|
|
"member": {"ls": c.memberLs, "add": c.memberAdd, "set": c.memberSet, "rm": c.memberRm, "import": c.memberImport},
|
|
"held": {"ls": c.heldLs, "approve": c.heldApprove, "discard": c.heldDiscard},
|
|
"archive": {"ls": c.archiveLs, "show": c.archiveShow, "rm": c.archiveRm, "import": c.archiveImport},
|
|
"queue": {"ls": c.queueLs, "rm": c.queueRm},
|
|
"dkim": {"keygen": c.dkimKeygen, "record": c.dkimRecord, "check": c.dkimCheck},
|
|
}
|
|
group, ok := commands[rest[0]]
|
|
if !ok {
|
|
return c.usageError("unknown command %q (see parsimony help)", rest[0])
|
|
}
|
|
if len(rest) < 2 {
|
|
return c.usageError("usage: parsimony %s <subcommand> (see parsimony help)", rest[0])
|
|
}
|
|
handler, ok := group[rest[1]]
|
|
if !ok {
|
|
return c.usageError("unknown command %q (see parsimony help)", rest[0]+" "+rest[1])
|
|
}
|
|
return handler(rest[2:])
|
|
}
|
|
|
|
// cmd holds what every command needs.
|
|
type cmd struct {
|
|
io IO
|
|
getenv func(string) string
|
|
url string
|
|
json bool
|
|
// insecure allows the token to travel over plain http to a non-loopback host.
|
|
insecure bool
|
|
cl *client
|
|
}
|
|
|
|
// usageErr is an error that is the caller's mistake: exit status 2.
|
|
type usageErr string
|
|
|
|
func (e usageErr) Error() string { return string(e) }
|
|
|
|
func (c *cmd) usageError(format string, a ...any) int {
|
|
fmt.Fprintf(c.io.Err, "error: "+format+"\n", a...)
|
|
return 2
|
|
}
|
|
|
|
func (c *cmd) fail(err error) int {
|
|
fmt.Fprintf(c.io.Err, "error: %s\n", printable(err.Error()))
|
|
var u usageErr
|
|
if errors.As(err, &u) {
|
|
return 2
|
|
}
|
|
return 1
|
|
}
|
|
|
|
// client builds the API client on first use, so usage errors never need a token.
|
|
func (c *cmd) client() (*client, error) {
|
|
if c.cl != nil {
|
|
return c.cl, nil
|
|
}
|
|
token := c.getenv("PARSIMONY_API_TOKEN")
|
|
if token == "" {
|
|
return nil, errors.New("PARSIMONY_API_TOKEN is not set")
|
|
}
|
|
base := c.url
|
|
if base == "" {
|
|
base = c.getenv("PARSIMONY_URL")
|
|
}
|
|
if base == "" {
|
|
base = "http://127.0.0.1:8080"
|
|
}
|
|
u, err := url.Parse(base)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid URL %q", base)
|
|
}
|
|
// url.Parse lowercases the scheme.
|
|
if u.Scheme == "http" && !isLoopback(u.Hostname()) && !c.insecure {
|
|
return nil, usageErr(fmt.Sprintf("refusing to send the token over plain http to %s: use https, or pass --insecure", u.Host))
|
|
}
|
|
c.cl = &client{
|
|
base: strings.TrimRight(base, "/"), token: token,
|
|
http: &http.Client{Timeout: 30 * time.Second},
|
|
upload: &http.Client{}, // big files: no overall timeout
|
|
}
|
|
return c.cl, nil
|
|
}
|
|
|
|
// newFlagSet returns a flag set that reports errors itself instead of printing usage.
|
|
func newFlagSet(name string) *flag.FlagSet {
|
|
fs := flag.NewFlagSet(name, flag.ContinueOnError)
|
|
fs.SetOutput(io.Discard)
|
|
return fs
|
|
}
|
|
|
|
// parseArgs parses flags that may appear before, between or after positional arguments.
|
|
func parseArgs(fs *flag.FlagSet, args []string) ([]string, error) {
|
|
var pos []string
|
|
for {
|
|
if err := fs.Parse(args); err != nil {
|
|
return nil, err
|
|
}
|
|
args = fs.Args()
|
|
if len(args) == 0 {
|
|
return pos, nil
|
|
}
|
|
pos = append(pos, args[0])
|
|
args = args[1:]
|
|
}
|
|
}
|
|
|
|
// --- API client ---------------------------------------------------------------
|
|
|
|
type client struct {
|
|
base, token string
|
|
http *http.Client // ordinary requests, with a timeout
|
|
upload *http.Client // streaming uploads, without one
|
|
}
|
|
|
|
type apiError struct {
|
|
status int
|
|
message string
|
|
}
|
|
|
|
func (e *apiError) Error() string { return e.message }
|
|
|
|
// do sends a JSON request and returns the raw response body (nil for 204).
|
|
func (cl *client) do(method, path string, body any) (json.RawMessage, error) {
|
|
var rd io.Reader
|
|
ctype := ""
|
|
if body != nil {
|
|
b, err := json.Marshal(body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rd, ctype = bytes.NewReader(b), "application/json"
|
|
}
|
|
return cl.send(cl.http, method, path, rd, ctype)
|
|
}
|
|
|
|
// uploadTo streams r as the body of a POST, with no overall timeout.
|
|
func (cl *client) uploadTo(path string, r io.Reader, contentType string) (json.RawMessage, error) {
|
|
return cl.send(cl.upload, "POST", path, r, contentType)
|
|
}
|
|
|
|
func (cl *client) send(hc *http.Client, method, path string, rd io.Reader, contentType string) (json.RawMessage, error) {
|
|
req, err := http.NewRequest(method, cl.base+"/api/v1"+path, rd)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+cl.token)
|
|
if contentType != "" {
|
|
req.Header.Set("Content-Type", contentType)
|
|
}
|
|
resp, err := hc.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cannot reach %s: %w", cl.base, errors.Unwrap(err))
|
|
}
|
|
defer resp.Body.Close()
|
|
data, _ := io.ReadAll(resp.Body)
|
|
if resp.StatusCode >= 300 {
|
|
msg := fmt.Sprintf("request failed (%d)", resp.StatusCode)
|
|
var e struct{ Error string }
|
|
if json.Unmarshal(data, &e) == nil && e.Error != "" {
|
|
msg = e.Error
|
|
}
|
|
return nil, &apiError{status: resp.StatusCode, message: msg}
|
|
}
|
|
if resp.StatusCode == http.StatusNoContent {
|
|
return nil, nil
|
|
}
|
|
return data, nil
|
|
}
|
|
|
|
func isNotFound(err error) bool {
|
|
var ae *apiError
|
|
return errors.As(err, &ae) && ae.status == http.StatusNotFound
|
|
}
|
|
|
|
// --- shared types and helpers ---------------------------------------------------
|
|
|
|
type list struct {
|
|
ID int64 `json:"id"`
|
|
Address string `json:"address"`
|
|
Title string `json:"title"`
|
|
PostPolicy string `json:"post_policy"`
|
|
JoinPolicy string `json:"join_policy"`
|
|
ArchivePolicy string `json:"archive_policy"`
|
|
}
|
|
|
|
// resolveList finds a list by numeric id or by address (case-insensitive).
|
|
func (c *cmd) resolveList(ref string) (list, error) {
|
|
cl, err := c.client()
|
|
if err != nil {
|
|
return list{}, err
|
|
}
|
|
if id, err := strconv.ParseInt(ref, 10, 64); err == nil {
|
|
raw, err := cl.do("GET", fmt.Sprintf("/lists/%d", id), nil)
|
|
if isNotFound(err) {
|
|
return list{}, fmt.Errorf("no such list: %s", ref)
|
|
}
|
|
if err != nil {
|
|
return list{}, err
|
|
}
|
|
var l list
|
|
return l, json.Unmarshal(raw, &l)
|
|
}
|
|
raw, err := cl.do("GET", "/lists", nil)
|
|
if err != nil {
|
|
return list{}, err
|
|
}
|
|
var all []list
|
|
if err := json.Unmarshal(raw, &all); err != nil {
|
|
return list{}, err
|
|
}
|
|
for _, l := range all {
|
|
if strings.EqualFold(l.Address, ref) {
|
|
return l, nil
|
|
}
|
|
}
|
|
return list{}, fmt.Errorf("no such list: %s", ref)
|
|
}
|
|
|
|
// printJSON writes raw API JSON, indented.
|
|
func (c *cmd) printJSON(raw json.RawMessage) int {
|
|
if raw == nil {
|
|
raw = json.RawMessage(`{"status":"ok"}`)
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := json.Indent(&buf, raw, "", " "); err != nil {
|
|
return c.fail(err)
|
|
}
|
|
fmt.Fprintln(c.io.Out, buf.String())
|
|
return 0
|
|
}
|
|
|
|
// isLoopback reports whether host is this machine: localhost or a loopback address.
|
|
func isLoopback(host string) bool {
|
|
if strings.EqualFold(strings.TrimSuffix(host, "."), "localhost") {
|
|
return true
|
|
}
|
|
ip := net.ParseIP(host)
|
|
return ip != nil && ip.IsLoopback()
|
|
}
|
|
|
|
// printable makes text that came from mail or from the API safe for a terminal: control
|
|
// characters (C0, DEL, C1) other than tab and newline are shown as \xNN / \uNNNN instead of
|
|
// being sent, so an escape sequence in a subject cannot drive the terminal. CRLF counts as a newline.
|
|
func printable(s string) string {
|
|
s = strings.ReplaceAll(s, "\r\n", "\n")
|
|
var b strings.Builder
|
|
for _, r := range s {
|
|
switch {
|
|
case r == '\t' || r == '\n':
|
|
b.WriteRune(r)
|
|
case r < 0x20 || r == 0x7f:
|
|
fmt.Fprintf(&b, `\x%02x`, r)
|
|
case r >= 0x80 && r <= 0x9f:
|
|
fmt.Fprintf(&b, `\u%04x`, r)
|
|
default:
|
|
b.WriteRune(r)
|
|
}
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func (c *cmd) table(rows [][]string) {
|
|
w := tabwriter.NewWriter(c.io.Out, 0, 8, 2, ' ', 0)
|
|
for _, r := range rows {
|
|
cells := make([]string, len(r))
|
|
for i, cell := range r {
|
|
cells[i] = printable(cell)
|
|
}
|
|
fmt.Fprintln(w, strings.Join(cells, "\t"))
|
|
}
|
|
w.Flush()
|
|
}
|
|
|
|
func parseID(s string) (int64, bool) {
|
|
id, err := strconv.ParseInt(s, 10, 64)
|
|
return id, err == nil && id > 0
|
|
}
|
|
|
|
func formatDate(t time.Time) string { return t.UTC().Format("2006-01-02 15:04") }
|
|
|
|
func formatBytes(n int) string {
|
|
switch {
|
|
case n < 1024:
|
|
return fmt.Sprintf("%d B", n)
|
|
case n < 1024*1024:
|
|
return fmt.Sprintf("%.1f KB", float64(n)/1024)
|
|
}
|
|
return fmt.Sprintf("%.1f MB", float64(n)/(1024*1024))
|
|
}
|