| 1 | package oficinaid |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/subtle" |
| 6 | "database/sql" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "mime" |
| 10 | "net/http" |
| 11 | "net/url" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/home/connect/linkstore" |
| 15 | "amadan.net/oficina/home/handoff" |
| 16 | "amadan.net/rastrillo/rastrillo/assertion" |
| 17 | "amadan.net/rastrillo/rastrillo/sessions" |
| 18 | json "github.com/go-json-experiment/json" |
| 19 | ) |
| 20 | |
| 21 | const NativeMethod = "home-assertion-native" |
| 22 | const NativeLifetime = 7 * 24 * time.Hour |
| 23 | const NativePath = "/native/oficina-id" |
| 24 | |
| 25 | func IsHomeDerived(method string) bool { return method == Method || method == NativeMethod } |
| 26 | |
| 27 | type NativeRequest struct { |
| 28 | Assertion string `json:"assertion"` |
| 29 | Verifier string `json:"verifier"` |
| 30 | Choice string `json:"choice,omitempty"` |
| 31 | } |
| 32 | type NativeState struct { |
| 33 | State string `json:"state"` |
| 34 | } |
| 35 | type NativeSession struct { |
| 36 | Name string `json:"name"` |
| 37 | Value string `json:"value"` |
| 38 | ExpiresAt int64 `json:"expires_at"` |
| 39 | } |
| 40 | |
| 41 | func nativeAnswer(w http.ResponseWriter, status int, state string) { |
| 42 | w.Header().Set("Content-Type", "application/json") |
| 43 | w.WriteHeader(status) |
| 44 | _, _ = io.WriteString(w, `{"state":"`+state+`"}`) |
| 45 | } |
| 46 | func nativeFailure(w http.ResponseWriter, err error) { |
| 47 | if errors.Is(err, linkstore.ErrRefused) || errors.Is(err, ErrUnlinked) { |
| 48 | nativeAnswer(w, 403, "unknown") |
| 49 | } else { |
| 50 | nativeAnswer(w, 503, "unavailable") |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // NativeExchange accepts only existing explicit links. Equipo has no trusted |
| 55 | // Home roster mapping for an unlinked subject, so choice never allocates. |
| 56 | func (h *HTTP) NativeExchange(w http.ResponseWriter, r *http.Request) { |
| 57 | w.Header().Set("Cache-Control", "no-store") |
| 58 | origin, _ := url.Parse(h.Store.Origin) |
| 59 | media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 60 | if r.Host != origin.Host || r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 || err != nil || media != "application/json" { |
| 61 | nativeAnswer(w, 400, "invalid") |
| 62 | return |
| 63 | } |
| 64 | body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 12*1024)) |
| 65 | var in NativeRequest |
| 66 | if err != nil || json.Unmarshal(body, &in, json.RejectUnknownMembers(true)) != nil || in.Assertion == "" || len(in.Assertion) > 8192 || (in.Choice != "" && in.Choice != "new") { |
| 67 | nativeAnswer(w, 400, "invalid") |
| 68 | return |
| 69 | } |
| 70 | challenge, ok := handoff.NativeChallenge(in.Verifier) |
| 71 | if !ok { |
| 72 | nativeAnswer(w, 400, "invalid") |
| 73 | return |
| 74 | } |
| 75 | now := time.Now().UTC().Truncate(time.Second) |
| 76 | claims, err := h.Store.Exchange.Verify(in.Assertion, now) |
| 77 | nonce, _ := handoff.NativeNonce(challenge) |
| 78 | if err != nil || subtle.ConstantTimeCompare([]byte(nonce), []byte(claims.Nonce)) != 1 { |
| 79 | nativeAnswer(w, 401, "failed") |
| 80 | return |
| 81 | } |
| 82 | // Resolve before reserving: unknown subjects never spend replay capacity. |
| 83 | if _, _, err = h.Store.Links.Resolve(r.Context(), claims.Issuer, claims.Subject); err != nil { |
| 84 | nativeFailure(w, err) |
| 85 | return |
| 86 | } |
| 87 | // Reserve owns and commits its short transaction before mintNative is called. |
| 88 | if _, err = h.Store.Exchange.Reserve(r.Context(), in.Assertion, now); err != nil { |
| 89 | if errors.Is(err, handoff.ErrRefused) { |
| 90 | nativeAnswer(w, 401, "failed") |
| 91 | } else { |
| 92 | nativeAnswer(w, 503, "unavailable") |
| 93 | } |
| 94 | return |
| 95 | } |
| 96 | token, err := h.Store.mintNative(r.Context(), claims, now) |
| 97 | if err != nil { |
| 98 | nativeFailure(w, err) |
| 99 | return |
| 100 | } |
| 101 | out, _ := json.Marshal(NativeSession{Name: h.Auth.SessionCookie(), Value: token, ExpiresAt: now.Add(NativeLifetime).Unix()}) |
| 102 | w.Header().Set("Content-Type", "application/json") |
| 103 | _, _ = w.Write(out) |
| 104 | } |
| 105 | |
| 106 | // mintNative is invoked with no writer held. Its own transaction rechecks the |
| 107 | // explicit link and roster and writes the session and audit through that handle. |
| 108 | // It calls no external hooks or framework session writer while holding it. |
| 109 | func (s *Store) mintNative(ctx context.Context, c assertion.Claims, now time.Time) (string, error) { |
| 110 | tx, err := s.begin(ctx, now) |
| 111 | if err != nil { |
| 112 | return "", err |
| 113 | } |
| 114 | defer tx.Rollback() |
| 115 | id, address, err := s.Links.ResolveOn(ctx, tx, c.Issuer, c.Subject) |
| 116 | if err != nil { |
| 117 | return "", err |
| 118 | } |
| 119 | var epoch int64 |
| 120 | if err = tx.QueryRowContext(ctx, "SELECT session_epoch FROM members WHERE address=? AND active=1", address).Scan(&epoch); err != nil { |
| 121 | if errors.Is(err, sql.ErrNoRows) { |
| 122 | return "", ErrUnlinked |
| 123 | } |
| 124 | return "", err |
| 125 | } |
| 126 | if now.Unix() < epoch { |
| 127 | return "", ErrUnlinked |
| 128 | } |
| 129 | token, hash, err := sessions.NewToken() |
| 130 | if err != nil { |
| 131 | return "", err |
| 132 | } |
| 133 | _, err = tx.ExecContext(ctx, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, c.Subject, NativeMethod, time.Unix(c.AuthTime, 0).UTC().Format(time.RFC3339), now.Format(time.RFC3339), now.Add(NativeLifetime).Format(time.RFC3339)) |
| 134 | if err != nil { |
| 135 | return "", err |
| 136 | } |
| 137 | if err = s.audit(ctx, tx, id, "oficina_id.signin", now); err != nil { |
| 138 | return "", err |
| 139 | } |
| 140 | if err = tx.Commit(); err != nil { |
| 141 | return "", err |
| 142 | } |
| 143 | return token, nil |
| 144 | } |
| 145 | |