package integrations import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "regexp" "strings" "time" ) // The executor: runs one manifest op against the service's pinned host. The // manifest is reviewed code; the args and token are member input — so every // arg is bounded and escaped into the slot its template put it in, and the // final URL is re-checked against auth.base's host before anything is sent. // A value can steer WHAT an op says, never WHERE it goes. const ( maxArgs = 16 maxArgBytes = 2048 maxRespBody = 256 << 10 // response read cap for un-projected ops // A projected op may read much more: provider list responses run to // hundreds of KB raw (a real /user/repos page is ~400KB), and the pick // throws almost all of it away immediately — the projected result is what // travels, not this buffer. maxPickedRespBody = 4 << 20 execTimeout = 20 * time.Second ) // purePlaceholderRE matches a template that is EXACTLY one placeholder — the // shape of an optional-arg slot like `"body": "{body}"`, whose key is dropped // from the JSON when the arg is absent (so optional means absent, not ""). var purePlaceholderRE = regexp.MustCompile(`^\{[a-z0-9_]+\}$`) // StatusError is a non-2xx provider response. The message keeps the exact // shape errors always had; the code lets a caller distinguish "token expired" // (401 → refresh and retry) from "the request was wrong". type StatusError struct { Service, Op string Code int Detail string } func (e *StatusError) Error() string { return fmt.Sprintf("%s.%s: status %d: %s", e.Service, e.Op, e.Code, e.Detail) } // baseOverride returns the test-only base URL for a service, mirroring how // LCHAT_DNSIMPLE_BASE points the dnsimple client at a loopback httptest // server (internal/bot/dnsimple.go). Never set in production units. func baseOverride(id string) string { return os.Getenv("LCHAT_INTEGRATIONS_BASE_" + strings.ToUpper(strings.ReplaceAll(id, "-", "_"))) } // Execute runs one op with the member's args and token, returning the // response body as a string. Errors are values — the sidecar feeds them back // into the thread as an honest failure, never a silent gap. func Execute(m *Manifest, opID string, args map[string]string, token string) (string, error) { return ExecuteAs(m, opID, args, token, "") } // ExecuteAs is Execute plus the credential's kind ("pat" | "oauth"; "" for // legacy credentials stored before kinds existed). An OAuth token is a Bearer // token by definition (RFC 6750), whatever scheme the manifest picked for // pasted keys — Linear's personal API keys go bare while its OAuth tokens // carry Bearer. Any other kind keeps the manifest's scheme. func ExecuteAs(m *Manifest, opID string, args map[string]string, token, tokenKind string) (string, error) { op := m.Op(opID) if op == nil { // Absence is refusal: an op the manifest doesn't declare cannot run. return "", fmt.Errorf("%s: unknown op %q", m.ID, opID) } if err := validateArgs(op, args); err != nil { return "", fmt.Errorf("%s.%s: %w", m.ID, opID, err) } base := m.Auth.Base override := baseOverride(m.ID) if override != "" { base = override } baseURL, err := url.Parse(base) if err != nil || baseURL.Host == "" { return "", fmt.Errorf("%s.%s: bad base %q", m.ID, opID, base) } final := strings.TrimRight(base, "/") + renderPath(op.Path, args) u, err := url.Parse(final) if err != nil { return "", fmt.Errorf("%s.%s: bad url: %w", m.ID, opID, err) } // Pin the host: re-check the URL we actually built, not just the inputs — // if escaping ever failed to contain a value, this is the backstop. // Skipped only under the env override (loopback test servers are http). if override == "" { if u.Scheme != "https" || u.Host != baseURL.Host { return "", fmt.Errorf("%s.%s: url escaped its pinned host", m.ID, opID) } } var body io.Reader contentType := "" switch { case op.Encoding == "form": vals := url.Values{} for k, tmpl := range op.BodyForm { vals.Set(k, substitute(tmpl, args)) } body = strings.NewReader(vals.Encode()) contentType = "application/x-www-form-urlencoded" case op.BodyJSON != nil: rendered := substituteJSONMap(op.BodyJSON, args) raw, err := json.Marshal(rendered) if err != nil { return "", fmt.Errorf("%s.%s: body: %w", m.ID, opID, err) } body = bytes.NewReader(raw) contentType = "application/json" } req, err := http.NewRequest(op.Method, u.String(), body) if err != nil { return "", fmt.Errorf("%s.%s: %w", m.ID, opID, err) } // Default Accept first, then the manifest's headers — a manifest Accept // (GitHub's vnd header) wins over the default, never the reverse. req.Header.Set("Accept", "application/json") for k, v := range m.Auth.Headers { req.Header.Set(k, v) } scheme := m.Auth.Authorization if scheme == "" { scheme = "Bearer" } if tokenKind == "oauth" { scheme = "Bearer" } if scheme == "none" { // Bare-token APIs: Linear rejects a Bearer prefix on personal API // keys — the header value is the token alone. req.Header.Set("Authorization", token) } else { req.Header.Set("Authorization", scheme+" "+token) } if contentType != "" { req.Header.Set("Content-Type", contentType) } client := &http.Client{ Timeout: execTimeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { if len(via) >= 5 { return errors.New("too many redirects") } // A redirect is a new URL: hold it to the same pin. Off-host // redirects are refused outright — an integration API that // bounces us elsewhere is outside the manifest's contract. if req.URL.Host != u.Host { return errors.New("redirect off the pinned host blocked") } if override == "" && req.URL.Scheme != "https" { return errors.New("redirect downgraded from https blocked") } return nil }, } resp, err := client.Do(req) if err != nil { return "", fmt.Errorf("%s.%s: %w", m.ID, opID, err) } defer resp.Body.Close() readCap := int64(maxRespBody) if op.Pick != nil { readCap = maxPickedRespBody } raw, err := io.ReadAll(io.LimitReader(resp.Body, readCap+1)) if err != nil { return "", fmt.Errorf("%s.%s: read: %w", m.ID, opID, err) } // Over the cap: refuse honestly — a silently truncated body would surface // as a baffling JSON parse error (or worse, truncated data downstream). if int64(len(raw)) > readCap { return "", fmt.Errorf("%s.%s: response too large (over %d bytes)", m.ID, opID, readCap) } if resp.StatusCode/100 != 2 { snippet := raw if len(snippet) > 300 { snippet = snippet[:300] } // Typed so a caller can react to the code (the sidecar refreshes an // expired token on a 401) without parsing the message. return "", &StatusError{Service: m.ID, Op: opID, Code: resp.StatusCode, Detail: string(snippet)} } if op.Pick != nil { projected, err := project(raw, op.Pick) if err != nil { return "", fmt.Errorf("%s.%s: %w", m.ID, opID, err) } return projected, nil } return string(raw), nil } // project applies an op's declared response projection (registry.go's Pick): // descend the root path, then keep only the named fields of the object — or of // each object of the array — found there. The manifest is the review surface, // so a response that doesn't match its declared shape is an honest error, never // a silent empty result. func project(raw []byte, p *Pick) (string, error) { var v any if err := json.Unmarshal(raw, &v); err != nil { return "", fmt.Errorf("response isn't JSON: %w", err) } for _, key := range splitPath(p.Root) { obj, ok := v.(map[string]any) if !ok { return "", fmt.Errorf("response has no %q envelope", p.Root) } if v, ok = obj[key]; !ok { return "", fmt.Errorf("response has no %q envelope", p.Root) } } if len(p.Fields) > 0 { switch t := v.(type) { case []any: out := make([]any, 0, len(t)) for _, e := range t { if obj, ok := e.(map[string]any); ok { out = append(out, pickFields(obj, p.Fields)) } } v = out case map[string]any: v = pickFields(t, p.Fields) default: return "", fmt.Errorf("response %q isn't an object or array", p.Root) } } out, err := json.Marshal(v) if err != nil { return "", err } return string(out), nil } // pickFields projects one object down to the named dot-paths. A field the // response doesn't carry is omitted (provider APIs grow and shrink; the client // treats absence as "—"). The output key is the full dot-path, flat — so // "user.login" comes back as {"user.login": "octocat"}. func pickFields(obj map[string]any, fields []string) map[string]any { out := make(map[string]any, len(fields)) for _, f := range fields { v := any(obj) found := true for _, key := range splitPath(f) { m, ok := v.(map[string]any) if !ok { found = false break } if v, ok = m[key]; !ok { found = false break } } if found { out[f] = v } } return out } // splitPath splits a validated pick path into keys; "" is the empty path. func splitPath(p string) []string { if p == "" { return nil } return strings.Split(p, ".") } // validateArgs bounds member input before any of it touches a template: // declared keys only, required keys present, values short and free of // control characters. func validateArgs(op *Op, args map[string]string) error { if len(args) > maxArgs { return fmt.Errorf("too many args (%d > %d)", len(args), maxArgs) } for k, v := range args { if _, ok := op.Args[k]; !ok { return fmt.Errorf("undeclared arg %q", k) } if len(v) > maxArgBytes { return fmt.Errorf("arg %q too long (%d bytes)", k, len(v)) } for i := 0; i < len(v); i++ { if v[i] < 0x20 || v[i] == 0x7f { return fmt.Errorf("arg %q contains control characters", k) } } } for k, spec := range op.Args { if spec.Required && args[k] == "" { return fmt.Errorf("missing required arg %q", k) } } return nil } // renderPath substitutes `{arg}` into a path template, escaping each value // for the slot it lands in: path-segment escaping before the first "?", // query escaping after it. A value can never introduce an un-escaped // `/`, `?`, `#`, or `&` — it stays inside its segment or query slot. func renderPath(path string, args map[string]string) string { pathPart, queryPart, hasQuery := strings.Cut(path, "?") out := substituteWith(pathPart, args, escapePathValue) if hasQuery { out += "?" + substituteWith(queryPart, args, url.QueryEscape) } return out } // escapePathValue is url.PathEscape plus the sub-delims PathEscape leaves // alone (`&;=+,`). They're legal in a path segment, but our promise is // stronger than legality: a substituted value must not be able to smuggle // anything a server might parse as a delimiter. func escapePathValue(v string) string { return strings.NewReplacer( "&", "%26", ";", "%3B", "=", "%3D", "+", "%2B", ",", "%2C", ).Replace(url.PathEscape(v)) } // substitute replaces `{arg}` with the raw arg value (bodies — no URL // escaping; the encoder for the body format does its own). An absent // optional arg substitutes to "". func substitute(tmpl string, args map[string]string) string { return substituteWith(tmpl, args, func(s string) string { return s }) } func substituteWith(tmpl string, args map[string]string, escape func(string) string) string { return placeholderRE.ReplaceAllStringFunc(tmpl, func(ph string) string { return escape(args[ph[1:len(ph)-1]]) }) } // substituteJSONMap deep-copies a body_json template with `{arg}` substituted // into string leaves. Keys whose template was exactly one placeholder and // substituted to "" are dropped — an optional arg the member didn't give is // omitted from the request, not sent as an empty string. func substituteJSONMap(m map[string]any, args map[string]string) map[string]any { out := make(map[string]any, len(m)) for k, v := range m { switch t := v.(type) { case string: s := substitute(t, args) if s == "" && purePlaceholderRE.MatchString(t) { continue } out[k] = s case map[string]any: out[k] = substituteJSONMap(t, args) case []any: out[k] = substituteJSONSlice(t, args) default: out[k] = v } } return out } func substituteJSONSlice(s []any, args map[string]string) []any { out := make([]any, len(s)) for i, v := range s { switch t := v.(type) { case string: out[i] = substitute(t, args) case map[string]any: out[i] = substituteJSONMap(t, args) case []any: out[i] = substituteJSONSlice(t, args) default: out[i] = v } } return out }