package equipo import ( "bytes" "context" "crypto/ed25519" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "strconv" "strings" "time" ) // Equipo's own native sign-in with Oficina ID, which Base completes for a // member whose native app hands it an assertion addressed to Equipo // (Equipo's internal/equipo/oficinaid/native.go and // personapi/native_device.go). It ends in the same person credential the // code flow does, which lasts only as long as the Equipo session it was // registered with: seven days, or until the person signs out of Equipo, is // relinked or leaves the roster. var ( // ErrNotLinked: Equipo has no roster member linked to the assertion's // Oficina ID (403 unknown). ErrNotLinked = &Error{Status: http.StatusForbidden, Code: "unknown"} // ErrAssertionFailed: Equipo did not accept the assertion (bad, // expired, wrong audience or verifier, or already used): a fresh one // may be tried (401 failed). ErrAssertionFailed = &Error{Status: http.StatusUnauthorized, Code: "failed"} // ErrAssertionInvalid: Equipo could not read the request (400 invalid). ErrAssertionInvalid = &Error{Status: http.StatusBadRequest, Code: "invalid"} ) // NativeSession is Equipo's native session: its cookie, and when it ends. type NativeSession struct { Name string Value string ExpiresAt time.Time } // Cookie is the session as a Cookie header's value. func (s NativeSession) Cookie() string { return s.Name + "=" + s.Value } // NativeExchange trades an Oficina ID assertion addressed to Equipo, with // its verifier, for an Equipo native session. Like the native app it // stands in for, it sends no Origin and no cookie. A refusal is an *Error // whose Code is Equipo's state (ErrNotLinked, ErrAssertionFailed, // ErrAssertionInvalid, or a 503 "unavailable"). func (c *Client) NativeExchange(ctx context.Context, assertion, verifier string) (NativeSession, error) { ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() raw, err := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier}) if err != nil { return NativeSession{}, err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.origin+"/native/oficina-id", bytes.NewReader(raw)) if err != nil { return NativeSession{}, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") res, err := c.http.Do(req) if err != nil { return NativeSession{}, err } defer res.Body.Close() body, err := io.ReadAll(io.LimitReader(res.Body, 64<<10)) if err != nil { return NativeSession{}, err } if res.StatusCode != http.StatusOK { var e struct { State string `json:"state"` } _ = json.Unmarshal(body, &e) return NativeSession{}, &Error{Status: res.StatusCode, Code: e.State} } var out struct { Name string `json:"name"` Value string `json:"value"` ExpiresAt int64 `json:"expires_at"` } if err := json.Unmarshal(body, &out); err != nil { return NativeSession{}, fmt.Errorf("equipo: native exchange: %w", err) } if !cookieToken(out.Name) || !cookieToken(out.Value) || out.ExpiresAt <= 0 { return NativeSession{}, fmt.Errorf("equipo: native exchange: an unusable session") } return NativeSession{Name: out.Name, Value: out.Value, ExpiresAt: time.Unix(out.ExpiresAt, 0).UTC()}, nil } // cookieToken reports whether s may stand in a Cookie header as a name or // value: 1 to 4096 printable ASCII characters, none of them a separator. func cookieToken(s string) bool { if s == "" || len(s) > 4096 { return false } for _, r := range s { if r <= ' ' || r >= 0x7f || strings.ContainsRune(`";,\=`, r) { return false } } return true } // RegisterNative registers a device key pub, labelled label, with the // person's Equipo native session s, and returns its credential: the same // kind as the code flow's (audience equipo.person.v1), ending with s. It // sends s's cookie and Equipo's own Origin, as Equipo's CSRF check wants // on a cookie mutation, and nothing of Base's. func (c *Client) RegisterNative(ctx context.Context, s NativeSession, pub ed25519.PublicKey, label string) (Credential, error) { var out Credential h := http.Header{"Cookie": {s.Cookie()}, "Origin": {c.origin}} in := map[string]string{"public_key": base64.RawURLEncoding.EncodeToString(pub), "label": label} hdr, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices/native", "", NewKey(), h, in, &out) if err != nil { return Credential{}, err } if out.ID == "" || out.Token == "" { return Credential{}, fmt.Errorf("equipo: native device: no credential") } out.Revision, _ = strconv.ParseInt(strings.Trim(hdr.Get("ETag"), `"`), 10, 64) return out, nil }