oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package operator
2
3import (
4 "bytes"
5 "context"
6 "database/sql"
7 "errors"
8 "net/url"
9 "regexp"
10
11 "amadan.net/oficina/home/internal/home/directorydata"
12)
13
14type VerificationInput struct {
15 InputBase
16 Consumer string `json:"consumer"`
17 TeamSQID string `json:"team_sqid"`
18 App string `json:"app"`
19 Audience string `json:"audience"`
20 Generation string `json:"generation"`
21 RecordSequence int64 `json:"record_sequence"`
22 RecordDigest string `json:"record_digest"`
23 Epoch int64 `json:"expected_epoch"`
24 Owner string `json:"owner_ref"`
25 Issued int64 `json:"issued_at"`
26 Expires int64 `json:"expires_at"`
27}
28type ActivationEvidence struct {
29 Version int `json:"version"`
30 Policy string `json:"policy"`
31 Attempt string `json:"attempt_id"`
32 Consumer string `json:"consumer"`
33 TeamSQID string `json:"team_sqid"`
34 App string `json:"app"`
35 Audience string `json:"audience"`
36 Generation string `json:"generation"`
37 RecordSequence int64 `json:"record_sequence"`
38 RecordDigest string `json:"record_digest"`
39 Epoch int64 `json:"epoch"`
40 Owner string `json:"owner_ref"`
41 AppVersion string `json:"app_version"`
42 ArtifactDigest string `json:"artifact_digest"`
43 EnvironmentBinding string `json:"environment_binding"`
44 ManifestDigest string `json:"credential_manifest_digest"`
45 AliasHost string `json:"alias_host"`
46 Started int64 `json:"started_at"`
47 Completed int64 `json:"completed_at"`
48}
49type ActivationInput struct {
50 InputBase
51 Evidence ActivationEvidence `json:"evidence"`
52}
53
54type pendingBinding struct {
55 teamID, epoch int64
56 label string
57 sequence int64
58 generation string
59 digest []byte
60}
61
62func (d *Directory) pending(ctx context.Context, c *sql.Conn, consumer, team, app, audience, gen string, sequence int64, recordDigest, owner string, epoch int64) (pendingBinding, error) {
63 fail := func() (pendingBinding, error) { return pendingBinding{}, ErrRefused }
64 expected, ok := canonical(recordDigest, 32)
65 if !atom(consumer, 64) || !d.apps[app] || !Origin(audience) || !CanonicalToken(gen) || sequence <= 0 || !ok || !PersonRef(owner) || epoch <= 0 {
66 return fail()
67 }
68 var b pendingBinding
69 var storedTeam, storedApp, storedOrigin, state string
70 var enabled int
71 err := c.QueryRowContext(ctx, `SELECT t.id,t.sqid,t.label,t.roster_epoch,i.app,i.origin,i.state,c.enabled
72 FROM roster_consumers c JOIN team_instances i ON i.consumer_id=c.consumer_id AND i.team_id=c.team_id AND i.app=c.app AND i.origin=c.origin
73 JOIN teams t ON t.id=c.team_id WHERE c.consumer_id=?`, consumer).Scan(&b.teamID, &storedTeam, &b.label, &b.epoch, &storedApp, &storedOrigin, &state, &enabled)
74 if err != nil {
75 if errors.Is(err, sql.ErrNoRows) {
76 return fail()
77 }
78 return pendingBinding{}, ErrUnavailable
79 }
80 if enabled != 1 || state != "pending" || storedTeam != team || storedApp != app || storedOrigin != audience || b.epoch != epoch {
81 return fail()
82 }
83 if err = generation(ctx, c, gen); err != nil {
84 return pendingBinding{}, err
85 }
86 var receiptSequence int64
87 var receiptGeneration, receiptConsumer, kind string
88 var receiptDigest []byte
89 err = c.QueryRowContext(ctx, `SELECT p.sequence,p.generation,p.record_digest,r.sequence,r.generation,r.record_digest,r.consumer_id,r.operation
90 FROM directory_operator_consumer_records p JOIN roster_operator_receipts r ON r.operation_id=p.operation_id WHERE p.consumer_id=?`, consumer).Scan(&b.sequence, &b.generation, &b.digest, &receiptSequence, &receiptGeneration, &receiptDigest, &receiptConsumer, &kind)
91 if err != nil {
92 return pendingBinding{}, ErrUnavailable
93 }
94 if b.sequence != sequence || b.generation != gen || !bytes.Equal(b.digest, expected) || receiptSequence != b.sequence || receiptGeneration != b.generation || !bytes.Equal(receiptDigest, b.digest) || receiptConsumer != consumer || kind != "provision" {
95 return fail()
96 }
97 var found int
98 if err = c.QueryRowContext(ctx, "SELECT 1 FROM memberships WHERE team_id=? AND person_ref=? AND role='owner'", b.teamID, owner).Scan(&found); err != nil {
99 if errors.Is(err, sql.ErrNoRows) {
100 return fail()
101 }
102 return pendingBinding{}, ErrUnavailable
103 }
104 var currentTokens int
105 if err = c.QueryRowContext(ctx, "SELECT count(*) FROM roster_tokens WHERE consumer_id=? AND slot='current' AND expires_at IS NULL AND issued_at<=?", consumer, d.engine.now().Unix()).Scan(&currentTokens); err != nil {
106 return pendingBinding{}, ErrUnavailable
107 }
108 if currentTokens != 1 {
109 return fail()
110 }
111 if !d.policy.ValidateRoute(directoryRoute(b, team, app, audience, consumer)) {
112 return fail()
113 }
114 return b, nil
115}
116func (d *Directory) verifyConsumer(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
117 return d.verifyConsumerForWindow(ctx, c, r, "")
118}
119
120func (d *Directory) verifyConsumerForWindow(ctx context.Context, c *sql.Conn, r Request, existingTeam string) ([]byte, error) {
121 var in VerificationInput
122 if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial {
123 return nil, ErrRefused
124 }
125 now := d.engine.now().Unix()
126 if in.Issued <= 0 || in.Issued > now || in.Expires <= now || in.Expires <= in.Issued || in.Expires-in.Issued > 600 {
127 return nil, ErrRefused
128 }
129 binding, e := d.pending(ctx, c, in.Consumer, in.TeamSQID, in.App, in.Audience, in.Generation, in.RecordSequence, in.RecordDigest, in.Owner, in.Epoch)
130 if e != nil {
131 return nil, e
132 }
133 if !routeScope(existingTeam, binding.label, in.TeamSQID, in.App, in.Consumer, in.Audience) {
134 return nil, ErrRefused
135 }
136 var old, oldConsumer string
137 var issued, expires int64
138 e = c.QueryRowContext(ctx, "SELECT a.operation_id,a.consumer_id,a.issued_at,a.expires_at FROM verification_active v JOIN verification_attempts a ON a.operation_id=v.operation_id WHERE v.consumer_id=?", in.Consumer).Scan(&old, &oldConsumer, &issued, &expires)
139 if e == nil {
140 if oldConsumer != in.Consumer || issued <= 0 || issued > now || expires <= issued || expires-issued > 600 || expires > now {
141 return nil, ErrRefused
142 }
143 if _, e = c.ExecContext(ctx, "DELETE FROM verification_active WHERE consumer_id=? AND operation_id=?", in.Consumer, old); e != nil {
144 return nil, e
145 }
146 if _, e = c.ExecContext(ctx, "INSERT INTO verification_outcomes(attempt_id,operator_operation_id,kind,completed_at) VALUES(?,?,'expired',?)", old, r.authorization.OperationID, now); e != nil {
147 return nil, e
148 }
149 } else if !errors.Is(e, sql.ErrNoRows) {
150 return nil, ErrUnavailable
151 }
152 hash, ok := canonical(r.Head(), 32)
153 if !ok {
154 return nil, ErrUnavailable
155 }
156 _, e = c.ExecContext(ctx, "INSERT INTO verification_attempts VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", r.authorization.OperationID, in.Consumer, binding.teamID, in.App, in.Audience, in.Generation, in.RecordSequence, binding.digest, in.Epoch, in.Owner, in.Issued, in.Expires, hash)
157 if e != nil {
158 return nil, e
159 }
160 if _, e = c.ExecContext(ctx, "INSERT INTO verification_active VALUES(?,?)", in.Consumer, r.authorization.OperationID); e != nil {
161 return nil, e
162 }
163 if _, e = c.ExecContext(ctx, "INSERT INTO verification_outcomes(attempt_id,operator_operation_id,kind,completed_at) VALUES(?,?,'opened',?)", r.authorization.OperationID, r.authorization.OperationID, now); e != nil {
164 return nil, e
165 }
166 result := resultFor(r)
167 result.Attempt = r.authorization.OperationID
168 result.Expires = in.Expires
169 return encode(result)
170}
171
172// observedVersion is the shape app_version must have: the opaque token Alta
173// read from the app's /api/version, which every app stamps with `git describe
174// --tags --always` (v0.1.0-63-gd867db1, or a bare commit). It is what Alta
175// observed, not a platform attestation (team-provisioning-amendment.md §2
176// item 6), so Home bounds it to printable ASCII and checks nothing more.
177var observedVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`)
178
179func version(s string) bool { return observedVersion.MatchString(s) }
180func (d *Directory) activate(ctx context.Context, c *sql.Conn, r Request) ([]byte, error) {
181 return d.activateForWindow(ctx, c, r, "")
182}
183
184func (d *Directory) activateForWindow(ctx context.Context, c *sql.Conn, r Request, existingTeam string) ([]byte, error) {
185 var in ActivationInput
186 if DecodeInput(r, &in) != nil || !in.matches(r) || r.authorization.Initial {
187 return nil, ErrRefused
188 }
189 p := in.Evidence
190 policy := "oficina/team-activation/v1"
191 if existingTeam != "" {
192 policy = existingActivationPolicy
193 }
194 now := d.engine.now().Unix()
195 u, e := url.Parse(p.Audience)
196 if e != nil || p.Version != 1 || p.Policy != policy || !CanonicalToken(p.Attempt) || !version(p.AppVersion) || !CanonicalToken(p.ArtifactDigest) || !CanonicalToken(p.EnvironmentBinding) || !CanonicalToken(p.ManifestDigest) || p.AliasHost != u.Host || p.Started <= 0 || p.Completed < p.Started || p.Completed > now || now-p.Completed >= 300 {
197 return nil, ErrRefused
198 }
199 binding, e := d.pending(ctx, c, p.Consumer, p.TeamSQID, p.App, p.Audience, p.Generation, p.RecordSequence, p.RecordDigest, p.Owner, p.Epoch)
200 if e != nil {
201 return nil, e
202 }
203 if !routeScope(existingTeam, binding.label, p.TeamSQID, p.App, p.Consumer, p.Audience) {
204 return nil, ErrRefused
205 }
206 var consumer, app, origin, gen, owner string
207 var teamID, sequence, epoch, issued, expires int64
208 var recordDigest []byte
209 e = c.QueryRowContext(ctx, `SELECT a.consumer_id,a.team_id,a.app,a.origin,a.generation,a.record_sequence,a.record_digest,a.expected_epoch,a.owner_ref,a.issued_at,a.expires_at
210 FROM verification_active v JOIN verification_attempts a ON a.operation_id=v.operation_id WHERE v.consumer_id=? AND a.operation_id=?`, p.Consumer, p.Attempt).Scan(&consumer, &teamID, &app, &origin, &gen, &sequence, &recordDigest, &epoch, &owner, &issued, &expires)
211 if e != nil {
212 if errors.Is(e, sql.ErrNoRows) {
213 return nil, ErrRefused
214 }
215 return nil, ErrUnavailable
216 }
217 if consumer != p.Consumer || teamID != binding.teamID || app != p.App || origin != p.Audience || gen != p.Generation || sequence != p.RecordSequence || !bytes.Equal(recordDigest, binding.digest) || epoch != p.Epoch || owner != p.Owner || issued <= 0 || issued > now || expires <= now || expires <= issued || expires-issued > 600 || p.Started < issued || p.Completed >= expires {
218 return nil, ErrRefused
219 }
220 if _, e = c.ExecContext(ctx, "UPDATE team_instances SET state='live' WHERE consumer_id=? AND state='pending'", p.Consumer); e != nil {
221 return nil, e
222 }
223 if _, e = c.ExecContext(ctx, "DELETE FROM verification_active WHERE consumer_id=? AND operation_id=?", p.Consumer, p.Attempt); e != nil {
224 return nil, e
225 }
226 if _, e = c.ExecContext(ctx, "INSERT INTO verification_outcomes(attempt_id,operator_operation_id,kind,completed_at) VALUES(?,?,'activated',?)", p.Attempt, r.authorization.OperationID, now); e != nil {
227 return nil, e
228 }
229 result := resultFor(r)
230 result.Attempt = p.Attempt
231 result.Generation = p.Generation
232 result.TeamID = binding.teamID
233 result.TeamSQID = p.TeamSQID
234 result.Epoch = p.Epoch
235 return encode(result)
236}
237
238func directoryRoute(b pendingBinding, team, app, audience, consumer string) directorydata.Route {
239 return directorydata.Route{TeamID: b.teamID, TeamSQID: team, Label: b.label, App: app, Origin: audience, ConsumerID: consumer}
240}
241