oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 "io"
11 "net/http"
12 "strconv"
13 "strings"
14 "time"
15)
16
17// Equipo's own native sign-in with Oficina ID, which Base completes for a
18// member whose native app hands it an assertion addressed to Equipo
19// (Equipo's internal/equipo/oficinaid/native.go and
20// personapi/native_device.go). It ends in the same person credential the
21// code flow does, which lasts only as long as the Equipo session it was
22// registered with: seven days, or until the person signs out of Equipo, is
23// relinked or leaves the roster.
24
25var (
26 // ErrNotLinked: Equipo has no roster member linked to the assertion's
27 // Oficina ID (403 unknown).
28 ErrNotLinked = &Error{Status: http.StatusForbidden, Code: "unknown"}
29 // ErrAssertionFailed: Equipo did not accept the assertion (bad,
30 // expired, wrong audience or verifier, or already used): a fresh one
31 // may be tried (401 failed).
32 ErrAssertionFailed = &Error{Status: http.StatusUnauthorized, Code: "failed"}
33 // ErrAssertionInvalid: Equipo could not read the request (400 invalid).
34 ErrAssertionInvalid = &Error{Status: http.StatusBadRequest, Code: "invalid"}
35)
36
37// NativeSession is Equipo's native session: its cookie, and when it ends.
38type NativeSession struct {
39 Name string
40 Value string
41 ExpiresAt time.Time
42}
43
44// Cookie is the session as a Cookie header's value.
45func (s NativeSession) Cookie() string { return s.Name + "=" + s.Value }
46
47// NativeExchange trades an Oficina ID assertion addressed to Equipo, with
48// its verifier, for an Equipo native session. Like the native app it
49// stands in for, it sends no Origin and no cookie. A refusal is an *Error
50// whose Code is Equipo's state (ErrNotLinked, ErrAssertionFailed,
51// ErrAssertionInvalid, or a 503 "unavailable").
52func (c *Client) NativeExchange(ctx context.Context, assertion, verifier string) (NativeSession, error) {
53 ctx, cancel := context.WithTimeout(ctx, callTimeout)
54 defer cancel()
55 raw, err := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
56 if err != nil {
57 return NativeSession{}, err
58 }
59 req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.origin+"/native/oficina-id", bytes.NewReader(raw))
60 if err != nil {
61 return NativeSession{}, err
62 }
63 req.Header.Set("Content-Type", "application/json")
64 req.Header.Set("Accept", "application/json")
65 res, err := c.http.Do(req)
66 if err != nil {
67 return NativeSession{}, err
68 }
69 defer res.Body.Close()
70 body, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
71 if err != nil {
72 return NativeSession{}, err
73 }
74 if res.StatusCode != http.StatusOK {
75 var e struct {
76 State string `json:"state"`
77 }
78 _ = json.Unmarshal(body, &e)
79 return NativeSession{}, &Error{Status: res.StatusCode, Code: e.State}
80 }
81 var out struct {
82 Name string `json:"name"`
83 Value string `json:"value"`
84 ExpiresAt int64 `json:"expires_at"`
85 }
86 if err := json.Unmarshal(body, &out); err != nil {
87 return NativeSession{}, fmt.Errorf("equipo: native exchange: %w", err)
88 }
89 if !cookieToken(out.Name) || !cookieToken(out.Value) || out.ExpiresAt <= 0 {
90 return NativeSession{}, fmt.Errorf("equipo: native exchange: an unusable session")
91 }
92 return NativeSession{Name: out.Name, Value: out.Value, ExpiresAt: time.Unix(out.ExpiresAt, 0).UTC()}, nil
93}
94
95// cookieToken reports whether s may stand in a Cookie header as a name or
96// value: 1 to 4096 printable ASCII characters, none of them a separator.
97func cookieToken(s string) bool {
98 if s == "" || len(s) > 4096 {
99 return false
100 }
101 for _, r := range s {
102 if r <= ' ' || r >= 0x7f || strings.ContainsRune(`";,\=`, r) {
103 return false
104 }
105 }
106 return true
107}
108
109// RegisterNative registers a device key pub, labelled label, with the
110// person's Equipo native session s, and returns its credential: the same
111// kind as the code flow's (audience equipo.person.v1), ending with s. It
112// sends s's cookie and Equipo's own Origin, as Equipo's CSRF check wants
113// on a cookie mutation, and nothing of Base's.
114func (c *Client) RegisterNative(ctx context.Context, s NativeSession, pub ed25519.PublicKey, label string) (Credential, error) {
115 var out Credential
116 h := http.Header{"Cookie": {s.Cookie()}, "Origin": {c.origin}}
117 in := map[string]string{"public_key": base64.RawURLEncoding.EncodeToString(pub), "label": label}
118 hdr, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices/native", "", NewKey(), h, in, &out)
119 if err != nil {
120 return Credential{}, err
121 }
122 if out.ID == "" || out.Token == "" {
123 return Credential{}, fmt.Errorf("equipo: native device: no credential")
124 }
125 out.Revision, _ = strconv.ParseInt(strings.Trim(hdr.Get("ETag"), `"`), 10, 64)
126 return out, nil
127}
128