Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): add admin api transport over the operator relay

Hampus5c42e57e66cf
diff --git a/fluxer_rexctl/internal/adminapi/client.go b/fluxer_rexctl/internal/adminapi/client.go
new file mode 100644
index 000000000..35d78a301
--- /dev/null
+++ b/fluxer_rexctl/internal/adminapi/client.go
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package adminapi
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+)
+
+const SchemaMajor = 1
+
+type Client struct {
+ t Transport
+ Version string
+ OnSkew func(apiVersion string)
+ skewOnce sync.Once
+}
+
+func New(t Transport, version string) *Client { return &Client{t: t, Version: version} }
+
+func (c *Client) Transport() Transport { return c.t }
+
+type RawBody struct {
+ ContentType string
+ Data []byte
+}
+
+func (c *Client) Call(ctx context.Context, method, path string, query map[string]string, in, out any) error {
+ if !strings.HasPrefix(path, "/admin/") {
+ return fmt.Errorf("adminapi: %s is not an admin path", path)
+ }
+ req := Request{Target: TargetOperator, Method: method, Path: path, Query: query}
+ return c.do(ctx, req, in, out)
+}
+
+func (c *Client) CallWithHeaders(ctx context.Context, method, path string, query, headers map[string]string, in, out any) error {
+ if !strings.HasPrefix(path, "/admin/") {
+ return fmt.Errorf("adminapi: %s is not an admin path", path)
+ }
+ req := Request{Target: TargetOperator, Method: method, Path: path, Query: query, Headers: headers}
+ return c.do(ctx, req, in, out)
+}
+
+func (c *Client) Loopback(ctx context.Context, method, path string, headers map[string]string, in, out any) error {
+ req := Request{Target: TargetLoopback, Method: method, Path: path, Headers: headers}
+ return c.do(ctx, req, in, out)
+}
+
+func (c *Client) do(ctx context.Context, req Request, in, out any) error {
+ switch body := in.(type) {
+ case nil:
+ case RawBody:
+ req.BodyBase64 = base64.StdEncoding.EncodeToString(body.Data)
+ if req.Headers == nil {
+ req.Headers = map[string]string{}
+ }
+ req.Headers["Content-Type"] = body.ContentType
+ case json.RawMessage:
+ req.Body = body
+ default:
+ data, err := json.Marshal(body)
+ if err != nil {
+ return err
+ }
+ req.Body = data
+ }
+ resp, err := c.t.Do(ctx, req)
+ if err != nil {
+ return err
+ }
+ if resp.RelayError != "" || resp.Status == 0 {
+ return &RelayError{Detail: firstLine(resp.RelayError, "no response from the api")}
+ }
+ c.checkSkew(resp.APIVersion)
+ if resp.SchemaMajor != 0 && resp.SchemaMajor != SchemaMajor {
+ return ErrSchemaMismatch
+ }
+ if resp.Status >= 400 {
+ return decodeAPIError(resp)
+ }
+ if out == nil || len(bytes.TrimSpace(resp.Body)) == 0 || string(bytes.TrimSpace(resp.Body)) == "null" {
+ return nil
+ }
+ if err := json.Unmarshal(resp.Body, out); err != nil {
+ return fmt.Errorf("adminapi: decode %s %s: %w", req.Method, req.Path, err)
+ }
+ return nil
+}
+
+func (c *Client) checkSkew(apiVersion string) {
+ if apiVersion == "" || c.Version == "" || apiVersion == c.Version || c.Version == "dev" {
+ return
+ }
+ c.skewOnce.Do(func() {
+ if c.OnSkew != nil {
+ c.OnSkew(apiVersion)
+ }
+ })
+}
+
+func decodeAPIError(resp *Response) error {
+ e := &APIError{Status: resp.Status, Body: resp.Body}
+ var body struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Errors []FieldError `json:"errors"`
+ }
+ if err := json.Unmarshal(resp.Body, &body); err == nil {
+ e.Code, e.Message, e.Fields = body.Code, body.Message, body.Errors
+ return e
+ }
+ var text string
+ if err := json.Unmarshal(resp.Body, &text); err == nil {
+ e.Message = firstLine(text, "")
+ }
+ return e
+}
+
+func IsStatus(err error, status int) bool {
+ var e *APIError
+ return errors.As(err, &e) && e.Status == status
+}
diff --git a/fluxer_rexctl/internal/adminapi/explain.go b/fluxer_rexctl/internal/adminapi/explain.go
new file mode 100644
index 000000000..474c8f614
--- /dev/null
+++ b/fluxer_rexctl/internal/adminapi/explain.go
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package adminapi
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
+)
+
+func Explain(err error) error {
+ if err == nil {
+ return nil
+ }
+ var ee *ui.ExitError
+ if errors.As(err, &ee) || errors.Is(err, context.Canceled) {
+ return err
+ }
+ var relay *RelayError
+ var api *APIError
+ var notFound *UserNotFoundError
+ var ambiguous *AmbiguousUserError
+ var invite *InviteNotFoundError
+ var pending *PendingNotFoundError
+ var unknown *UnknownKeyError
+ var invalid *InvalidValueError
+ var banBlocks *BanBlocksDeletionError
+ switch {
+ case errors.Is(err, ErrSchemaMismatch):
+ return &ui.ExitError{Code: ui.ExitRefused, Msg: "This rexctl and the Fluxer running here don't match.", Fix: "Run rexctl upgrade.", Err: err}
+ case errors.Is(err, ErrNoRelay):
+ return &ui.ExitError{Code: ui.ExitRefused, Msg: "The Fluxer release running here can't take commands from rexctl.", Fix: "Run rexctl upgrade.", Err: err}
+ case errors.As(err, &relay):
+ return &ui.ExitError{Code: ui.ExitFailed, Msg: "Couldn't connect to Fluxer on this machine.", Fix: "Run rexctl status to check that it's running.", Err: err}
+ case errors.As(err, &notFound):
+ return ui.Failed(fmt.Sprintf("There's no account called %s.", notFound.Ref), "Run rexctl users list --search to find it.")
+ case errors.As(err, &ambiguous):
+ ids := make([]string, 0, len(ambiguous.Matches))
+ for _, m := range ambiguous.Matches {
+ ids = append(ids, m.ID)
+ }
+ return ui.Failed(fmt.Sprintf("%d accounts are called %s.", len(ambiguous.Matches), ambiguous.Ref), fmt.Sprintf("Pass a user ID. Theirs are %s.", joinAnd(ids)))
+ case errors.As(err, &banBlocks):
+ return ui.Refused(fmt.Sprintf("%s is banned for a reason that doesn't allow closing the account.", banBlocks.Username), fmt.Sprintf("Run rexctl users unban %s, then delete the account.", banBlocks.Username))
+ case errors.As(err, &invite):
+ return ui.Failed(fmt.Sprintf("There's no invite with the ID %s.", invite.ID), "Run rexctl invites list to see your invites.")
+ case errors.As(err, &pending):
+ return ui.Failed(fmt.Sprintf("Nobody waiting for approval has the ID %s.", pending.ID), "Run rexctl registration pending to see who is waiting.")
+ case errors.As(err, &unknown):
+ fix := "Run rexctl config list to see every setting."
+ if len(unknown.Similar) > 0 && len(unknown.Similar) <= 3 {
+ fix = "Did you mean " + JoinOr(unknown.Similar) + "?"
+ }
+ return &ui.ExitError{Code: ui.ExitUsage, Msg: fmt.Sprintf("There's no setting called %s.", unknown.Key), Fix: fix}
+ case errors.As(err, &invalid):
+ return ui.Usage(fmt.Sprintf("%s needs %s.", invalid.Key.Key, invalid.Want))
+ case errors.As(err, &api):
+ return explainAPI(api)
+ }
+ return ui.Wrap(err, "Something went wrong talking to Fluxer.", "Run rexctl logs api to see why.")
+}
+
+func sentence(s string) string {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return s
+ }
+ if !strings.HasSuffix(s, ".") && !strings.HasSuffix(s, "?") && !strings.HasSuffix(s, "!") {
+ s += "."
+ }
+ return strings.ToUpper(s[:1]) + s[1:]
+}
+
+func explainAPI(e *APIError) error {
+ switch {
+ case e.Status == http.StatusNotFound && e.Code == "":
+ return &ui.ExitError{Code: ui.ExitFailed, Msg: "The Fluxer running here can't do this yet.", Fix: "Run rexctl upgrade.", Err: e}
+ case e.Status == http.StatusUnauthorized || e.Status == http.StatusForbidden:
+ return &ui.ExitError{Code: ui.ExitRefused, Msg: "Fluxer turned down the request.", Fix: "Run rexctl upgrade, then try again.", Err: e}
+ case e.Status == http.StatusTooManyRequests:
+ return &ui.ExitError{Code: ui.ExitFailed, Msg: "Fluxer is limiting how fast it takes these requests.", Fix: "Wait a minute, then try again.", Err: e}
+ case e.Status >= 500:
+ return &ui.ExitError{Code: ui.ExitFailed, Msg: "Fluxer ran into an error.", Fix: "Run rexctl logs api to see why.", Err: e}
+ }
+ msg := sentence(e.Error())
+ if msg == "" {
+ msg = "Fluxer didn't accept that."
+ }
+ return &ui.ExitError{Code: ui.ExitFailed, Msg: msg, Err: e}
+}
diff --git a/fluxer_rexctl/internal/adminapi/transport.go b/fluxer_rexctl/internal/adminapi/transport.go
new file mode 100644
index 000000000..1a17bcc77
--- /dev/null
+++ b/fluxer_rexctl/internal/adminapi/transport.go
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package adminapi
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ osuser "os/user"
+ "strings"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
+)
+
+const (
+ RelayService = "api"
+ RelayPath = "/usr/src/app/fluxer_api/bin/operator-relay.mjs"
+ RelayNode = "node"
+)
+
+type Target string
+
+const (
+ TargetOperator Target = "operator"
+ TargetLoopback Target = "loopback"
+)
+
+type Request struct {
+ Target Target `json:"target"`
+ Method string `json:"method"`
+ Path string `json:"path"`
+ Query map[string]string `json:"query,omitempty"`
+ Headers map[string]string `json:"headers,omitempty"`
+ Body json.RawMessage `json:"body,omitempty"`
+ BodyBase64 string `json:"body_base64,omitempty"`
+ HostUser string `json:"host_user,omitempty"`
+}
+
+type Response struct {
+ Status int `json:"status"`
+ Headers map[string]string `json:"headers,omitempty"`
+ Body json.RawMessage `json:"body,omitempty"`
+ APIVersion string `json:"api_version"`
+ SchemaMajor int `json:"schema_major"`
+ RelayError string `json:"relay_error,omitempty"`
+}
+
+type Transport interface {
+ Do(ctx context.Context, req Request) (*Response, error)
+}
+
+type ExecTransport struct {
+ Project *engine.Project
+ HostUser string
+}
+
+func NewExec(p *engine.Project) *ExecTransport {
+ return &ExecTransport{Project: p, HostUser: HostUser()}
+}
+
+func (t *ExecTransport) Do(ctx context.Context, req Request) (*Response, error) {
+ if req.HostUser == "" {
+ req.HostUser = t.HostUser
+ }
+ payload, err := json.Marshal(req)
+ if err != nil {
+ return nil, err
+ }
+ var stdout, stderr bytes.Buffer
+ err = t.Project.Exec(ctx, RelayService, engine.ExecOptions{
+ Stdin: bytes.NewReader(payload),
+ Stdout: &stdout,
+ Stderr: &stderr,
+ }, RelayNode, RelayPath)
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ if err != nil {
+ if missing := stderr.String(); strings.Contains(missing, "Cannot find module") && strings.Contains(missing, RelayPath) {
+ return nil, &RelayError{Detail: "this Fluxer release has no " + RelayPath, Err: ErrNoRelay}
+ }
+ return nil, &RelayError{Detail: firstLine(stderr.String(), err.Error()), Err: err}
+ }
+ var resp Response
+ if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &resp); err != nil {
+ return nil, &RelayError{Detail: firstLine(stderr.String(), "the relay wrote no response"), Err: err}
+ }
+ return &resp, nil
+}
+
+func firstLine(s, fallback string) string {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return fallback
+ }
+ if i := strings.IndexByte(s, '\n'); i >= 0 {
+ return strings.TrimSpace(s[:i])
+ }
+ return s
+}
+
+func HostUser() string {
+ for _, key := range []string{"SUDO_USER", "USER", "USERNAME"} {
+ if v := strings.TrimSpace(os.Getenv(key)); v != "" {
+ return v
+ }
+ }
+ if u, err := osuser.Current(); err == nil {
+ return u.Username
+ }
+ return ""
+}
+
+type RelayError struct {
+ Detail string
+ Err error
+}
+
+func (e *RelayError) Error() string { return "adminapi: relay: " + e.Detail }
+
+func (e *RelayError) Unwrap() error { return e.Err }
+
+type FieldError struct {
+ Path string `json:"path"`
+ Code string `json:"code,omitempty"`
+ Message string `json:"message"`
+}
+
+type APIError struct {
+ Status int
+ Code string
+ Message string
+ Fields []FieldError
+ Body json.RawMessage
+}
+
+func (e *APIError) Error() string {
+ msg := e.Message
+ if len(e.Fields) > 0 {
+ f := e.Fields[0]
+ if f.Path != "" {
+ msg = fmt.Sprintf("Fluxer didn't accept the value for %s. %s", fieldName(f.Path), f.Message)
+ } else {
+ msg = f.Message
+ }
+ }
+ if msg != "" {
+ return msg
+ }
+ return fmt.Sprintf("admin API returned %d", e.Status)
+}
+
+func fieldName(path string) string {
+ parts := strings.FieldsFunc(path, func(r rune) bool { return r == '.' || r == '[' || r == ']' })
+ for i := len(parts) - 1; i >= 0; i-- {
+ if strings.Trim(parts[i], "0123456789") != "" {
+ return strings.ReplaceAll(parts[i], "_", " ")
+ }
+ }
+ return path
+}
+
+var ErrNoRelay = errors.New("adminapi: this Fluxer release has no operator relay")
+
+var ErrSchemaMismatch = errors.New("adminapi: rexctl and Fluxer versions differ")