CSE 331: Apps with users
Course motto: Your job is to deliver code that you know works.
Everyone wants a guestbook
The guestbook with JavaScript in its page keeps one book. Let's start it in one terminal, in the directory that holds it:
$ javac Guestbook.java
$ java Guestbook
Serving at http://localhost:9331/
Ada opens http://localhost:9331/ in her browser. She types her
name and a message, and clicks Post. Here is her page:
Then bob opens the page in his own browser, and he sees the same
page, with ada's message on it. When a visitor's page opens, its
program asks the server for the messages with the request
GET /api/messages. Every visitor's page sends that same request,
and gets the same answer. The book is shared.
When we first built the server,
we said it this way: "every request the program answers, from any
browser, reads it or adds to it."
In one sense that is a good thing, and it is what a guestbook is for. Anyone can leave a message, and anyone can see it.
Now the guestbook's users ask for something new. Everyone wants a guestbook of their own: one book per user. The new guestbook has three rules:
- Each user has a book at an address of their own, such as
/ada@example.com. - Any user who has signed in may read any book and sign it. The
signature is their login, the name they sign in with, such as
ada@example.com, not a name they type. - Only a book's owner may delete a message from it.
The guestbook cannot delete a message at all yet, so the third rule asks for a new operation as well.
The guestbook was written for one book, and the new guestbook needs many. This lecture is about how to make that change: one becomes many. A book for each user is today's case of it.
Before we change anything, we need to find where the guestbook assumes there is one book.
Where the program says one
The change starts with a search: every place where the guestbook
assumes there is one book. Make your own list before you read on.
(The page's files and the server's manual are in
the notes on JavaScript in the page,
and the field and Book are in
the notes on the first server,
at other line numbers.)
Here are four places:
-
The field
book, and its comment.Guestbookkeeps oneBook:22 23 24
public class Guestbook { // The one book, shared by every request the server handles. private static Book book = new Book(); -
The path
/api/messages, in the server's manual. Nothing in the path says which book:18 19 20
* GET /api/messages the messages posted so far, as JSON * POST /api/messages adds the message the fields send, then the * messages posted so far, as JSON -
The page's one list. Nothing on the page says whose book it is:
7 8 9
<h1>Guestbook</h1> <ul id="messages"> </ul> -
The tests. A guestbook that has just started answers these two runs so. The post names no book, and the read expects the one book back:
$ curl -d 'name=ada&message=hello' http://localhost:9331/api/messages ["ada: hello"] $ curl http://localhost:9331/api/messages ["ada: hello"]
Each of the four assumes there is one book. Only the comment on line 23 says so in words. We found the four by reading.1
The change from one book to many reaches all four: a field, a path, a page, and the tests. The next section asks why it reaches so far.
Why the change reaches everything
That should be a surprise. When we studied abstract data types, the point of an ADT was that a change to how its data is kept could stay inside it. An ADT's specification is written in terms of its abstract state, "which is how the client should think about the object". Its representation is "how its objects are implemented: the fields of the class, and what each field holds." And then:
The specification never mentions the representation, so the implementer may change it, as long as each method still satisfies its specification.
Book is an ADT. Yet changing one book into many reaches a
field, a path, a page, and the tests. To see why, sort the list
by the line between an ADT's clients and its implementation.
Nothing on the list is behind Book's line. Here is where Book
begins:
115 116 117 | |
Book's representation is its one field, messages, on
line 117. A list of signed messages says nothing about how many
books there are, and neither does the specification on line 115:
we could just have more than one Book.
So the whole list is on the clients' side, in two places:
Book's client. The fieldbookand its comment are inGuestbook.Guestbookmade oneBook, and nothing inBookasked it to.- The server's manual, and the manual's clients. The manual is
the server's specification,
and the path
/api/messagesis in it. Beside the path, on line 18, the manual promises "the messages posted so far": one sequence of messages for the whole server. That is the server's abstract state, and the new guestbook changes it, to a book for each user. So the manual changes, and the page's program and the tests, which rely on the manual, change with it.
So the change is not a change of Book's representation, the one
kind of change that Book keeps behind its line. It is a change
to Book's client, and to the server's abstract state.
Data abstraction keeps a client from depending on the representation. It cannot keep a client from depending on the abstract state, since the abstract state is what the client is meant to depend on.
In Reading 3, David Parnas begins a design with a list of the decisions likely to change, and hides each one inside a module, so that a change to the decision changes that module alone.2 The guestbook does not treat "one book" as such a decision. No module hides it. The comment on line 23 states it, the manual promises it, and the page and the tests rely on it.
So the redesign starts with the abstract state: we write the new one first.
A book for each user
Two things have to change. There was one Book, and now each
user has a book, so something has to keep the books, one for each
user. And the third rule gives each book an owner, who alone may
delete from it, so in the finished program a book also says whose
it is.
Where the check lives says why the book
itself has to know. So the finished program has two ADTs where
the earlier guestbook had one: Books, new, and Book, changed.
The finished program is a new Guestbook.java, with its page in
a new index.html and app.js. The rest of these notes read it
once, a layer at a time, starting here.
Here is the first line of the new Book:
279 280 | |
A book is now an owner and a sequence of signed messages. The owner is the user the book belongs to. The old words stay, and "the messages posted so far" now describes each book: the messages posted so far to this book.
Here are the specifications of Book's constructor and of add:
287 288 289 290 291 292 293 294 295 296 297 | |
User is a new class in the same file. A User is a user who has
signed in, named by their login, such as ada@example.com, as its
comment on lines 205 to 208 says.
A mistake that does not compile
says why a login is wrapped in a class, and not passed as a
String.
The constructor is handed the book's owner. add is handed
asker, the user who is asking to post, and signs the message
with that user's login. The earlier add signed "with the name"
it was handed. messages, on lines 317 to 321, is the earlier
guestbook's, word for word. Between add and messages,
lines 301 to 315 are delete, the new operation that the third
rule asks for. Where the check lives
reads it.
Books is new. Its comment, on line 252, gives its abstract
state: "The books: a book for each user who has signed in." It has
two operations:
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
open gives a user a book, and leaves a user who has one as they
were. bookOf is the lookup. It is handed a login, as a String,
and returns that user's book. The next section shows where the
server finds the login.
A user may have no book, so bookOf has to be able to say so.
When a method had to say no,
top returned an OptionalInt, "a value that either holds one
int or is empty." Java's
Optional
is the same wrapper for a value of any type: an Optional<Book>
either holds one Book or is empty. Line 275 makes it.
Map.get
returns null for a key the map does not hold, and
Optional.ofNullable
returns an empty Optional for null, and otherwise one that
holds the value.
Now the fields.
When we implemented abstract data types,
a representation invariant was "a claim about its fields that is
true of every object of the class whenever no method of the class
is running." The
abstraction function
"maps each value of the fields that the representation invariant
allows to the abstract state it stands for." Both are written as
comments beside the fields. Here are Book's:
280 281 282 283 284 285 | |
messages is the earlier guestbook's field. owner, on
line 281, is new, and it is final: it is assigned once, in the
constructor, and never again. The RI says that owner is never
null, and neither is any message in the list. The AF reads the
two fields as the abstract state: the book of the user in owner,
holding the messages in the list, oldest first.
Here are Books' fields:
252 253 254 255 256 257 258 | |
The one field is a map, from each user's login to that user's
Book. The RI says that the map files every book under its own
owner: ada@example.com maps to a book whose owner is ada, and
never to bob's. open keeps it true. Line 266 maps a user's login
to a new Book whose owner is that same user. The AF says which
users have a book: exactly the users whose logins are in the map.
So for any other login, bookOf is right to answer with an empty
Optional.
Line 275 returns the Book that the map holds, not a copy. Is that
representation exposure?
When we implemented abstract data types,
representation exposure was "a reference, held by code outside a
class, to a changeable object among the class's fields." A Book
is changeable, and after a call of bookOf the server holds one
of the Books in Books' map. The definition then says what the
harm is: through the reference, "that code can change the fields
without calling any method of the class, so the representation
invariant and every specification can be broken by code the class
does not control." The first half of that does happen here. The
server adds a message to a book that Books' map holds, and it
calls no method of Books to do so. The harm is the second half,
after "so", and that does not happen. A Book is itself an ADT,
and its clients are meant to change it, through its own methods.
Those methods keep Book's own RI. Books' abstract state is
which book belongs to each user, as a list's abstract state is
which objects it holds. Books' RI says nothing about a book's
messages. It is about the login of each book's owner, and neither
can change: owner is final in Book, and login is final
in User. So no client can break Books' RI, or its
specifications, through a Book.
The code quality guide's section
Avoid representation exposure
says that an ADT "should be the sole owner and reference to" the
changeable objects among its fields. By the letter, bookOf does
not follow that. Returning a copy would follow it. But then a
message added to the copy would never reach the user's book.
The two ADTs are written. The rest of the server relies on them, and the next section reads it.
The rest follows
The two ADTs hold the server's new abstract state. The list from Where the program says one was the server's own field, the manual, and the manual's clients, the page and the tests. Each has to be read again against the new abstract state. Let's take them from the server out to the tests.
The server. The field comes first:
35 36 37 38 | |
Where the earlier guestbook kept one Book, the finished program
keeps one Books, and the comment on lines 36 and 37 says so.
The path /api/messages named no book. Now the book joins the
path. Here is the part of the manual that lists the requests:
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
OWNER stands for a login. So ada's messages are at
/api/books/ada@example.com/messages, and the page for her book,
line 22, is at /ada@example.com. The manual's other new lines
belong to later sections: who sent a request, the delete, and what
/ and a missing book get.
handle first finds out who sent the request, and opens that
user's book:
61 62 63 64 65 66 67 68 | |
The sections after this one say how User.from finds out who sent
the request. Line 68 opens asker's book, and
What if there is no book? comes back
to it. Then handle answers by the path, as before. A path that
starts with /api/books/ goes to a new method, messages, which
takes the book from the path:
107 108 109 | |
Line 107 cuts the path at each slash, and line 108 takes its
fourth piece, the owner's login. Line 109 asks Books for that
user's book. If there is none, or the path is not one the manual
lists, messages sends 404. From there on, messages does what
the earlier handle did for /api/messages: a POST signs the
book, as asker, and the answer is the book's messages as JSON.
What differs is which book. The earlier handle used the one
field. messages uses the book in the path.3
The page. The page has to know which book it shows, and all it
has is its own address. Here are the new lines at the top of
app.js:
10 11 12 13 14 15 16 17 18 | |
location.pathname
is the path of the page's address, /ada@example.com on ada's
page. Line 12 drops its first character, the slash, and
decodeURIComponent
decodes what is left, a part of an address, into the login.
Line 15 builds the path the manual gives for that book's messages.
load and post send their requests to url, on
lines 60 and 68, where the earlier page sent them to
/api/messages. Line 18 writes the owner into the page's heading,
the <h1> with the id title on line 7 of index.html.
A page now shows one book, so the page's one list stays one list, and the heading says whose book it is. When bob opens ada's book, the heading reads ada@example.com's guestbook. The page takes whose book it is from its address, not from who is looking.
The tests. First stop the earlier guestbook: press
Ctrl+C in its terminal. From here on, stop
the running program the same way before you start the next one.
Then start the finished program, and send it three requests from
a second terminal. Each request carries the login of the user who
sends it, in a
header, a line
of the request with a name, a colon, and a value. The header is
Tailscale-User-Login, which curl adds with -H. Here the
header stands for signing in, and the sections after this one say
where it comes from:
$ curl -H 'Tailscale-User-Login: ada@example.com' -d 'message=hello' http://localhost:9331/api/books/ada@example.com/messages
["ada@example.com: hello"]
$ curl -H 'Tailscale-User-Login: bob@example.com' -d 'message=hi ada' http://localhost:9331/api/books/ada@example.com/messages
["ada@example.com: hello", "bob@example.com: hi ada"]
$ curl -H 'Tailscale-User-Login: bob@example.com' http://localhost:9331/api/books/bob@example.com/messages
[]
Ada signs her own book. Bob signs ada's, and his message goes after hers. Then bob reads his own book, and it is empty. His book was there to read, since line 68 opened it on his first request. And his message went to ada's book, the one in the path, and not to bob's.
Which book is now an input to every test, beside the request's fields. So a test has to choose it. With one book, a message has no wrong book to land in, so a test with one book cannot show that a message landed in the right one. Look at the first run alone. A program that kept one book for everyone, and signed with the login, would answer it the same way. The third run is the one that needs a second book: it shows that bob's message stayed out of bob's book.
Every request above carried its user's login in a header that we typed ourselves. Which parts of a request may the client choose? That is the next section's question.
Which book, and who says?
There was only one book, so a request never had to say which book it meant. Now a request carries two keys: the book it is for, and the user who sent it. Each key raises its own question. Who gets to choose it?
Any user who has signed in may read any book and sign it. So the
client may choose the book, and the program takes it from the
path. When bob asks for /api/books/ada@example.com/messages, he
gets ada's book, and that is what the request was for.
The user who sent it is another matter. In
the guestbook with JavaScript in its page,
the signer came from the request too. The page sent whatever was
typed in its Name box, and Book.add signed the message "with
the name". Start the earlier guestbook as it stands, and send it a
post from a second terminal:
$ curl -d 'name=zach&message=hello' http://localhost:9331/api/messages
["zach: hello"]
The book now holds a message signed zach. Who sent it? Look at the request before reading on.
Nothing in the request says. Its name field says zach, but anyone
can send those fields, from the Name box or from curl: bob, ada,
or zach himself. With one shared book, add signed a post with
whatever name the post sent, and its specification said so. With a
book for each user, a signature is a login, and it
says which user posted. A user may choose which book to sign.
Nobody may choose who they are.
When we first built the server, the notes said that the guestbook "can assume nothing about what the browser will send." A name the client sends is a name the client chose. So the server must not take the signer from a field. It has to learn who sent a request from something the client cannot choose.
Definition: authentication
Authentication is establishing who sent a request.
"Establishing" is the word that matters. The earlier guestbook was
told "zach", and it established nothing: it took a field's word
for it. To establish who sent a request, the server needs evidence
that the sender could not have made up. "Who" is a user, named in
the finished program by a login such as ada@example.com.
The notes on the first server also made a promise. Nothing in a request said who sent it, and those notes said: "A site that knows who you are was told so by your browser, in a request. A later lecture shows how, with cookies." This is that lecture. It keeps the promise in outline. The next section lists, with no code, how a site does it with cookies. The finished program uses no cookies. It learns who is asking from a header that Tailscale adds to a request from a user's device, as the sidebar after that shows.
Testing changes too. Who is asking is now an input, as the
request's fields are, so a test has to choose it. One user is not
enough. A test with only ada in it would pass on a program that
signed every message ada@example.com. That is the reason
one test is never enough:
"A single test cannot catch a method that always returns the same
answer, because that answer may be the one the test expects."
What, then, does the rest of the program need from authentication? Just one method.
Who is asking
With one book, no part of the program needed to know who sent a
request. Now handle needs to know it for every request, and it
asks one method, User.from. Here is its specification, from the
finished program:
218 219 220 221 222 223 | |
from returns an Optional, as bookOf does: an
Optional<User> either holds one User or is empty. Empty is how
from says that it found no user.
handle calls from once, on line 61. When from returns an
empty Optional, lines 62 to 66 answer the request and return.
Otherwise line 67 takes the User out, as asker, and handle
hands asker on to whatever needs to know who is asking. No
method but from reads the header. That is
procedural abstraction:
"using a method through its specification alone." The handlers
rely on less than the whole specification, too: on a User who
sent the request, or on there being none. So how from finds out
who is asking can change, from a header to a cookie, say. The
clause about the header would change with it. No handler relies on
that clause, so handle, messages, post, and Book would
stay as they are.
How would from find out with no Tailscale? A program that
checks passwords itself needs these pieces, in the order a user
meets them:
- The password, never stored. The server keeps, for each user, not the password but the result of a one-way function of it: easy to compute, hard to undo, and slow on purpose. Before applying the function, the server mixes in a random number, the salt, which it keeps beside the result. When the user signs in, it applies the function to what was typed, with the same salt, and compares the results. A stolen file then holds no passwords. The slowness makes each guess cost a thief time, and a different salt for each user keeps the thief from looking the results up in a table computed ahead of time.4
- A sign-in form, over HTTPS. The user types the password into a form, and the browser sends it over HTTPS, "the form of HTTP that encrypts the whole exchange", so that nobody on the network can read it.5
- A session, in a cookie. When the password checks out, the server starts a session, a sequence of requests that it ties to that user. The server gives the session a long random number, its identifier, and remembers the number beside the user. It hands the number to the browser in a cookie, a value that the browser keeps for the site and sends back to it in a header.6
- The cookie, on every later request. The browser sends the
cookie with every request after that. The server looks up the
user from the number, and that lookup is the job
User.fromwould do. - The rest. Signing out, sessions that expire, a limit on guesses at a password, and a way back in for a user who has forgotten theirs.7
Doing all this yourself is hard to get right. A classic paper on protection says what rests on it: checking every access "implies that a foolproof method of identifying the source of every request must be devised."8 Each item on the list is a place to fall short of foolproof. Even the way back in, which looks simple, is "a common source of vulnerabilities".9
So a program can hand the job to someone else. One way is an identity provider, a service that checks who the user is and tells the program. OpenID Connect is a standard for that: it lets a program "verify the identity of the End-User based on the authentication performed by" the provider. Google's sign-in APIs conform to it.10 Another way is the session code a web framework ships. (A web framework is a library that a server for the web is built on.) OWASP recommends that code "versus building a home made one from scratch".11
The finished program hands the job to Tailscale, which hands it in turn to an identity provider. The sidebar shows how.
A sidebar: Tailscale
Where does the finished program get its answer to who is asking? This section is a sidebar, on one neat way to be handed that answer with no password code at all. It is how the finished program is run. The next section picks up the lecture's thread again.
Tailscale connects devices into a private network, called a
tailnet. A user joins a device to a tailnet by signing in on
it, and Tailscale does not check the password itself. When a user
signs in on a new device, "an identity provider authenticates the
user".12 Tailscale's Serve passes requests from the other
devices on the tailnet to a server on your own machine. The
finished program's opening comment, on lines 15 and 16 of
Guestbook.java, says to run it with tailscale serve 9331 in
front of it. Serve then prints an HTTPS
address, ending in ts.net, that is available only within the
tailnet. It passes each request sent to that address on to the
guestbook, at port 9331.13
Serve also tells the guestbook who is asking. To each request it
passes on from a user's device on the tailnet, it adds headers
that say which user sent the request.
One is Tailscale-User-Login, "Filled with the requester's login
name (for example, alice@example.com)."14 So the body
of User.from is short:
223 224 225 226 227 228 229 230 | |
Lines 224 and 225 read the header.
getFirst
returns the header's first value, or null if the request has no
such header. Line 226 treats a missing header and an empty one alike:
either way, there is no user.
These notes cannot show a run through a real tailnet. So in the
runs below, curl plays Serve's part: it sends the header itself,
with -H. Start the finished program, and first send a request
with no header at all:
$ curl http://localhost:9331/
not signed in
Lines 61 to 66 of handle sent that answer, before handle looked
at the path. Its status is 401, a status in the 400s that says the
request does not show who sent it. (curl -i prints the status
line too: its first line is then HTTP/1.1 401 Unauthorized.)
With the header, the guestbook answers as the header says. Ada
asks /api/me, which sends back the login of the user asking:
$ curl -H 'Tailscale-User-Login: ada@example.com' http://localhost:9331/api/me
ada@example.com
Now bob sends ada's book the very fields of zach's post above,
name=zach among them:
$ curl -H 'Tailscale-User-Login: bob@example.com' -d 'name=zach&message=hello' http://localhost:9331/api/books/ada@example.com/messages
["bob@example.com: hello"]
The post is signed bob. post reads only the message field, and
Book.add signs with asker's login, on line 298.
The page has no Name box anymore: index.html holds a Message box
and the Post button, on lines 10 and 11. Behind Serve, the
signature no longer passes through anything a user types.
If zach sends Serve a request with a Tailscale-User-Login header
of his own, Serve removes the header from the request before
passing the request on.15
The sidebar has a limit. Serve's headers identify only people on your tailnet, and people a device was shared with: Tailscale's documentation says it fills in the headers "when your friend visits the Serve URL" of a device shared with them. An app for the public, whose users have never joined your tailnet, would hand the job to an identity provider, as Who is asking described. And Tailscale's public mode, Funnel, carries no identity headers at all.16
So the guestbook now knows who sent each request it answers. What each user may then do is another question that one book never raised: who may do what?
Who may do what?
With one shared book, the guestbook never had to ask what a user may do. The book had no owner. So every visitor could do everything the guestbook offered: read the book, and post to it. A book for each user has an owner, and the new guestbook's third rule gives the owner something that nobody else may do:
Only a book's owner may delete a message from it.
Knowing who sent a request does not settle this. Authentication tells the guestbook that a DELETE came from bob. Whether bob may delete a message from ada's book is a second question, and the guestbook answers it with its own rule.
Definition: authorization
Authorization is deciding what the user who sent a request may do.
The box has the shape of the box for authentication. "The user who sent a request" is what authentication established, so authorization comes after it and relies on it. "Deciding" is done by rules, and the rules are the program's own. Today's are the new guestbook's second and third rules: any user who has signed in may read any book and sign it, and only a book's owner may delete a message from it.
Where should the guestbook decide? Here is one design, in a copy
of the finished program, nocheck/Guestbook.java. In this copy
the page decides. Here is show, in app.js, which draws the
page:
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
me is a variable of the page's program, declared on line 21. It
holds the login the server sent back for /api/me, which load
asks for on lines 58 and 59. owner is the login in the page's
own address, on line 12. On line 38, === is JavaScript's
comparison. For two strings, it is true when they hold the same
characters. So show adds a Delete button to each message only
when me holds the login of the book's owner. A click on the
button calls remove, which sends a DELETE for that message.
And here is Book.delete in nocheck/Guestbook.java:
300 301 302 303 304 305 306 307 | |
The handler calls it on line 129, as book.delete(index), for
every DELETE whose path gives the index of a message in the book.
Here is nocheck/Guestbook.java in the browser, with both users.
A browser sends no Tailscale-User-Login header of its own. So
these steps were run in a Chrome that sent each user's header with
every request, in Serve's place, as curl does. Ada opens her
book and posts two messages, hello and welcome, all. Each
message on her page has a Delete button. Bob opens ada's book, at
/ada@example.com. He sees both messages, with no Delete button
beside either. He posts hi ada, and his page shows three
messages, still with no buttons. Ada reloads her page, and she
sees all three, each with a Delete button.
So the page shows bob no Delete button on ada's book. Is it right? Can bob still delete one of ada's messages? Find a way before you read on.
Bob has two ways.17 The first is the console, as when we studied the data behind the page. Bob opens it on ada's book and types three lines:
> me
"bob@example.com"
> me = "ada@example.com"
"ada@example.com"
> show()
undefined
The first line reads me, which holds bob's login, as the server
sent it. The second line assigns ada's login to me. The page
does not change yet, since nothing redrew it. The third line calls
show, and the page now draws a Delete button beside each of the
three messages. Bob clicks the first one. The server answers with
the status 200, and ada's hello is gone from the book.
The check ran in bob's browser. It compared a variable that bob can assign.
The second way skips the browser. Bob sends the DELETE with curl.
As in the sidebar, curl plays Serve's part and sends the login
in the header itself. Start nocheck/Guestbook.java again, so
that no book holds a message. Ada posts, and then bob deletes:
$ curl -H 'Tailscale-User-Login: ada@example.com' -d 'message=hello' http://localhost:9331/api/books/ada@example.com/messages
["ada@example.com: hello"]
$ curl -H 'Tailscale-User-Login: bob@example.com' -X DELETE http://localhost:9331/api/books/ada@example.com/messages/0
[]
-X DELETE tells curl to send the request with the method
DELETE. The server deleted ada's message for bob, and answered
with her book, now empty.
Neither way changed a line of the server. Each sent a
DELETE that the server accepted, since Book.delete in
nocheck/Guestbook.java deletes for whoever calls it. The page's
check said only which buttons to draw.
We have met this before.
When we studied the data behind the page,
Exercise 1 put a check for an empty name in the page, and asked
why the server had to check too. Its answer named two ways around
such a check: a visitor can call fetch at the console with any
fields they like, or replace app.js with their own program.
"The check in the page spares a visitor a round trip. Only the
server's check decides what gets into the book." The reason goes
back to
when we first built the server:
the server "can assume nothing about what the browser will send."
The guestbook's own page is no exception. It runs in bob's
browser, and bob can change what it does or go around it.
So a check in the page can make the page easier to use. It cannot decide who may delete.18
The fix is to decide on the server. The finished program compares
the user who sent a DELETE with the book's owner. When the two
differ, it refuses the request. Here is the same curl run
against the finished program, started fresh, with bob signing
ada's book first so that his refused delete has a message to aim
at:
$ curl -H 'Tailscale-User-Login: ada@example.com' -d 'message=hello' http://localhost:9331/api/books/ada@example.com/messages
["ada@example.com: hello"]
$ curl -H 'Tailscale-User-Login: bob@example.com' -d 'message=hi ada' http://localhost:9331/api/books/ada@example.com/messages
["ada@example.com: hello", "bob@example.com: hi ada"]
$ curl -H 'Tailscale-User-Login: bob@example.com' -X DELETE http://localhost:9331/api/books/ada@example.com/messages/0
bob@example.com does not own this book
$ curl -H 'Tailscale-User-Login: ada@example.com' -X DELETE http://localhost:9331/api/books/ada@example.com/messages/0
["bob@example.com: hi ada"]
Bob's DELETE is refused, and ada's hello stays in the book. Then
ada sends the same DELETE, and the server deletes hello.
The refusal's status is 403. (curl -i prints the status line
too: its first line is then HTTP/1.1 403 Forbidden.) HTTP's
standard says that a 403 means the server "understood the request
but refuses to fulfill it."19 The guestbook's 401, in the
sidebar, said that a request did not show who sent it. Bob's
request does show who sent it, and the guestbook refuses it
anyway.
Bob's first way fares the same. Start the finished program fresh,
and repeat the browser session above. Bob's three lines at the
console print what they printed before, and show draws a Delete
button beside each message again. But his click on the first one
gets a 403, and ada's book still holds all three
messages.20
Testing changes with the rule. A test in which ada deletes from
her own book passes on nocheck/Guestbook.java: her page draws
the buttons, and the server deletes. A test that uses only the
page's buttons passes too, since the page draws them only for
the owner.
When we studied testing,
the advice was to "choose an input for each case the specification
describes". The rule describes two cases: the user who sent the
DELETE owns the book, or does not. So a test of the rule needs two
users. And the second case reaches the server only in a request
that the page never sends, such as bob's curl. So
a test of the rule sends that request itself, as curl did above.
The fix put the comparison on the server. The server has more than one method it could go in, though, and the choice matters.
Where the check lives
In which method does the comparison go? The handler, messages,
could compare the user who sent the DELETE with the book's owner
before it calls delete. Or Book.delete could compare them
itself. Either place could refuse bob's request. The two differ in
how much code we have to read to know that only owners delete.
We have asked this before. The front page of the lecture on abstract data types asked: "how much of the code do we have to test or reason about in order to be sure the rules are followed?" Its answer: "all the code that modifies the data." With an ADT, it went on, "we only need to test and reason about the ADT itself, not the rest of the program."
Take the comparison in the handler first. Book.delete would then
be the one in nocheck/Guestbook.java, which deletes for whoever
calls it. The rule would hold only if every call of delete came
after a comparison. To know that, we would read every handler that
can reach a Book, since books.bookOf hands a Book to any
handler that asks. That means today's handlers, and every handler
written later. A handler added next year to clear a book would
have to remember the comparison, and javac would not remind
its author.
Now take the comparison inside Book.delete. Here is the method,
with its specification, from the finished program:
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
delete takes the asker as a parameter. Line 310 compares the
asker with the book's owner, the field on line 281, and when they
differ, lines 311 and 312 throw before line 314 removes anything.
So "leaves the book unchanged" is true at the throw with nothing
to undo, as
when we studied exceptions:
"Check first when you can."
With the comparison here, the code to read, to know that every
delete is compared with the book's owner, is Book,
lines 279 to 322. Two facts make that enough:
deletecannot be called without an asker. A call has to pass one, andjavacrefuses a call that does not.22- No other method removes a message. The list
messagesis a private field, on line 282. InBook, line 298 adds to it, and line 314 removes from it. Nothing else changes it. Andmessages()hands out a copy, on line 320, so a client cannot remove a message through what it returns.
So every delete passes through the comparison on line 310.21 A handler written next year cannot delete from a book without going through it.
So the first fact is one that javac checks. The second fact,
that no other method removes a message, we know by reading Book.
The rule is also written where a client can read it: in delete's
specification, on lines 305 and 306. A handler's author learns the
rule from the @throws clause, with no need to read the method's
body.23
The handler catches the exception and turns it into the 403:
124 125 126 127 128 129 130 | |
Lines 127 and 128 send the exception's message as the body. That
is the line bob's curl printed against the finished program:
bob@example.com does not own this book.
One thing is left for the handler to get right. On line 125, it
passes asker, the user who sent the request. What keeps a
handler from passing something else? That is the next
section's question.
A mistake that does not compile
With many books, the delete handler holds two keys. One is
asker, the user who sent the request. The other is owner, the
login that the path names, which the client may choose. Each key
has its own job: owner says which book, and asker says who
wants the message gone. In a program where both are a String,
nothing but the care of the handler's author keeps them apart.
Here is such a program, a copy of the finished program,
strings/Guestbook.java. In the copy, Book holds its owner as a
String, on line 281, and its constructor, add, and delete
take a String where the finished program's take a User.
Books.open, on line 266, and post pass asker.login(), the
login. No line is added or removed, so every
line number is the finished program's. As before, messages is
handed asker, a User, and takes owner from the path on
line 108. Here is the part of messages that answers a
DELETE:
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
And here is Book.delete in strings/Guestbook.java:
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
Is it right? Read line 125 against delete's parameters before
you read on.
javac accepts strings/Guestbook.java, and prints nothing. Start
it in one terminal:
$ javac Guestbook.java
$ java Guestbook
Serving at http://localhost:9331/
Then send it, from a second terminal, the two requests that
nocheck/Guestbook.java got in
Who may do what?. Ada posts to her own book,
and then bob sends a DELETE for her message:
$ curl -H 'Tailscale-User-Login: ada@example.com' -d 'message=hello' http://localhost:9331/api/books/ada@example.com/messages
["ada@example.com: hello"]
$ curl -H 'Tailscale-User-Login: bob@example.com' -X DELETE http://localhost:9331/api/books/ada@example.com/messages/0
[]
Bob deleted ada's message, and the server answered with her book,
now empty. Yet this delete has its comparison, on line 310. Look
at what it compared. Line 125 passes owner, the login from the
path, as delete's first argument, where asker belongs. Bob's
path named ada's book, so owner held ada@example.com. Inside
delete, the parameter asker then held ada@example.com too.
Line 310 compared it with the field owner, ada's login. So the
handler passed the owner as the asker, and delete compared the
owner with the owner. Books' RI, on lines 255 and 256, says that
each login maps to a book whose owner has that login. So the two
are equal on every DELETE that finds a book, line 310 never
throws, and anyone deletes from any book.
javac accepted line 125, since delete asks for a String and
an int, and owner is a String. A String says nothing about
whose login it holds, or where the login came from.
The finished program gives the asker its own type. Here is
User, whole:
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
The constructor, on line 214, is private, so only code inside
User can call it. The one call is on line 229, in from, which
Who is asking read. So the only way to get a
User is to call from on a request, and from returns the user
who sent it. The comment on line 207 says so: "The one way to get a
User is from a request."
In the finished program, Book holds its owner as a User, on
line 281, and add and delete take one, on lines 297 and 308.
The owner from the path stays a String, on line 108, since the
client may choose it. So the types say which key is which. A
User is a user who sent a request. A String is whatever the
client put in the path.
Now make the same mistake in the finished program.
mistake/Guestbook.java is a copy of it with one line changed,
line 125:
124 125 126 127 128 129 130 | |
Compile mistake/Guestbook.java:
$ javac Guestbook.java
Guestbook.java:125: error: incompatible types: String cannot be converted to User
book.delete(owner, index);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
javac refuses mistake/Guestbook.java at line 125, with its
caret under owner. delete asks for a User, and owner is a
String. (The note says that javac shortened its message, and
that the option -Xdiags:verbose prints it whole.) Since javac
refuses mistake/Guestbook.java, javac writes no class file.
So the mistaken handler never runs, and bob deletes nothing.
We turned a coding mistake into a compile-time error. In
strings/Guestbook.java, knowing that every call passes the user
who sent the request meant reading every handler that calls add
or delete: today's, and every one written later. Now javac
checks part of it, each time it compiles the program: every call
passes a User, and never a login from a path. As in
Where the program says one, the
claim javac was built to check is type safety: on every run, a
variable refers only to objects of its declared type. delete's
parameter asker is a variable of type User, so on every run it
refers only to a User. (A variable may also be null, as
the notes on generics
said. No call in the program passes null.) And reading User
once showed that every User comes from from, from a request.
Reasoning chose the claim, by making the asker a type that only
from can make. The tool checks it from then on.
The type does not check everything. It says that delete is
handed a User. It does not say which request that User came
from: that line 125 passes asker, the user who sent this
request, we know by reading the handler. And it does not say what
delete does with it. That line 310 compares asker with the
book's owner, and that lines 311 and 312 throw when the two
differ, we still know by reading Book.
Line 310 compares two User objects with equals. So User has
its own equals, on lines 237 to 244. The User in asker was
made on line 229, for this request. The User in the field
owner came from the request that opened the book, and line 266
handed it to the new Book. So the two are two objects that
stand for one user.
When we studied equality,
two objects of an abstract data type were equal "when they stand
for the same abstract value", so equals compares the logins.
The rule there
was to "write hashCode from the same abstract value, in the same
class", and lines 246 to 249 do.
So only a book's owner can delete from it, and javac refuses
any call of delete that does not pass a User. Every request so
far that named a book named one that was there, though. One book
never raised the question of what happens when a request names one
that is not.
What if there is no book?
There was always a book. Line 24 of the earlier guestbook made it when the server started, and every request found it there. With many books, two new cases come up. A request can name a book that does not exist, such as cy's, when cy has never signed in. And a user can arrive with no book, on their first request.
The finished program settles both with one rule: a book exists
only for a user who has signed in. Line 68 of handle,
books.open(asker), runs on every request from a user who has
signed in, before handle looks at the path. So a user's first
request gives them a book, an empty one, as bob's first request
did in The rest follows. And open is the
only method that adds to Books' map, on line 266. So a user who
has never signed in has no book.
A path that names a user with no book gets a 404. Here ada asks for cy's messages, and then for cy's page:
$ curl -H 'Tailscale-User-Login: ada@example.com' http://localhost:9331/api/books/cy@example.com/messages
not found
$ curl -H 'Tailscale-User-Login: ada@example.com' http://localhost:9331/cy@example.com
not found
For the messages, bookOf on line 109 found no book, and
messages sent the 404. For the page, handle asked bookOf
too, and found none. A 404, Not Found, says that
the server "did not find a current representation for the target
resource":24 it has nothing at that address. (With
curl -i, the first line printed is HTTP/1.1 404 Not Found.) The
manual's last line, line 33, states the rule: "A path that names a
user with no book gets 404." And /, which was the one book's
page, now sends each user to their own book.25
None is a case to test, too. A program with one book never met a
missing book, so nothing in its tests tried one. As in
Who may do what?, a test chooses an input for
each case the specification describes. One of the cases
when we studied testing
was an empty range, "with lo == hi". The guestbook has three
cases of none:
- a book that does not exist, as cy's;
- a user's first request, before they have a book, as bob's post to ada's book was;
- a book with no messages, as bob's own book after that post.
The third is not new. The earlier guestbook's one book started with no messages, so its tests could try that case too. The runs in these notes try each one, and each belongs among the guestbook's tests. The last section steps back from the guestbook, to the ones in any program.
One versus many
The finished program has a book for each user. It still
assumes there is one of several things. Read Guestbook.java
again and find some before reading on.
Here are four, each at a line you can point at:
- One owner for each book.
Bookkeeps its owner in one field, on line 281, anddeletecompares the asker with that owner, on line 310. The program has no way to give a book two owners. - One signature on each message. A message is one
String.addmakes it from one login and the text, on line 298. The program has no way to sign a message with two logins. - One book for each user.
Books.opengives a user a book only if the user has none, on lines 265 and 266. A user who wants a second book, for a club, cannot have one. - One server. The books are one field,
books, on line 38, in one running program. A second copy of the server, on a second machine to share the work, would have its ownbooks. The two copies would keep different books.
None of these is a bug. The new guestbook's rules asked for none
of them to be many. Programs are often full of ones like these,
and many of them were never decided: they were assumed, as one
book was. Name more, in the guestbook (app.js has some) or in
your own project.
Next, write them down. The earlier guestbook stated its one book
in a single comment, on line 23, and nowhere else. We found the
other places on our list by reading. The finished program states
some of its ones in its specifications. Book's, on line 279,
begins "An owner". Books', on line 252, is "a book for
each user who has signed in". And add's, on line 294, says it
signs the message "with asker's login". When a specification
states a one, the next person to change the program can find it
there, without the search we made. No specification in
Guestbook.java says that there is one server.
Last, know how to make one into many, later, if it is needed. This lecture's method is a place to start:
- Find every place that assumes the one, as in Where the program says one.
- Sort the places by the line between an ADT's clients and its implementation, as in Why the change reaches everything.
- Write the new abstract state first, as in A book for each user.
- Let the rest follow from it, as in The rest follows.
- Ask what many brings that one never raised: which one, and who says; who may do what; and what if there is none.
When we studied testing, we named three ways to gain the knowledge that code works. Each had a part in the method:
- Reasoning is to "argue from the code itself that it meets
its specification on every run." The line between an ADT's
clients and its implementation told us, before we wrote the new
program, where the change had to go. No place on our list was
inside
Book. The list wasBook's client, the server's manual, and the manual's clients. Later, the check insideBook.delete, on lines 310 to 313, kept the argument that every delete is compared with the book's owner to one class. No other method ofBookremoves a message. - Tools "let another program check yours." The type
Usergavejavaca new claim to check. With the asker aUser,javacrefused the handler that passed the owner from the path where the asker belongs: "String cannot be converted to User". We turned a coding mistake into a compile-time error. And Tailscale, with the identity provider it hands the job to, is a tool in the different sense that the notes on persistent data gave: "another program, built and checked by others, that keeps the promise for us". Here the promise is the oneUser.fromrelies on: the header holds the login of the user who sent the request. - Testing is to "run the code on inputs chosen on purpose, and
check each run against the specification." The inputs grew. A
request now says which book, and it comes from a user. So the
tests need two of each. With one book, a test cannot see a
message land in the wrong book. With one user, every delete is
by the book's owner, so a test cannot tell
nocheck/Guestbook.javafrom the finished program. The tests also need the three cases of none: a book that does not exist, a user's first request, and a book with no messages. And they need a request with no login, and a request the page would not send on its own, such as bob's delete from ada's book.
None of this says to build for many from the start. The earlier guestbook was asked for one book, so it was right to have one. Many brought three new classes, a new operation, a 401 and a 403, and three questions that one book never raised. The new guestbook's rules are what said who owns a book and who may delete from it. Before them, nobody had said. In Parnas's terms, nobody had listed one book as a decision likely to change.
A book for each user was one case of this change. The same change comes in other forms:
- a single-tenant app goes multi-tenant: built for one company, it now serves many;
- a to-do app that kept one list lets each user keep several;
- an app that assumed one device for each user has to work on their phone and their laptop at once;
- an app built for one currency, language, or time zone adds a second.
In each of these, a program written for one of something has to serve many.
Exercises
Each answer is folded under its question. Write yours first.
1. The finished program assumes one owner for each book, as One versus many found. Suppose the third rule changes, so that a book may have several owners. It now reads:
Any of a book's owners may delete a message from it.
Follow this lecture's method on paper, with no new program:
- List every place in the finished program that assumes one owner, with its line numbers.
- Sort the places by the line between
Book's clients and its implementation. - Write
Book's new abstract state, and each specification that changes. - Say what several owners bring that one owner never raised.
Here are Book and its exception, whole, from the finished
program:
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | |
The rest of the program is in the sections above: the manual and
messages in The rest follows, Books in
A book for each user, and show, from
app.js, in Who may do what?.
Answer
-
Five places are behind the line, in
Book's implementation. They are the representation, its RI and AF, and the code that uses it:- line 281, the field
owner, which holds oneUser; - line 283, the RI, "owner is not null";
- lines 284 and 285, the AF, "the book of owner";
- line 289, the constructor's body, which assigns the one owner;
- line 310, which compares the asker with that owner.
- line 281, the field
-
Four places are
Book's specification and its exception's, whichBook's clients rely on.- line 279, the abstract state: "An owner, and the messages posted so far";
- line 287, the constructor, which "makes owner's book";
- lines 305 and 306,
delete's@throwsclause: "if asker is not the book's owner"; - line 324, the comment on
NotOwnerException: "a user who is not the book's owner".
-
The rest are in
Book's clients.Books. Its RI, on lines 255 and 256, files each login under "a book whose owner has that login".bookOf's@return, on line 271, gives "the book of the user whose login is owner", and line 274 names its parameterowner.- The manual. Line 21 sends a user "to their own book".
Lines 22 and 25 to 32 write each book as
OWNER, and line 31 deletes "for OWNER alone". messages. Line 108 names the login in the pathowner.app.js. Line 12 takesownerfrom the page's address, and the comments on lines 10 and 30 call that login "the book's owner". Line 38 draws the Delete buttons only whenme === owner.- The tests. The runs in Who may do what? have one owner, ada, and one user who is not, bob.
-
The change crosses the line, but little of the clients' code changes. The abstract state changes, so every client has to be read again. Most of the clients' code still does what it should. Line 125 still calls
delete(asker, index), and line 266 still callsnew Book(user). The comparison is insideBook.delete, so the handler needs no new check. Most of what changes in the clients is words. The page's check is the exception. Line 38 comparesmewith the one login in the page's address, so a second owner would see no Delete button. The page has to learn the book's owners from the server, so the manual needs a request that sends them, and one that adds an owner. -
The new abstract state keeps one name for each book. Today the login in a path names a book's owner. With several owners, bob may own ada's book as well as his own, which line 68 opened on his first request. Then "bob's book" no longer names one book. So keep the login in the path as the book's name: the user the book was opened for, by
Books.open.Book's new abstract state:A book opened for one user: its owners, a set of users that always includes the user it was opened for, and the messages posted so far, oldest first.
-
Three specifications change, and one operation is new.
The constructor. Makes the book opened for owner, with owner as its only owner, and no messages.
delete. As before, except that it throwsNotOwnerExceptionif asker is not one of the book's owners, and then leaves the book unchanged.addOwner(asker, login), new. Modifies the book. Adds the user whose login is login to the book's owners. ThrowsNotOwnerExceptionif asker is not one of the book's owners, and then leaves the book unchanged.NotOwnerException. A change to a book by a user who is not one of the book's owners.addandmessageskeep their specifications. OutsideBook,Books' RI andbookOfspeak of the book opened for each user, and line 31 of the manual deletes for the book's owners. The manual also gains the two requests that send a book's owners and add one. -
Several owners bring questions that one owner never raised.
- Who may add an owner? The rules do not say. The
specification above lets any owner add one. Another rule
would let only the user the book was opened for. Either way
the rule says who may do what, so it goes in
addOwner's specification, insideBook, for the reason in Where the check lives. - Who is the new owner?
addOwnertakes a login, aString, and not aUser. Line 207 says "The one way to get a User is from a request", and the new owner did not send the request. So the new owner's login comes from what the request sends, which the client chooses, as it chooses the book in the path. - What if a book has no owner? With this abstract state it cannot: the user a book was opened for is always one of its owners. A later request to let that user leave would change the abstract state. If the last owner may then leave, nobody may ever delete from that book, or add an owner to it. The specification of the removal has to say which.
- How many users does a test need? Three. Ada adds bob as an
owner of her book. Bob's delete from her book now succeeds.
Zach's delete, and his
addOwner, are both refused. Two users cannot show both cases at once: a second owner who may delete, and a user who still may not.
- Who may add an owner? The rules do not say. The
specification above lets any owner add one. Another rule
would let only the user the book was opened for. Either way
the rule says who may do what, so it goes in
2. Here is Books, whole, from the finished program:
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
Name each "one" that Books assumes. For each, say whether the
comments and specifications in the listing state it, and with
which words.
Answer
-
One book for each user, stated in three places. Line 252 says "a book for each user who has signed in".
opengives a user a book "if user has none", on line 262, so a user never gets a second one.bookOfreturns "the book of the user", on line 271. The code keeps the one: the map on line 254 holds oneBookfor each login, and line 265 keepsopenfrom replacing a book a user already has. -
One login for each user, stated in the AF. The map's key, on line 254, is one
String. The AF, on line 257, speaks of "each user whose login is in books". So to the program, two logins are two users, with a book each, even when one person signs in with both. -
One owner for each book, stated in
Books' RI. Lines 255 and 256 say that each login maps to "a book whose owner has that login". The one owner isBook's, andBooksrelies on it. So Exercise 1's change reachesBooksthrough these two lines, and throughbookOf's specification, on line 271. -
Each one is stated in a few words that say how many. They are "a book for each user", "if user has none", "the book", "each user whose login", and "whose owner". The earlier guestbook stated its one book in a single comment, on line 23 of that program, and Where the program says one found the other places by reading. Here, someone who wants to give a user a second book can find
Books' ones by readingBooks' comments. That is the advice of One versus many: write the ones down.
3. The copy nocheck/Guestbook.java, from
Who may do what?, differs from the finished
program only in comments, in the handler's one call of delete,
and in delete itself. Here is the finished program's delete:
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
And here is the copy's:
300 301 302 303 304 305 306 307 | |
The finished program's handler calls book.delete(asker, index), on
line 125, and the copy's calls book.delete(index), on line 129.
Write the requests of a test, as curl lines, that passes on the
finished program and fails on the copy. Say what response the test
expects. Then say why no test with one user can tell the two programs
apart.
Answer
-
The test sends two requests, from two users. Start the program fresh. Ada posts to her own book, and then bob asks to delete message 0 from it. The test expects the second response to have the status 403 and the body
bob@example.com does not own this book. Ada's post comes first so that the DELETE names a message the book holds. Without it, both programs answer 404, before either callsdelete. -
The finished program passes. Here is the test, run on it:
$ curl -H 'Tailscale-User-Login: ada@example.com' -d 'message=hello' http://localhost:9331/api/books/ada@example.com/messages ["ada@example.com: hello"] $ curl -H 'Tailscale-User-Login: bob@example.com' -X DELETE http://localhost:9331/api/books/ada@example.com/messages/0 bob@example.com does not own this bookLine 310 finds that bob is not ada, lines 311 and 312 throw, and lines 127 and 128 send the 403 with the exception's message. The response is the one the test expects. (With
curl -i, its first line isHTTP/1.1 403 Forbidden.) -
The copy fails. Here is the same test, run on the copy:
$ curl -H 'Tailscale-User-Login: ada@example.com' -d 'message=hello' http://localhost:9331/api/books/ada@example.com/messages ["ada@example.com: hello"] $ curl -H 'Tailscale-User-Login: bob@example.com' -X DELETE http://localhost:9331/api/books/ada@example.com/messages/0 []The copy's
deleteremoves message 0 for bob, on line 306, and the handler sends ada's book, now empty. The test expected the status 403 and bob's refusal. It got the status 200 and[]. (Withcurl -i, the first line isHTTP/1.1 200 OK.) -
A test with one user cannot tell the two apart. Suppose every request in a test comes from ada, or carries no login. The line numbers below are the finished program's, and the copy has the same code at its own line numbers:
- A request with no login gets 401, from lines 61 to 66.
- Ada's requests open only her own book, on line 68. So a
DELETE that names any other book gets 404 from
messages, beforedeleteis called. - So every call of
deletehas ada as the asker, on ada's book. In the finished program, line 310 finds that the asker equals the owner, and line 314 removes the message, as the copy's line 306 does.
The rest of the two programs is the same code. So on every run of such a test, the two programs send the same responses. A test of the rule needs a second user, and a request that the page never sends that user: bob's DELETE.
4. post, in app.js, sends whatever the Message box holds,
an empty box included:
64 65 66 67 68 69 70 71 72 73 74 | |
On the server, post hands the message field to Book.add:
292 293 294 295 296 297 298 299 | |
Suppose post began with a check that returns without sending
when the box is empty, and suppose the server did not check. What
request stores an empty message in a book anyway? What does the
finished program do with an empty message today? Where does a check
for an empty message belong?
Answer
-
One
curlline stores it. No page sends the request, so the page's check never runs. Start the finished program fresh, and ada posts a message field with nothing in it:$ curl -H 'Tailscale-User-Login: ada@example.com' -d 'message=' http://localhost:9331/api/books/ada@example.com/messages ["ada@example.com: "]The field
message=has nothing after the=, so the message is the empty string.posthands that toadd, and line 298 stores ada's login, a colon, a space, and nothing more. Afetchtyped at the console, as in Who may do what?, could send the same field from the page itself. -
The finished program stores an empty message today, and its specification allows that. The run above is the finished program as it is. Its page sends an empty box as it is, and its server stores what comes.
add's specification, on lines 292 to 296, adds "the message", and says nothing against an empty one. So today an empty message is allowed. A rule against one would be a new rule, and a specification would have to state it. -
The check belongs on the server. The reason is the one in Who may do what?: a visitor can go around a check in the page, so only the server's check decides what goes into the book.
curl, above, goes around the page with no browser at all. -
On the server, the check belongs in
Book. The argument is the one in Where the check lives. Line 298 is the one line that adds tomessages. So a check inBook.addis one that every post passes through, from today's handler and from any handler written later.add's specification would then say what it does with an empty message, asdelete's says what it does when the asker is not the owner. The page's check can stay, to spare the visitor the round trip.
Further reading
- The calls. The JDK's pages for
Headers, whose names match without regard to case, and whosegetFirstreturns a header's first value, ornull.User.fromcalls it on whatHttpExchange.getRequestHeadersreturns. - Authentication and authorization.
- Saltzer and Schroeder, The Protection of Information in Computer Systems (1975), whose section I.A.3 gives eight examples of design principles for protection, complete mediation among them.
- Morris and Thompson, Password Security: A Case History (1979), on how Unix came to keep each password salted and made slow, a design that "was the result of countering observed attempts to penetrate the system."
- Bonneau, Herley, van Oorschot, and Stajano, The Quest to Replace Passwords (2012), which compares schemes proposed to replace passwords. It finds that, of the schemes it rates, "every scheme does worse than passwords on deployability". It suggests that the cost of moving off passwords may best explain why they are staying.
- OWASP's cheat sheets on Authentication, Password Storage, Session Management, and Forgot Password state current rules for each item on the list in Who is asking. OWASP's Authorization sheet says where an authorization check belongs. Broken Access Control is first in OWASP's Top 10 for 2021 and again for 2025.
- NIST, SP 800-63B-4, Digital Identity Guidelines: Authentication and Authenticator Management (July 2025), whose section 3.1.1.2 states the rules for passwords.
- Tailscale.
- Tailscale Serve, on passing requests from a tailnet to a server on your machine. Its section "Identity headers" lists the headers Serve adds, and says that Serve removes copies a client sends.
- Tailscale identity, on how Tailscale hands authentication to an identity provider.
- The
tailscale servecommand's reference.
- One becoming many.
- Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules" (1972), which was Reading 3: begin with the decisions likely to change, and hide each one in a module.
- Chong, Carraro, and Wolter, Multi-Tenant Data Architecture (Microsoft, 2006), on how a program that many customers share can keep their data. In one of its three approaches, "a Tenant ID column associates every record with the appropriate tenant."
- Microsoft's Tenancy models for a multitenant solution (2025): "You need to first define a tenant for your organization." It says that when tenants share one deployment, the application's code and a tenant identifier typically keep each tenant's data apart.
- The zero-one-infinity rule, in the Jargon File: "Allow none of foo, one of foo, or any number of foo." Here foo stands for any kind of thing. It is folklore. Willem van der Poel is credited with it, and Bruce MacLennan has claimed it too. No print source we read settles which. Marc Brooker's The Zero, One, Infinity Disease (2015) adds a caution: "The value is lost when the word arbitrary is forgotten."
-
Could a tool have made the list? Only part of it. In
field/Guestbook.java, a copy with line 24 changed so that the field holds a map from aStringto aBook,javacpoints at lines 57 and 74, the two lines of code that use the field. It points at nothing else on the list. A comment, a path kept in aString, a page, and tests are not variables whose type changed. ↩ -
David L. Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules", Communications of the ACM (1972). He proposes that "one begins with a list of difficult design decisions or design decisions which are likely to change. Each module is then designed to hide such a decision from the others." ↩
-
Each signature that changed has callers to fix, and
javacpoints at each call that no longer fits. The page and the tests get no such help, since they are not in whatjavaccompiles. ↩ -
Robert Morris and Ken Thompson, Password Security: A Case History, Communications of the ACM 22(11), 1979, tell how Unix came to put "only the encrypted form in the password file". Their word is "encrypted". In their scheme, the password is the key that encrypts a constant, the encryption is iterated 25 times to make it slow, and a 12-bit random salt is appended to the password first. Today such a function is called a password hash. OWASP's Password Storage Cheat Sheet gives the current rules: "Passwords should never be stored in plain text," and "A unique salt must be added to each password to prevent attackers from using precomputed lookup tables". NIST's SP 800-63B-4, Digital Identity Guidelines: Authentication and Authenticator Management (2025), section 3.1.1.2, says the same: "Passwords SHALL be salted and hashed using a suitable password hashing scheme." ↩
-
OWASP's Authentication Cheat Sheet: "The login page and all subsequent authenticated pages must be exclusively accessed over TLS or other strong transport." TLS is the encryption under HTTPS. ↩
-
OWASP's Session Management Cheat Sheet: "Session identifiers must have at least 64 bits of entropy to prevent brute-force session guessing attacks." It says of the session's number that "it is sent on every HTTP request", and of cookies that they "are one of the most extensively used session ID exchange mechanisms". ↩
-
The Session Management sheet: "it is mandatory to set expiration timeouts for every session," and at logout "the web application must invalidate the session at least on server side." The Authentication sheet describes login throttling, "a security mechanism used to prevent an attacker from making too many attempts at guessing a password". NIST's SP 800-63B-4 says "Verifiers SHALL implement a rate-limiting mechanism". OWASP's Forgot Password Cheat Sheet covers the way back in. ↩
-
Jerome H. Saltzer and Michael D. Schroeder, The Protection of Information in Computer Systems, Proceedings of the IEEE 63(9), 1975, section I.A.3, of the principle of complete mediation. ↩
-
OWASP's Forgot Password Cheat Sheet: "Even though this functionality looks straightforward and easy to implement, it is a common source of vulnerabilities, such as the renowned user enumeration attack." ↩
-
N. Sakimura, J. Bradley, M. Jones, B. de Medeiros, and C. Mortimore, OpenID Connect Core 1.0 incorporating errata set 2 (2023), whose abstract says it "enables Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server". Google's OpenID Connect page: "Google's OAuth 2.0 APIs support authentication and authorization, conforming to the OpenID Connect specification". ↩
-
OWASP's Session Management Cheat Sheet, of the session code that web frameworks provide: "It is recommended to use these built-in frameworks versus building a home made one from scratch". ↩
-
Tailscale's documentation, Tailscale identity: "When a Tailscale user logs in to a new device (that is, a device not previously joined to a tailnet), an identity provider authenticates the user ... Tailscale itself is not an identity provider". ↩
-
Tailscale's documentation, Tailscale Serve: Serve routes "traffic from other devices on your Tailscale network (known as a tailnet) to a local service running on your device." Its example,
tailscale serve 3000, prints "Available within your tailnet:" and an address ending ints.net, and the page calls Serve "available only within the tailnet". Thetailscale servereference says that "HTTPS traffic uses an automatically provisioned TLS certificate." ↩ -
Tailscale's Serve documentation, under "Identity headers": Serve "adds a few Tailscale identity headers to the request sent to your backend." ↩
-
Tailscale's Serve documentation: "If Serve finds the following headers on an incoming request, it will remove them for security reasons, to avoid header spoofing." In Tailscale's source at tag v1.104.7,
addTailscaleIdentityHeadersdeletesTailscale-User-Loginand its sibling headers from the request it will send on, before it sets any of them. ↩ -
Tailscale's Serve documentation, under "Identity headers": "Although identity headers are only populated for tailnet traffic, this includes traffic from external users who have accepted a share of your device. For example, if you share a device with a friend and have it configured with a Serve proxy, Tailscale populates the identity headers when your friend visits the Serve URL." And: "Funnel traffic, which is publicly available, does not include identity headers." ↩
-
A third way stays in the browser and skips the button. At the console, bob types the request that
removewould have sent:(await fetch(url + "/0", { method: "DELETE" })).status. The console prints 200, and the oldest message is gone.urlis the page's own constant, from line 15. ↩ -
OWASP's Authorization Cheat Sheet, under "Verify that Authorization Checks are Performed in the Right Location": "Developers must never rely on client-side access control checks. While such checks may be permissible for improving the user experience, they should never be the decisive factor in granting or denying access to a resource; client-side logic is often easy to bypass." ↩
-
R. Fielding, M. Nottingham, and J. Reschke, eds., HTTP Semantics, RFC 9110 (2022), section 15.5.4: "The 403 (Forbidden) status code indicates that the server understood the request but refuses to fulfill it." ↩
-
The page keeps its check. Without it, the page would draw a Delete button beside every message for every user, and a button that always fails helps nobody. So the rule is written twice: in JavaScript, in
app.js, to decide which buttons to draw, and in Java, on the server, to decide which deletes to carry out. Only the check on the server decides. ↩ -
Saltzer and Schroeder (1975), section I.A.3, call this complete mediation, the third of their design principles for protection: "Every access to every object must be checked for authority." ↩
-
In a copy of the finished program whose line 125 is
book.delete(index);,javacreports that "method delete in class Book cannot be applied to given types", withrequired: User,intandfound: int. ↩ -
NotOwnerExceptionextendsException, so it is a checked exception, which suits a problem "a careful client should expect and recover from". Why not a precondition, such as "requires asker to be the book's owner"? A precondition is the client's promise, and the lecture on errors said what follows when a client breaks it: "the method may do anything at all and still satisfy its specification." A handler that forgot to compare would then delete for anyone, and the rule would be back in every handler. ↩ -
RFC 9110, section 15.5.5: "The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists." ↩
-
handleanswers/with the status 303, See Other, and a header,Location: /ada@example.comfor ada. RFC 9110, section 15.4.4, says that a 303 "is redirecting the user agent to a different resource, as indicated by a URI in the Location header field." Chrome follows the redirect, so ada's Chrome, opened at/, ends at her own book. ↩