Zoo

← back to the zoo

18. Add a laptop by pasting its key

Pasting a machine's public key on apps lets that machine push; removing it stops it.

apps's Machines: paste a public key (~/.ssh/id_ed25519.pub) and a name, confirm it with your passkey, and that machine pushes as you; Remove stops it at once. Each machine shows its last push.

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 (live). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.

e18_add_a_laptop.odin sha256 82591917eef8 · raw

1package main
2
3// Exhibit 18. A creator's machines are their ssh public keys. Pasting one on apps (Machines, with a
4// passkey approval of exactly that key at account) lets that machine push as them; removing it stops
5// it at once. apps lists each one with its last push, and a creator's workbench key is on the same
6// list, first; the card shows the robot's.
7//
8// The check, on live, as the robot (a creator): make a fresh ed25519 key (rc.ssh keygen, in the zoo's
9// own workspace: its private half never enters this program), approve it with the robot's passkey and
10// add it on apps, find it on apps's machine list, clone the robot's sample zoo-broken and push its
11// branch e18-live with it (a branch that goes nowhere), find that push on the list, remove the key on
12// apps, and push again: refused. The robot's own key (the zoo's, for exhibits 8 and 30) is never
13// touched; a key a killed round left behind (labelled zoo-18) goes first.
14//
15// On staging, apps acts in a pretend world (account-staging's names are anyone's to register): the
16// robot is no creator there, so its key-add must be refused, and that is what the staging zoo checks.
17
18import "core:crypto/hash"
19import "core:encoding/json"
20import "core:fmt"
21import "core:strings"
22import "ratcloud:rc"
23
24E18_LABEL :: "zoo-18"
25E18_APP :: "zoo-broken"
26// Every 6 hours (an hour when red): a round rewrites the robot's keys on the box twice (root
27// reinstalls the creators' keys each time) and puts a push into zoo-broken's push log, which exhibit
28// 8's refusals share. A revoke that stopped working still shows the same day.
29E18_EVERY :: 6 * 3600
30E18_RETRY :: 3600
31E18_STALE :: E18_EVERY + 2 * 3600
32
33// A request through apps's door, then root's answer (rc-spool-apps answers within a second or two).
34e18_do :: proc(b: ^Browser, do_: string, fields_json: string) -> json.Value {
35	base := rc.app_url("apps")
36	r := post(b, cat(base, "/api/do"), fmt.tprintf(`{{"do":%s,%s}}`, jq(do_), fields_json))
37	if r.status != 200 || jstr(r.j, "id") == "" do return parse(fmt.tprintf(`{{"result":"unsent","message":%s}}`, jq(fmt.tprintf("apps answered %d: %s", r.status, clip(r.body, 200)))))
38	id := jstr(r.j, "id")
39	for _ in 0 ..< 120 {
40		rc.sleep(500)
41		q := get(b, fmt.tprintf("%s/api/req?id=%s", base, rc.percent_encode(id)))
42		if res := jstr(q.j, "result"); q.j != nil && res != "" && res != "waiting" do return q.j
43	}
44	return parse(`{"result":"waiting","message":"root did not answer within 60 s"}`)
45}
46
47// The robot's machines as apps lists them: [{fp, type, label, last_push, workbench, on, refs}].
48e18_machines :: proc(b: ^Browser) -> json.Array {
49	r := get(b, cat(rc.app_url("apps"), "/api/apps"))
50	if r.status != 200 do return nil
51	out := make(json.Array)
52	for k in jarr(r.j, "machines") do if _, ok := k.(json.Object); ok do append(&out, k)
53	return out
54}
55e18_find :: proc(ms: json.Array, fp: string) -> json.Value {
56	for k in ms do if jstr(k, "fp") == fp do return k
57	return nil
58}
59// Wait up to secs for apps's list to have (or not have, `gone`) the key, with a push if `pushed`.
60e18_wait :: proc(b: ^Browser, fp: string, gone := false, pushed := false, secs := 15) -> json.Array {
61	ms: json.Array
62	for i := 0; i < secs * 10 / 7 + 1; i += 1 {
63		ms = e18_machines(b)
64		k := e18_find(ms, fp)
65		if gone && k == nil do return ms
66		if !gone && k != nil && (!pushed || jhas(k, "last_push")) do return ms
67		rc.sleep(700)
68	}
69	return ms
70}
71
72// `ssh-keygen -l`'s fingerprint: SHA256 of the key's blob, unpadded base64.
73e18_fp :: proc(pub: string) -> string {
74	f := strings.fields(pub)
75	blob, _ := unb64(f[1] if len(f) > 1 else "")
76	sum: [32]u8
77	hash.hash_bytes_to_buffer(.SHA256, blob, sum[:])
78	return cat("SHA256:", strings.trim_right(b64(sum[:]), "="))
79}
80
81// One new commit on zoo-broken's e18-live, pushed with the key `key`: the push's exit code and answer.
82e18_push :: proc(key, what: string, cloned: ^bool) -> Ran_Tool {
83	if !cloned^ {
84		r := creator_git({op = "clone", repo = E18_APP, branch = "main", dir = "e18", key = key})
85		if r.code != 0 do return {r.code, cat("clone: ", r.out)}
86		cloned^ = true
87	}
88	creator_git({op = "commit", dir = "e18", allow_empty = true, message = cat("exhibit 18: ", what)})
89	r := creator_git({op = "push", dir = "e18", branch = "e18-live", force = true, key = key})
90	return {r.code, unremote(r.out)}
91}
92
93E18_Data :: struct {
94	at:         string `json:"at"`,
95	fp:         string `json:"fp,omitempty"`,
96	add:        json.Value `json:"add,omitempty"`,
97	push:       string `json:"push,omitempty"`,
98	last_push:  json.Value `json:"last_push,omitempty"`,
99	rm:         json.Value `json:"rm,omitempty"`,
100	push_after: string `json:"push_after,omitempty"`,
101	machines:   json.Value `json:"machines,omitempty"`,
102	leftover:   []json.Value `json:"leftover,omitempty"`,
103	seconds:    i64 `json:"seconds,omitempty"`,
104}
105
106e18_staging :: proc() -> Check {
107	b, err := robot_at("apps")
108	if err != "" do return fail(err)
109	k := rc.ssh({op = "keygen", name = "e18", comment = E18_LABEL})
110	if k.code != 0 do return fail(cat("ssh keygen failed: ", k.err, string(k.out)))
111	r := e18_do(b, "key-add", fmt.tprintf(`"key":%s,"label":%s,"approval":""`, jq(strings.trim_space(string(k.out))), jq(E18_LABEL)))
112	ms := e18_machines(b)
113	data := E18_Data{at = iso(now()), add = r, machines = ms}
114	if jstr(r, "result") != "refused" do return fail(fmt.tprintf("staging's apps %s a machine for the robot, who is no creator in its pretend world: %s", jstr(r, "result") or_else "?", jstr(r, "message")), data)
115	if len(ms) > 0 do return fail("staging's apps lists machines for the robot", data)
116	return pass(fmt.tprintf("staging's apps acts in a pretend world: the robot is no creator there, and its key was refused (%s); the live zoo adds and removes one", jstr(r, "message")), data)
117}
118
119e18_round :: proc() -> Check {
120	b, err := robot_at("apps")
121	if err != "" do return fail(err)
122	t0 := now()
123	data := E18_Data{at = iso(t0)}
124	failing :: proc(b: ^Browser, data: ^E18_Data, why: string) -> Check {
125		data.machines = e18_machines(b)
126		return fail(why, data^)
127	}
128	// A key an earlier round left behind goes first (labelled zoo-18; never the zoo's own keys).
129	left := make([dynamic]json.Value)
130	for k in e18_machines(b) do if jstr(k, "label") == E18_LABEL do append(&left, e18_do(b, "key-rm", fmt.tprintf(`"fp":%s`, jq(jstr(k, "fp")))))
131	data.leftover = left[:]
132	creator_git({op = "rm", dir = "e18"})
133	defer creator_git({op = "rm", dir = "e18"})
134	k := rc.ssh({op = "keygen", name = "e18", comment = E18_LABEL})
135	if k.code != 0 do return failing(b, &data, cat("ssh keygen failed: ", k.err, string(k.out)))
136	pub := strings.trim_space(string(k.out))
137	fp := e18_fp(pub)
138	data.fp = fp
139	added := false
140	// Never leave the key behind on a red round.
141	defer if added do e18_do(b, "key-rm", fmt.tprintf(`"fp":%s`, jq(fp)))
142	cloned := false
143
144	// 1. Paste it on apps, with the passkey approval of exactly this key.
145	approval, aerr := robot_approve("apps", "key-add", fmt.tprintf(`{{"fp":%s,"label":%s}}`, jq(fp), jq(E18_LABEL)))
146	if aerr != "" do return failing(b, &data, aerr)
147	r := e18_do(b, "key-add", fmt.tprintf(`"key":%s,"label":%s,"approval":%s`, jq(pub), jq(E18_LABEL), jq(approval)))
148	data.add = r
149	if jstr(r, "result") != "done" do return failing(b, &data, fmt.tprintf("apps did not add the machine: %s, %s", jstr(r, "result") or_else "?", jstr(r, "message")))
150	added = true
151	if e18_find(e18_wait(b, fp), fp) == nil do return failing(b, &data, "the added machine is not on apps's machine list")
152
153	// 2. It pushes, and the list shows that push.
154	p := e18_push("e18", "a push by a machine added on apps a moment ago", &cloned)
155	data.push = clip(p.out, 400)
156	if p.code != 0 do return failing(b, &data, cat("the added machine's push was refused: ", clip(p.out, 200)))
157	kk := e18_find(e18_wait(b, fp, pushed = true), fp)
158	data.last_push = jget(kk, "last_push")
159	if !jhas(kk, "last_push") do return failing(b, &data, "apps's machine list does not show the added machine's push")
160
161	// 3. Remove it on apps; its next push is refused.
162	r = e18_do(b, "key-rm", fmt.tprintf(`"fp":%s`, jq(fp)))
163	data.rm = r
164	if jstr(r, "result") != "done" do return failing(b, &data, fmt.tprintf("apps did not remove the machine: %s, %s", jstr(r, "result") or_else "?", jstr(r, "message")))
165	added = false
166	if e18_find(e18_wait(b, fp, gone = true), fp) != nil do return failing(b, &data, "the removed machine is still on apps's machine list")
167	p = e18_push("e18", "a push by a machine removed on apps a moment ago", &cloned)
168	data.push_after = clip(p.out, 400)
169	if p.code == 0 do return failing(b, &data, "a removed machine's push was ACCEPTED")
170	data.machines = e18_machines(b)
171	data.seconds = now() - t0
172	return pass(fmt.tprintf("a key pasted on apps (approved with the robot's passkey) pushed %s's e18-live and the list showed it; removed on apps, its next push was refused: %s (%d s)", E18_APP, first_line(p.out), data.seconds), data)
173}
174
175e18 :: proc() -> Exhibit {
176	return {
177		n = 18, wing = "Building",
178		title = "Add a laptop by pasting its key",
179		promise = "Pasting a machine's public key on apps lets that machine push; removing it stops it.",
180		block = "apps's Machines: paste a public key (~/.ssh/id_ed25519.pub) and a name, confirm it with your passkey, and that machine pushes as you; Remove stops it at once. Each machine shows its last push.",
181		src = {"e18_add_a_laptop.odin", #load("e18_add_a_laptop.odin", string)},
182		files = srcs({"robot.odin", #load("robot.odin", string)}, {"creator.odin", #load("creator.odin", string)}),
183		show = proc(me: ^rc.User) -> string {
184			apps := rc.app_url("apps")
185			yours := fmt.tprintf(`<p class="muted">Your machines are on <a href="%s/#machines">apps</a> (creators): paste a public key, confirm it with your passkey, and each one shows its last push. Your workbench's own key is on the same list, first, once you have opened the workbench.</p>`, h(apps))
186			d, s, found := stored_data(18, E18_Data)
187			if env().env != "live" do return cat(`<p>This is staging: its apps acts in a pretend world, where the robot is no creator, so its key is refused`, cat(" (", h(jstr(d.add, "message")), ")") if found else "", `. The live zoo adds and removes one.</p>`, yours)
188			if !found || d.fp == "" do return cat(`<p>Every six hours the robot, a creator, adds a machine on apps, pushes with it, removes it, and pushes again. It has not run yet.</p>`, yours)
189			b := strings.builder_make()
190			li :: proc(b: ^strings.Builder, tag: string, ok: bool, html: string) {
191				fmt.sbprintf(b, `<li><span class="tag %s">%s</span><span>%s</span></li>`, "ok" if ok else "bad", h(tag), html)
192			}
193			rc.render_to(&b, `<p>The robot, a creator, {{1}}:</p><ul class="list">`, {{"1", rc.raw(ago(parse_time(d.at)))}})
194			li(&b, "added", jstr(d.add, "result") == "done", fmt.tprintf("<code>%s</code> (%s), pasted on apps and approved with its passkey: %s", E18_LABEL, h(d.fp), h(jstr(d.add, "message"))))
195			lp := d.last_push
196			li(&b, "pushed", jhas(lp), cat("with it, <code>e18-live</code> of ", E18_APP, fmt.tprintf("; apps's list showed the push (%s %s %s)", h(jstr(lp, "app")), h(jstr(lp, "env")), h(jstr(lp, "commit"))) if jhas(lp) else ""))
197			li(&b, "removed", jstr(d.rm, "result") == "done", cat("on apps: ", h(jstr(d.rm, "message"))))
198			li(&b, "refused", s.ok && d.push_after != "", cat("its next push: ", h(first_line(d.push_after if d.push_after != "" else "not tried"))))
199			strings.write_string(&b, "</ul>")
200			if ms := jarr(d.machines); len(ms) > 0 {
201				names := make([dynamic]string)
202				for k in ms {
203					n := jstr(k, "label") or_else "?"
204					if jbool(k, "workbench") do n = cat("its workbench (the workbench's own key", ", kept off main and staging, a robot's" if jstr(k, "refs") == "branches" else "", ", removed" if !jbool(k, "on") else "", ")")
205					if jhas(k, "last_push", "at") do n = cat(n, " (last push ", day_hm(parse_time(jstr(k, "last_push", "at"))), ")")
206					append(&names, n)
207				}
208				rc.render_to(&b, `<p class="muted">The robot's machines on apps now: {{1}}.</p>`, {{"1", strings.join(names[:], ", ")}})
209			}
210			if !s.ok do rc.render_to(&b, `<p class="muted">{{1}}</p>`, {{"1", s.detail}})
211			return cat(strings.to_string(b), yours)
212		},
213		check = proc() -> Check {
214			d, s, found := stored_data(18, E18_Data)
215			last := parse_time(d.at)
216			due := last == 0 || now() - last >= (E18_EVERY if s.ok else E18_RETRY)
217			// Rounds run in the five-minute job; a "check now" reads the last one.
218			if due && g_in_job do return e18_round() if env().env == "live" else e18_staging()
219			if last == 0 do return fail("no round yet: the five-minute job starts one")
220			if now() - last > E18_STALE do return fail(fmt.tprintf("the last round is %.1f hours old: the rounds have stopped", f64(now() - last) / 3600), d)
221			// Between rounds, the robot's machine list as apps shows it now (its workbench's key appears there).
222			if env().env == "live" && g_in_job {
223				if b, err := robot_at("apps"); err == "" do d.machines = e18_machines(b)
224			}
225			_ = found
226			return {s.ok, s.detail, to_json(d)}
227		},
228	}
229}

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}

creator.odin sha256 1924fc3d7c2d · raw

1package main
2
3// The zoo's robot as a creator: git and `ratcloud` over ssh, as `zoo-robot`, the robot creator whose
4// apps are the zoo's samples it looks after (zoo-broken). A wasm app runs no process of its own:
5// git and ssh are the platform's named capabilities (`capabilities = git, ssh` in ratcloud.conf,
6// granted by root with `rc cap zoo git ssh --as zoo-robot`). Each call is one fixed shape (rc.git,
7// rc.ssh: clone, checkout, write, read, add, commit, push, rev-parse, rm; keygen, ratcloud), run as
8// the zoo's own unix user in its own workspace, with the robot creator's key from the zoo's secrets,
9// which never enters this program. It logs in exactly as a creator's laptop does: git, `ratcloud`,
10// nothing that is a shell.
11//
12// Exhibit 8's nightly (broken.odin), 18 (a machine key of its own for a minute) and 30 (asking for a
13// preview) use it.
14
15import "core:strings"
16import "ratcloud:rc"
17
18CREATOR :: "zoo-robot"
19
20Ran_Tool :: struct {
21	code: int, // the tool's exit code; -1: it did not run (out says why)
22	out:  string,
23}
24
25// git as the robot creator: its exit code and output (git's messages included).
26creator_git :: proc(t: rc.Tool) -> Ran_Tool {
27	r := rc.git(t)
28	if r.code < 0 do return {-1, r.err}
29	return {r.code, strings.trim_space(string(r.out))}
30}
31
32// `ratcloud <verb> <app> ...` over ssh, the verbs a creator's laptop has (tools PLATFORM.md).
33creator_ratcloud :: proc(words: ..string) -> Ran_Tool {
34	ws := make([]string, len(words))
35	copy(ws, words)
36	r := rc.ssh({op = "ratcloud", words = ws})
37	if r.code < 0 do return {-1, r.err}
38	return {r.code, strings.trim_space(string(r.out))}
39}
40
41// git's "remote: " prefixes off, as a person reads a push's answer.
42unremote :: proc(s: string) -> string {
43	b := strings.builder_make()
44	for line, i in strings.split_lines(s) {
45		if i > 0 do strings.write_byte(&b, '\n')
46		strings.write_string(&b, strings.trim_left_space(strings.trim_prefix(line, "remote:")) if strings.has_prefix(line, "remote:") else line)
47	}
48	return strings.trim_space(strings.to_string(b))
49}