package equipotest import ( "crypto/ed25519" "crypto/rand" "encoding/base64" "mime" "net/http" "net/url" "strings" "sync" "time" "unicode/utf8" ) // Equipo's own native sign-in with Oficina ID, as Base completes it for a // person (Equipo's internal/equipo/oficinaid/native.go and // personapi/native_device.go): // // - POST /native/oficina-id trades an assertion Oficina ID made for // Equipo, and its verifier, for a seven-day native session, only for a // subject Equipo has linked to a roster member. It refuses anything a // browser sends (Origin, Sec-Fetch-Site), and answers // {name, value, expires_at}, or {"state": …} with 400, 401 failed, // 403 unknown or 503. // - POST /api/v1/auth/devices/native, with that session's cookie and // Equipo's own Origin, registers a device key and answers its person // credential, which ends with the session. // // The fake does not verify signatures: OficinaAssertion hands out an opaque // assertion and its verifier, as Oficina ID would for Equipo, and the // exchange accepts each once. // SessionCookie is the name of the fake's session cookie. const SessionCookie = "__Host-equipo_session" // nativeLifetime is how long Equipo's native session, and every device // registered with it, lasts. const nativeLifetime = 7 * 24 * time.Hour type nativeSession struct { subject, address string at time.Time ended bool } type assertionGrant struct { subject, verifier string used bool } type nativeState struct { nmu sync.Mutex links map[string]string // Oficina subject → roster address assertions map[string]*assertionGrant sessions map[string]*nativeSession // cookie value → session failNative int // the next exchange's status, once // nativeHold, when set, stops the next exchange until it is closed; // nativeEntered is closed when that exchange arrives. nativeHold, nativeEntered chan struct{} } func (n *nativeState) init() { n.links, n.assertions, n.sessions = map[string]string{}, map[string]*assertionGrant{}, map[string]*nativeSession{} } // LinkOficinaID links the Oficina ID subject to the roster member address, // as signing in to Equipo with Oficina ID once does. func (f *Fake) LinkOficinaID(subject, address string) { f.nmu.Lock() defer f.nmu.Unlock() f.links[subject] = address } // OficinaAssertion is an assertion Oficina ID made for Equipo about // subject, and its verifier, as the native app fetches them. func (f *Fake) OficinaAssertion(subject string) (assertion, verifier string) { f.nmu.Lock() defer f.nmu.Unlock() assertion, verifier = "oficina."+rand.Text()+rand.Text(), rand.Text()+rand.Text() f.assertions[assertion] = &assertionGrant{subject: subject, verifier: verifier} return assertion, verifier } // FailNextNativeExchange makes the next native exchange answer status // (with its state), as Equipo does when it is down (503). func (f *Fake) FailNextNativeExchange(status int) { f.nmu.Lock() defer f.nmu.Unlock() f.failNative = status } // HoldNextNativeExchange makes the next native exchange wait, once it has // arrived and before it answers, until release is called: a test can act // in between. entered is closed when it arrives. func (f *Fake) HoldNextNativeExchange() (entered <-chan struct{}, release func()) { f.nmu.Lock() defer f.nmu.Unlock() f.nativeHold, f.nativeEntered = make(chan struct{}), make(chan struct{}) hold := f.nativeHold return f.nativeEntered, func() { close(hold) } } // NativeSessions is how many native sessions the fake has minted. func (f *Fake) NativeSessions() int { f.nmu.Lock() defer f.nmu.Unlock() return len(f.sessions) } // EndNativeSession ends the native session whose cookie is value, as // signing out of Equipo does, and revokes every device registered with it. func (f *Fake) EndNativeSession(value string) { f.nmu.Lock() if s := f.sessions[value]; s != nil { s.ended = true } f.nmu.Unlock() f.mu.Lock() defer f.mu.Unlock() for _, d := range f.devices { if d.session == value { d.revoked = true } } } // DeviceSession is the native session cookie the device with id was // registered with ("" for a device from the code flow). func (f *Fake) DeviceSession(id string) string { f.mu.Lock() defer f.mu.Unlock() if d := f.devices[id]; d != nil { return d.session } return "" } // LiveCredentials are the ids of the devices holding a credential Equipo // still takes: exchanged or registered, and not revoked. func (f *Fake) LiveCredentials() []string { f.mu.Lock() defer f.mu.Unlock() var out []string for id, d := range f.devices { if d.token != "" && !d.revoked { out = append(out, id) } } return out } // Devices are the ids of every device the fake knows. func (f *Fake) Devices() []string { f.mu.Lock() defer f.mu.Unlock() var out []string for id := range f.devices { out = append(out, id) } return out } func nativeAnswer(w http.ResponseWriter, status int, state string) { writeJSON(w, status, map[string]string{"state": state}) } // serveNative answers the two native routes, and reports whether r was // one of them. func (f *Fake) serveNative(w http.ResponseWriter, r *http.Request) bool { switch { case r.Method == http.MethodPost && r.URL.Path == "/native/oficina-id": f.nativeExchange(w, r) case r.Method == http.MethodPost && r.URL.Path == "/api/v1/auth/devices/native": f.nativeDevice(w, r) default: return false } return true } func (f *Fake) nativeExchange(w http.ResponseWriter, r *http.Request) { u, _ := url.Parse(f.URL) media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if r.Host != u.Host || r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 || len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Authorization")) != 0 || err != nil || media != "application/json" { nativeAnswer(w, 400, "invalid") return } var in struct { Assertion string `json:"assertion"` Verifier string `json:"verifier"` } if strict(r, &in) != nil || in.Assertion == "" || in.Verifier == "" { nativeAnswer(w, 400, "invalid") return } f.nmu.Lock() hold, entered := f.nativeHold, f.nativeEntered f.nativeHold, f.nativeEntered = nil, nil f.nmu.Unlock() if hold != nil { close(entered) select { case <-hold: case <-f.closing: return } } f.nmu.Lock() defer f.nmu.Unlock() if status := f.failNative; status != 0 { f.failNative = 0 state, ok := map[int]string{400: "invalid", 401: "failed", 403: "unknown"}[status] if !ok { state = "unavailable" } nativeAnswer(w, status, state) return } g := f.assertions[in.Assertion] if g == nil || g.used || g.verifier != in.Verifier { nativeAnswer(w, 401, "failed") return } address, linked := f.links[g.subject] if !linked { nativeAnswer(w, 403, "unknown") return } g.used = true value := rand.Text() + rand.Text() now := time.Now().UTC().Truncate(time.Second) f.sessions[value] = &nativeSession{subject: g.subject, address: address, at: now} writeJSON(w, 200, map[string]any{"name": SessionCookie, "value": value, "expires_at": now.Add(nativeLifetime).Unix()}) } func (f *Fake) nativeDevice(w http.ResponseWriter, r *http.Request) { // A browser-style request: the session cookie, and Equipo's own // Origin, which its CSRF check wants on a cookie mutation. if r.Header.Get("Origin") != f.URL || len(r.Header.Values("Authorization")) != 0 || len(r.Header.Values("Idempotency-Key")) > 1 { writeError(w, r, 403, "forbidden") return } c, err := r.Cookie(SessionCookie) if err != nil || len(r.Cookies()) != 1 { writeError(w, r, 401, "unauthenticated") return } var in struct { PublicKey string `json:"public_key"` Label string `json:"label"` } if strict(r, &in) != nil { writeError(w, r, 422, "invalid_input") return } raw, err := base64.RawURLEncoding.Strict().DecodeString(in.PublicKey) if err != nil || len(raw) != ed25519.PublicKeySize || in.Label == "" || len(in.Label) > 128 || !utf8.ValidString(in.Label) || strings.ContainsAny(in.Label, "\x00\r\n") { writeError(w, r, 422, "invalid_input") return } f.nmu.Lock() s := f.sessions[c.Value] live := s != nil && !s.ended && time.Now().Before(s.at.Add(nativeLifetime)) var at time.Time if live { at = s.at } f.nmu.Unlock() if !live { writeError(w, r, 401, "unauthenticated") return } d := &device{id: rand.Text(), publicKey: in.PublicKey, label: in.Label, approved: true, revision: 1, token: personAudience + "." + rand.Text(), expires: at.Add(nativeLifetime), session: c.Value} f.mu.Lock() f.devices[d.id] = d f.mu.Unlock() w.Header().Set("ETag", `"1"`) writeJSON(w, 200, map[string]any{"id": d.id, "token": d.token, "audience": personAudience, "instance_id": f.Instance, "expires_at": d.expires}) }