| 1 | // Package equipo is Base's client for Equipo's person API (v1): signing a |
| 2 | // device in for a member, and the Assistant's chat behind "Ask Base |
| 3 | // anything". Base calls Equipo server to server with the member's bearer; |
| 4 | // the bearer never reaches a browser. |
| 5 | // |
| 6 | // The shapes mirror Equipo's handlers (internal/wire/api.go and |
| 7 | // assistant.go, internal/equipo/personapi/devices.go and |
| 8 | // chat/assistant_http.go), reading only the fields Base uses. |
| 9 | package equipo |
| 10 | |
| 11 | import ( |
| 12 | "bytes" |
| 13 | "context" |
| 14 | "crypto/ed25519" |
| 15 | "crypto/rand" |
| 16 | "encoding/base64" |
| 17 | "encoding/json" |
| 18 | "errors" |
| 19 | "fmt" |
| 20 | "io" |
| 21 | "net/http" |
| 22 | "net/url" |
| 23 | "strconv" |
| 24 | "strings" |
| 25 | "time" |
| 26 | ) |
| 27 | |
| 28 | // Error is a non-2xx answer from Equipo: its status and error code, and |
| 29 | // for an upload or a read its Retry-After, if it gave one. |
| 30 | type Error struct { |
| 31 | Status int |
| 32 | Code string |
| 33 | RetryAfter string |
| 34 | } |
| 35 | |
| 36 | func (e *Error) Error() string { return fmt.Sprintf("equipo: %d %s", e.Status, e.Code) } |
| 37 | |
| 38 | // Is lets errors.Is match the sentinel errors below by status and code. |
| 39 | func (e *Error) Is(target error) bool { |
| 40 | t, ok := target.(*Error) |
| 41 | return ok && t.Status == e.Status && (t.Code == "" || t.Code == e.Code) |
| 42 | } |
| 43 | |
| 44 | var ( |
| 45 | // ErrUnauthenticated: the bearer is revoked, expired or its person |
| 46 | // removed. The member must reconnect. |
| 47 | ErrUnauthenticated = &Error{Status: 401} |
| 48 | // ErrPending: the sign-in code is not approved yet. |
| 49 | ErrPending = &Error{Status: 409, Code: "authorization_pending"} |
| 50 | // ErrSlowDown: asked again too soon. |
| 51 | ErrSlowDown = &Error{Status: 429} |
| 52 | // ErrExpired: the sign-in code expired; start again. |
| 53 | ErrExpired = &Error{Status: 410} |
| 54 | // ErrNoRunner: the person has no runner, so the Assistant cannot |
| 55 | // answer a message or a question. |
| 56 | ErrNoRunner = &Error{Status: 409, Code: "no_runner"} |
| 57 | // ErrRunnerTooOld: the person's runner is too old for the Assistant. |
| 58 | ErrRunnerTooOld = &Error{Status: 409, Code: "runner_too_old"} |
| 59 | ) |
| 60 | |
| 61 | // Challenge is POST /api/v1/auth/devices's answer. |
| 62 | type Challenge struct { |
| 63 | ID string `json:"id"` |
| 64 | DeviceSecret string `json:"device_secret"` |
| 65 | UserCode string `json:"user_code"` |
| 66 | Challenge string `json:"challenge"` |
| 67 | VerificationURI string `json:"verification_uri"` |
| 68 | ExpiresAt time.Time `json:"expires_at"` |
| 69 | } |
| 70 | |
| 71 | // Proof is the body of POST /api/v1/auth/devices/exchange. |
| 72 | type Proof struct { |
| 73 | ID string `json:"id"` |
| 74 | DeviceSecret string `json:"device_secret"` |
| 75 | Challenge string `json:"challenge"` |
| 76 | Nonce string `json:"nonce"` |
| 77 | Signature string `json:"signature"` |
| 78 | } |
| 79 | |
| 80 | // Credential is a device's bearer. Revision is the device's revision (the |
| 81 | // exchange's ETag), which revoking it must name. |
| 82 | type Credential struct { |
| 83 | ID string `json:"id"` |
| 84 | Token string `json:"token"` |
| 85 | ExpiresAt time.Time `json:"expires_at"` |
| 86 | Revision int64 `json:"-"` |
| 87 | } |
| 88 | |
| 89 | // Client calls one Equipo instance. |
| 90 | type Client struct { |
| 91 | origin string |
| 92 | http *http.Client |
| 93 | // StreamHeaderTimeout bounds the wait for the event stream's headers. |
| 94 | StreamHeaderTimeout time.Duration |
| 95 | // FileTimeout bounds an upload, and the wait for a file's headers |
| 96 | // (60 s when zero). |
| 97 | FileTimeout time.Duration |
| 98 | } |
| 99 | |
| 100 | // New is a client for the Equipo at origin. It never follows a redirect, |
| 101 | // so a bearer goes nowhere but origin. |
| 102 | func New(origin string) *Client { |
| 103 | return &Client{origin: strings.TrimRight(origin, "/"), StreamHeaderTimeout: 15 * time.Second, http: &http.Client{ |
| 104 | CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| 105 | }} |
| 106 | } |
| 107 | |
| 108 | // Origin is the instance's origin. |
| 109 | func (c *Client) Origin() string { return c.origin } |
| 110 | |
| 111 | // callTimeout bounds every call but the event stream. |
| 112 | const callTimeout = 20 * time.Second |
| 113 | |
| 114 | // call sends one request. token is the bearer ("" for the device routes); |
| 115 | // key, when set, is the Idempotency-Key. A 2xx body is decoded into out. |
| 116 | func (c *Client) call(ctx context.Context, method, path, token, key string, header http.Header, in, out any) (http.Header, error) { |
| 117 | ctx, cancel := context.WithTimeout(ctx, callTimeout) |
| 118 | defer cancel() |
| 119 | var body io.Reader |
| 120 | if in != nil { |
| 121 | raw, err := json.Marshal(in) |
| 122 | if err != nil { |
| 123 | return nil, err |
| 124 | } |
| 125 | body = bytes.NewReader(raw) |
| 126 | } |
| 127 | req, err := http.NewRequestWithContext(ctx, method, c.origin+path, body) |
| 128 | if err != nil { |
| 129 | return nil, err |
| 130 | } |
| 131 | for k, v := range header { |
| 132 | req.Header[k] = v |
| 133 | } |
| 134 | if in != nil { |
| 135 | req.Header.Set("Content-Type", "application/json") |
| 136 | } |
| 137 | req.Header.Set("Accept", "application/json") |
| 138 | setCapabilities(ctx, req) |
| 139 | if token != "" { |
| 140 | req.Header.Set("Authorization", "Bearer "+token) |
| 141 | } |
| 142 | if key != "" { |
| 143 | req.Header.Set("Idempotency-Key", key) |
| 144 | } |
| 145 | res, err := c.http.Do(req) |
| 146 | if err != nil { |
| 147 | return nil, err |
| 148 | } |
| 149 | defer res.Body.Close() |
| 150 | raw, err := io.ReadAll(io.LimitReader(res.Body, 4<<20)) |
| 151 | if err != nil { |
| 152 | return nil, err |
| 153 | } |
| 154 | if res.StatusCode < 200 || res.StatusCode > 299 { |
| 155 | var e struct { |
| 156 | Code string `json:"code"` |
| 157 | } |
| 158 | _ = json.Unmarshal(raw, &e) |
| 159 | return res.Header, &Error{Status: res.StatusCode, Code: e.Code} |
| 160 | } |
| 161 | if out != nil && len(raw) > 0 { |
| 162 | if err := json.Unmarshal(raw, out); err != nil { |
| 163 | return nil, fmt.Errorf("equipo: %s %s: %w", method, path, err) |
| 164 | } |
| 165 | } |
| 166 | return res.Header, nil |
| 167 | } |
| 168 | |
| 169 | // NewKey is a fresh request key: Idempotency-Key, or a message's key. |
| 170 | func NewKey() string { return rand.Text() } |
| 171 | |
| 172 | // BeginDevice asks Equipo to sign in a device with public key pub; label |
| 173 | // is what the person sees when approving it. |
| 174 | func (c *Client) BeginDevice(ctx context.Context, pub ed25519.PublicKey, label string) (Challenge, error) { |
| 175 | var out Challenge |
| 176 | in := map[string]string{"public_key": base64.RawURLEncoding.EncodeToString(pub), "label": label} |
| 177 | _, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices", "", NewKey(), nil, in, &out) |
| 178 | return out, err |
| 179 | } |
| 180 | |
| 181 | // Prove signs ch with the device's key and nonce, as the exchange wants: |
| 182 | // Ed25519 over the compact JSON array |
| 183 | // ["equipo.person.device.v1", instance, id, challenge, nonce], where the |
| 184 | // instance is the first element of the decoded challenge. |
| 185 | func Prove(key ed25519.PrivateKey, ch Challenge, nonce string) (Proof, error) { |
| 186 | raw, err := base64.RawURLEncoding.DecodeString(ch.Challenge) |
| 187 | if err != nil { |
| 188 | return Proof{}, fmt.Errorf("equipo: challenge: %w", err) |
| 189 | } |
| 190 | var parts []string |
| 191 | if err := json.Unmarshal(raw, &parts); err != nil || len(parts) == 0 { |
| 192 | return Proof{}, errors.New("equipo: challenge is not a JSON array") |
| 193 | } |
| 194 | p := Proof{ID: ch.ID, DeviceSecret: ch.DeviceSecret, Challenge: ch.Challenge, Nonce: nonce} |
| 195 | msg, _ := json.Marshal([]string{"equipo.person.device.v1", parts[0], p.ID, p.Challenge, p.Nonce}) |
| 196 | p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, msg)) |
| 197 | return p, nil |
| 198 | } |
| 199 | |
| 200 | // Exchange trades an approved proof for a bearer: ErrPending until the |
| 201 | // person approves, ErrSlowDown when asked too soon, ErrExpired once the |
| 202 | // code has expired. The same proof and nonce may be sent again. |
| 203 | func (c *Client) Exchange(ctx context.Context, p Proof) (Credential, error) { |
| 204 | var out Credential |
| 205 | h, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices/exchange", "", NewKey(), nil, p, &out) |
| 206 | if err != nil { |
| 207 | return Credential{}, err |
| 208 | } |
| 209 | out.Revision, _ = strconv.ParseInt(strings.Trim(h.Get("ETag"), `"`), 10, 64) |
| 210 | return out, nil |
| 211 | } |
| 212 | |
| 213 | // RevokeDevice revokes device id, signed in as itself, at revision. |
| 214 | func (c *Client) RevokeDevice(ctx context.Context, token, id string, revision int64) error { |
| 215 | h := http.Header{"If-Match": {`"` + strconv.FormatInt(revision, 10) + `"`}} |
| 216 | _, err := c.call(ctx, http.MethodDelete, "/api/v1/auth/devices/"+url.PathEscape(id), token, NewKey(), h, struct{}{}, nil) |
| 217 | return err |
| 218 | } |
| 219 | |