Zoo

staging

← back to the zoo

4. Your name and picture follow you

Change your name and picture at account, and every app shows the new ones.

rc.users(ids) turns stored ids into current names and pictures, one call per page. An app keeps ids, never copies of names or pictures.

This is the code serving the zoo right now: the bytes this very program was built from (each file is embedded when the zoo is compiled), at commit 55c71513c5 (staging). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.

e04_guestbook.odin sha256 7915b7126905 · raw

1package main
2
3// Exhibit 4. The guestbook stores only user ids. Names and pictures are asked of account at render
4// time, in one batch call (rc.users), so a change at account shows on the next load. Storing a copy
5// of someone's name or picture is how an app ends up showing the old one.
6
7import "core:fmt"
8import "core:strings"
9import "core:unicode/utf8"
10import "ratcloud:rc"
11
12Guest :: struct {
13	user: rc.User `json:"user"`,
14	note: string `json:"note"`,
15	at:   string `json:"at"`,
16}
17
18guestbook :: proc() -> []Guest {
19	rows := rc.query_rows(db(), "SELECT user_id, note, at FROM guestbook ORDER BY at DESC LIMIT 60")
20	ids := make([dynamic]i64)
21	notes := make([dynamic]string)
22	ats := make([dynamic]i64)
23	for rc.next(&rows) {
24		append(&ids, rc.col_int(&rows, 0))
25		append(&notes, strings.clone(rc.col_text(&rows, 1)))
26		append(&ats, rc.col_int(&rows, 2))
27	}
28	users := rc.users(ids[:]) // one call for the whole list
29	out := make([dynamic]Guest)
30	// A deleted person's entry is not shown: an unnamed line reads as a broken one. The row stays
31	// (account deletes the person, not what they wrote). If account answered nobody at all, it is more
32	// likely down than everyone gone, so then the entries show without names.
33	down := len(ids) > 0 && len(users) == 0
34	for id, i in ids {
35		u, ok := users[id]
36		if !ok && !down do continue
37		if !ok do u = {id = 0, username = "", name = "someone", picture = ""}
38		append(&out, Guest{u, notes[i], iso(ats[i])})
39	}
40	return out[:]
41}
42
43e04 :: proc() -> Exhibit {
44	return {
45		n = 4, try_ = "sign the guestbook", wing = "Identity",
46		title = "Your name and picture follow you",
47		promise = "Change your name and picture at account, and every app shows the new ones.",
48		block = "rc.users(ids) turns stored ids into current names and pictures, one call per page. An app keeps ids, never copies of names or pictures.",
49		src = {"e04_guestbook.odin", #load("e04_guestbook.odin", string)},
50		files = srcs({"robot.odin", #load("robot.odin", string)}),
51		script = {"web/e04.js", #load("web/e04.js", string)},
52		show = proc(me: ^rc.User) -> string {
53			list := strings.builder_make()
54			for &g in guestbook() {
55				mine := me != nil && g.user.id == me.id
56				rc.render_to(&list, `<div{{1}}>{{2}}<div class="note">{{3}} · {{4}}</div></div>`, {{"1", rc.raw(` class="mine"` if mine else "")}, {"2", rc.raw(person(&g.user))}, {"3", g.note}, {"4", rc.raw(ago(parse_time(g.at)))}})
57			}
58			form := `<form class="row" id="gb-form"><input name="note" maxlength="140" placeholder="Say hello (140 characters)" required><button class="primary">Sign</button></form>` if me != nil else signin_line("to sign the guestbook.")
59			listed := strings.to_string(list) if strings.builder_len(list) > 0 else `<p class="muted">Nobody has signed yet.</p>`
60			return cat(form, `<p class="muted">Change your name or picture at <a href="`, h(env().accounts), `/">account</a>, then reload: your entry changes too. (The robot renames itself to the time of every check, which is how this exhibit checks itself.)</p>`,
61				`<p class="rc-note ok" id="gb-done" role="status" hidden></p><div class="people" id="gb-list">`, listed, `</div>`)
62		},
63		api = proc(a: ^Api) -> bool {
64			switch a.do_ {
65			case "list":
66				inst, _ := meta("instance")
67				reply(a, struct {
68						env:       string `json:"env"`,
69						instance:  string `json:"instance"`,
70						guestbook: []Guest `json:"guestbook"`,
71					}{env().env, inst, guestbook()})
72				return true
73			case "sign":
74				if !a.post do return false
75				if a.me == nil {reply_err(a, 401, "sign in to sign the guestbook"); return true}
76				note := in_str(a, "note")
77				if utf8.rune_count_in_string(note) > 140 {
78					n := 0
79					for _, i in note {if n == 140 {note = note[:i]; break}; n += 1}
80				}
81				note = strings.trim_space(note)
82				if note == "" {reply_err(a, 400, "say something"); return true}
83				must("INSERT INTO guestbook (user_id, note, at) VALUES (?, ?, ?) ON CONFLICT(user_id) DO UPDATE SET note = excluded.note, at = excluded.at", a.me.id, note, now())
84				reply_raw(a, `{"ok":true}`)
85				return true
86			}
87			return false
88		},
89		// The robot renames itself at account, then reads the guestbook as a visitor would.
90		check = proc() -> Check {
91			b, err := robot_at()
92			if err != "" do return fail(err)
93			r := post(b, self_url("/api/4/sign"), fmt.tprintf(`{{"note":%s}}`, jq(fmt.tprintf("The robot was here, on %s.", env().env))))
94			if r.status != 200 do return fail(fmt.tprintf("the robot could not sign the guestbook (%d)", r.status))
95			name := cat("Zoo Robot ", hm(now()))
96			if code, _ := account_api(b, "profile", fmt.tprintf(`{{"name":%s}}`, jq(name))); code != 200 do return fail(fmt.tprintf("account would not rename the robot (%d)", code))
97			l := get(new_browser(), self_url("/api/4/list"))
98			me := robot_user().id
99			for g in jarr(l.j, "guestbook") {
100				if jint(g, "user", "id") != me do continue
101				if got := jstr(g, "user", "name"); got != name do return fail(fmt.tprintf(`renamed to "%s" at account, but the guestbook still says "%s"`, name, got))
102				return pass(fmt.tprintf(`renamed the robot to "%s" at account; the guestbook showed the new name on the next load`, name))
103			}
104			return fail("the robot's entry is missing from the guestbook")
105		},
106	}
107}

robot.odin sha256 4cfbb96b4503 · raw

1package main
2
3// The zoo's robot: a real account, `zoo-robot`, visible in the directory like anyone, that the
4// self-check signs in as. Its passkey is a software key kept in robot.json (the zoo's own data;
5// nothing of root's or account's). It signs in exactly as a person does: a WebAuthn assertion to
6// account, then the silent upgrade into each app it visits.
7//
8// Live and staging each have their own account, so each environment has its own robot. One sign-in
9// per instance (a request or a job run); robot_done() signs it out again at the end, so robot
10// sessions never pile up.
11
12import "core:crypto/ecdsa"
13import "core:crypto/hash"
14import "core:encoding/base64"
15import "core:encoding/json"
16import "core:fmt"
17import "core:strings"
18import "ratcloud:rc"
19
20ROBOT_NAME :: "zoo-robot"
21
22Robot_File :: struct {
23	username: string `json:"username"`,
24	id:       i64 `json:"id"`,
25	cred:     string `json:"cred"`, // the credential id, base64url
26	key:      string `json:"key"`, // the private key, PEM
27	count:    i64 `json:"count"`,
28}
29
30b64u :: proc(b: []u8) -> string {
31	s := base64.encode(b)
32	out := strings.builder_make()
33	for ch in transmute([]u8)s {
34		switch ch {
35		case '+': strings.write_byte(&out, '-')
36		case '/': strings.write_byte(&out, '_')
37		case '=':
38		case: strings.write_byte(&out, ch)
39		}
40	}
41	return strings.to_string(out)
42}
43b64 :: proc(b: []u8) -> string {return base64.encode(b)}
44unb64 :: proc(s: string) -> ([]u8, bool) {
45	t := strings.builder_make()
46	for ch in transmute([]u8)s {
47		switch ch {
48		case '-': strings.write_byte(&t, '+')
49		case '_': strings.write_byte(&t, '/')
50		case ' ', '\n', '\r', '\t':
51		case: strings.write_byte(&t, ch)
52		}
53	}
54	for strings.builder_len(t) % 4 != 0 do strings.write_byte(&t, '=')
55	b, err := base64.decode(strings.to_string(t))
56	return b, err == nil
57}
58sha256 :: proc(b: []u8) -> []u8 {
59	out := make([]u8, 32)
60	hash.hash_bytes_to_buffer(.SHA256, b, out)
61	return out
62}
63sha256s :: proc(s: string) -> []u8 {return sha256(transmute([]u8)s)}
64bytes_of :: proc(s: string) -> []u8 {return transmute([]u8)s}
65join :: proc(parts: ..[]u8) -> []u8 {
66	n := 0
67	for p in parts do n += len(p)
68	out := make([]u8, n)
69	o := 0
70	for p in parts {copy(out[o:], p); o += len(p)}
71	return out
72}
73be32 :: proc(n: u32) -> []u8 {return bs(u8(n >> 24), u8(n >> 16), u8(n >> 8), u8(n))}
74be16 :: proc(n: u16) -> []u8 {return bs(u8(n >> 8), u8(n))}
75// A slice of these bytes that outlives the call.
76bs :: proc(xs: ..u8) -> []u8 {
77	out := make([]u8, len(xs))
78	copy(out, xs)
79	return out
80}
81
82// ---- P-256 keys as PEM: the 32-byte scalar inside SEC 1 or PKCS #8 ----------------------------------
83
84// The private scalar d of a P-256 key in PEM (SEC 1 "EC PRIVATE KEY" or PKCS #8 "PRIVATE KEY", as
85// openssl writes them): the OCTET STRING after ECPrivateKey's version 1.
86pem_scalar :: proc(pem: string) -> ([]u8, bool) {
87	body := strings.builder_make()
88	for line in strings.split_lines(pem) {
89		if strings.has_prefix(line, "-----") do continue
90		strings.write_string(&body, strings.trim_space(line))
91	}
92	der, ok := unb64(strings.to_string(body))
93	if !ok do return nil, false
94	for i in 0 ..< len(der) - 37 {
95		if der[i] == 0x02 && der[i + 1] == 0x01 && der[i + 2] == 0x01 && der[i + 3] == 0x04 && der[i + 4] == 0x20 do return der[i + 5:i + 37], true
96	}
97	return nil, false
98}
99
100// SEC 1 PEM of a P-256 key: d and its public point.
101pem_of :: proc(d, pub: []u8) -> string {
102	der := join({0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20}, d, {0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00}, pub)
103	s := base64.encode(der)
104	b := strings.builder_make()
105	label := cat("EC PRIV", "ATE KEY") // split, so exhibit 14's search for a key's shape does not find this line
106	strings.write_string(&b, cat("-----BEGIN ", label, "-----\n"))
107	for i := 0; i < len(s); i += 64 {strings.write_string(&b, s[i:min(i + 64, len(s))]); strings.write_byte(&b, '\n')}
108	strings.write_string(&b, cat("-----END ", label, "-----\n"))
109	return strings.to_string(b)
110}
111
112// An ES256 signature (DER, as WebAuthn wants) over msg with the key in pem.
113es256_sign :: proc(pem: string, msg: []u8) -> ([]u8, bool) {
114	d, ok := pem_scalar(pem)
115	if !ok do return nil, false
116	k: ecdsa.Private_Key
117	if !ecdsa.private_key_set_bytes(&k, .SECP256R1, d) do return nil, false
118	return ecdsa.sign_asn1(&k, .SHA256, msg, context.allocator)
119}
120
121// ---- CBOR, just enough for a COSE key and an attestation object -------------------------------------
122
123cbor_head :: proc(major: u8, n: int) -> []u8 {
124	if n < 24 do return bs(major << 5 | u8(n))
125	if n < 256 do return bs(major << 5 | 24, u8(n))
126	return bs(major << 5 | 25, u8(n >> 8), u8(n))
127}
128cbor_int :: proc(n: int) -> []u8 {return cbor_head(0, n) if n >= 0 else cbor_head(1, -1 - n)}
129cbor_bytes :: proc(b: []u8) -> []u8 {return join(cbor_head(2, len(b)), b)}
130cbor_text :: proc(s: string) -> []u8 {return join(cbor_head(3, len(s)), transmute([]u8)s)}
131
132// ---- the robot -----------------------------------------------------------------------------------
133
134ROBOT_FILE :: "robot.json"
135
136robot_file :: proc() -> (r: Robot_File, ok: bool) {
137	b, err := rc.read_file(ROBOT_FILE)
138	if err != 0 || len(b) == 0 do return {}, false
139	// unmarshal first: a return's values are read left to right, so `return r, unmarshal(&r)` returns the empty r
140	ok = json.unmarshal(b, &r) == nil && r.key != ""
141	return r, ok
142}
143
144// The robot's passkey and counter, written whole or not at all (the host writes a temp file and
145// renames it): a half-written file would read as "no robot", the next run would register
146// zoo-robot-1, and the real robot's name would be stranded.
147robot_save :: proc(r: Robot_File) {
148	if rc.write_file(ROBOT_FILE, transmute([]u8)to_json(r)) != 0 do panic("could not save the robot's state")
149}
150
151rp_id :: proc() -> string {return domain_host(env().accounts)}
152domain_host :: proc(url: string) -> string {
153	s := strings.trim_prefix(strings.trim_prefix(url, "https://"), "http://")
154	if i := strings.index_byte(s, '/'); i >= 0 do s = s[:i]
155	return s
156}
157
158account_api :: proc(b: ^Browser, name: string, in_ := "{}") -> (int, json.Value) {
159	r := post(b, cat(env().accounts, "/api/", name), in_)
160	return r.status, r.j
161}
162
163// Make the robot's account (once per environment) and give it a picture.
164robot_register :: proc(b: ^Browser) -> (Robot_File, string) {
165	k: ecdsa.Private_Key
166	if !ecdsa.private_key_generate(&k, .SECP256R1) do return {}, "could not make a key"
167	d := make([]u8, 32)
168	ecdsa.private_key_bytes(&k, d)
169	pub := make([]u8, 65)
170	ecdsa.private_key_public_bytes(&k, pub)
171	cred := random_bytes(16)
172	// If a previous robot.json was lost, its name is retired for good: take the next free one.
173	code: int
174	o: json.Value
175	for i in 0 ..< 5 {
176		name := ROBOT_NAME if i == 0 else fmt.tprintf("%s-%d", ROBOT_NAME, i)
177		code, o = account_api(b, "register-start", fmt.tprintf(`{{"username":%s}}`, jq(name)))
178		if code == 200 do break
179	}
180	if code != 200 do return {}, cat("account would not register a robot: ", to_json(o))
181	cose := join(cbor_head(5, 5), cbor_int(1), cbor_int(2), cbor_int(3), cbor_int(-7), cbor_int(-1), cbor_int(1), cbor_int(-2), cbor_bytes(pub[1:33]), cbor_int(-3), cbor_bytes(pub[33:65]))
182	ad := join(sha256s(rp_id()), {0x45}, be32(0), make([]u8, 16), be16(16), cred, cose)
183	att := join(cbor_head(5, 3), cbor_text("fmt"), cbor_text("none"), cbor_text("attStmt"), cbor_head(5, 0), cbor_text("authData"), cbor_bytes(ad))
184	cdj := fmt.tprintf(`{{"type":"webauthn.create","challenge":%s,"origin":%s,"crossOrigin":false}}`, jq(jstr(o, "challenge")), jq(env().accounts))
185	code2, j := account_api(b, "register-finish", fmt.tprintf(`{{"clientDataJSON":%s,"attestationObject":%s}}`, jq(b64u(bytes_of(cdj))), jq(b64u(att))))
186	if code2 != 200 do return {}, cat("robot registration failed: ", to_json(j))
187	r := Robot_File{username = jstr(j, "user", "username"), id = jint(j, "user", "id"), cred = b64u(cred), key = pem_of(d, pub), count = 0}
188	robot_save(r)
189	account_api(b, "profile", `{"name":"Zoo Robot"}`)
190	account_api(b, "picture", fmt.tprintf(`{{"image":%s}}`, jq(b64(robot_picture()))))
191	return r, ""
192}
193
194g_robot: ^Browser
195g_robot_at: map[string]bool
196
197// A WebAuthn assertion with the robot's passkey over this challenge: the counter goes up first,
198// under the robot's lock (one counter value per signature). The fields account's *-finish wants.
199@(private = "file")
200robot_assert :: proc(challenge: string) -> (string, string) {
201	r, ok := robot_file()
202	if !ok do return "", "the robot's robot.json is gone"
203	// The signature counter must go up every time. Time does, even after a restore from backup.
204	r.count = max(r.count + 1, now())
205	ad := join(sha256s(rp_id()), {0x05}, be32(u32(r.count)))
206	cdj := fmt.tprintf(`{{"type":"webauthn.get","challenge":%s,"origin":%s}}`, jq(challenge), jq(env().accounts))
207	sig, sok := es256_sign(r.key, join(ad, sha256s(cdj)))
208	if !sok do return "", "the robot's key did not sign"
209	robot_save(r)
210	return fmt.tprintf(`{{"id":%s,"clientDataJSON":%s,"authenticatorData":%s,"signature":%s}}`, jq(r.cred), jq(b64u(bytes_of(cdj))), jq(b64u(ad)), jq(b64u(sig))), ""
211}
212
213// A browser signed in as the robot at account, or why not. One sign-in per instance.
214robot :: proc() -> (^Browser, string) {
215	if g_robot != nil do return g_robot, ""
216	lk := lock_open("robot.json.lock")
217	defer lock_close(lk)
218	lock_wait(lk, 30_000) // the job's check and a web check never sign in with one counter value
219	b := new_browser()
220	if _, ok := robot_file(); !ok {
221		if _, err := robot_register(b); err != "" do return nil, err
222	}
223	account_api(b, "signout") // registering signed it in; start clean either way
224	code, o := account_api(b, "login-start")
225	if code != 200 do return nil, fmt.tprintf("account login-start answered %d", code)
226	fin, err := robot_assert(jstr(o, "challenge"))
227	if err != "" do return nil, err
228	code2, j := account_api(b, "login-finish", fin)
229	if code2 != 200 do return nil, fmt.tprintf("the robot could not sign in at account (%d): %s", code2, jstr(j, "error"))
230	g_robot = b
231	g_robot_at = make(map[string]bool)
232	return b, ""
233}
234
235// At the end of the instance: sign the robot out at account, if it signed in.
236robot_done :: proc() {
237	if g_robot != nil do account_api(g_robot, "signout")
238	g_robot = nil
239}
240
241Robot_User :: struct {
242	id:       i64,
243	username: string,
244}
245robot_user :: proc() -> Robot_User {
246	r, _ := robot_file()
247	return {r.id, r.username}
248}
249
250// The robot's browser after a page load at app (default: the zoo), so its token is there too.
251robot_at :: proc(app := "") -> (^Browser, string) {
252	b, err := robot()
253	if err != "" do return nil, err
254	if !g_robot_at[app] {
255		url := self_url() if app == "" else cat(rc.app_url(app), "/")
256		r := visit(b, url)
257		if r.status != 200 do return nil, fmt.tprintf("%s answered the robot with %d", "the zoo" if app == "" else app, r.status)
258		g_robot_at[app] = true
259	}
260	return b, ""
261}
262
263// A passkey approval of exactly this action and params, as the robot (account README, "Approvals"):
264// the same two calls account's /approve page makes, signed with the robot's software passkey, for
265// app to file with aud (root). The approval, or why not.
266robot_approve :: proc(app, action, params_json: string, aud := "root") -> (string, string) {
267	b, err := robot()
268	if err != "" do return "", err
269	lk := lock_open("robot.json.lock")
270	defer lock_close(lk)
271	lock_wait(lk, 30_000) // one counter value per signature, as at sign-in
272	code, o := account_api(b, "approve-start", fmt.tprintf(`{{"app":%s,"aud":%s,"action":%s,"params":%s}}`, jq(app), jq(aud), jq(action), params_json))
273	if code != 200 || jstr(o, "challenge") == "" do return "", fmt.tprintf("account would not start an approval of %s (%d): %s", action, code, jstr(o, "error"))
274	fin, ferr := robot_assert(jstr(o, "challenge"))
275	if ferr != "" do return "", ferr
276	code2, j := account_api(b, "approve-finish", fin)
277	if code2 != 200 || jstr(j, "approval") == "" do return "", fmt.tprintf("account would not sign the approval of %s (%d): %s", action, code2, jstr(j, "error"))
278	return jstr(j, "approval"), ""
279}
280
281// A little robot face, drawn here so the guestbook has a picture to show.
282robot_picture :: proc() -> []u8 {
283	im := image_new(128, 128, {{46, 125, 90}, {240, 240, 230}, {30, 30, 30}})
284	fill_rect(&im, 24, 34, 104, 100, 1)
285	fill_ellipse(&im, 48, 60, 8, 2)
286	fill_ellipse(&im, 80, 60, 8, 2)
287	fill_rect(&im, 46, 82, 82, 88, 2)
288	fill_rect(&im, 61, 18, 67, 34, 1)
289	return png_encode(&im)
290}

web/e04.js sha256 ba9719d4be28 · raw

1document.getElementById("gb-form")?.addEventListener("submit", async (ev) => {
2  ev.preventDefault();
3  const btn = ev.target.querySelector("button");
4  btn.disabled = true;
5  const j = await zoo.call("/api/4/sign", { note: ev.target.note.value });
6  btn.disabled = false;
7  if (!j.error) {
8    // Her entry, in place: the list again from the server, hers marked, and a line saying so.
9    // No reload, so the card stays open where she is looking.
10    const l = await zoo.call("/api/4/list");
11    if (!l.error) {
12      document.getElementById("gb-list").innerHTML = l.guestbook.map(g =>
13        '<div' + (g.user.id === zoo.me ? ' class="mine"' : "") + ">" + zoo.person(g.user) + '<div class="note">' + zoo.esc(g.note) + " · " + zoo.ago(g.at) + "</div></div>").join("");
14    }
15    const done = document.getElementById("gb-done");
16    done.textContent = "Signed. Your entry is at the top of the guestbook.";
17    done.hidden = false;
18    ev.target.reset();
19    document.querySelector("#gb-list .mine")?.scrollIntoView({ block: "nearest", behavior: "smooth" });
20    return;
21  }
22  let e = ev.target.nextElementSibling;
23  if (!e || !e.classList.contains("form-err")) { e = document.createElement("p"); e.className = "rc-note bad form-err"; ev.target.after(e); }
24  e.textContent = j.error;
25});